一、k8s 对象介绍

1.简介

  • “对象”是指 Kubernetes 系统中的一个抽象概念,表示集群中所管理的实体
  • Kubernetes 对象用于定义和描述应用程序的状态、配置以及其所需的资源
  • 每个对象都被配置为特定的资源,Kubernetes 会根据定义的期望状态(如部署的 Pod 数量、资源需求等)自动管理并确保集群中的实际状态与期望状态一致
  • k8s里所有的功能都对应着对象,对象由api server实现,放在api server里
  • Kubernetes 对象的定义通常是声明式的,即你告诉 Kubernetes 你希望集群中的对象是什么样子的,而 Kubernetes 会自动处理底层的细节,通过yaml文件

2.查看对象

[root@localhost ~]# kubectl api-resources
NAME                                SHORTNAMES   APIVERSION                          NAMESPACED   KIND
bindings                                         v1                                  true         Binding
componentstatuses                   cs           v1                                  false        ComponentStatus
configmaps                          cm           v1                                  true         ConfigMap
endpoints                           ep           v1                                  true         Endpoints
events                              ev           v1                                  true         Event
limitranges                         limits       v1                                  true         LimitRange
namespaces                          ns           v1                                  false        Namespace
nodes                               no           v1                                  false        Node
persistentvolumeclaims              pvc          v1                                  true         PersistentVolumeClaim
persistentvolumes                   pv           v1                                  false        PersistentVolume
pods                                po           v1                                  true         Pod
podtemplates                                     v1                                  true         PodTemplate
replicationcontrollers              rc           v1                                  true         ReplicationController
resourcequotas                      quota        v1                                  true         ResourceQuota
secrets                                          v1                                  true         Secret
serviceaccounts                     sa           v1                                  true         ServiceAccount
services                            svc          v1                                  true         Service
mutatingwebhookconfigurations                    admissionregistration.k8s.io/v1     false        MutatingWebhookConfiguration
validatingadmissionpolicies                      admissionregistration.k8s.io/v1     false        ValidatingAdmissionPolicy
validatingadmissionpolicybindings                admissionregistration.k8s.io/v1     false        ValidatingAdmissionPolicyBinding
validatingwebhookconfigurations                  admissionregistration.k8s.io/v1     false        ValidatingWebhookConfiguration
customresourcedefinitions           crd,crds     apiextensions.k8s.io/v1             false        CustomResourceDefinition
apiservices                                      apiregistration.k8s.io/v1           false        APIService
controllerrevisions                              apps/v1                             true         ControllerRevision
daemonsets                          ds           apps/v1                             true         DaemonSet
deployments                         deploy       apps/v1                             true         Deployment
replicasets                         rs           apps/v1                             true         ReplicaSet
statefulsets                        sts          apps/v1                             true         StatefulSet
selfsubjectreviews                               authentication.k8s.io/v1            false        SelfSubjectReview
tokenreviews                                     authentication.k8s.io/v1            false        TokenReview
localsubjectaccessreviews                        authorization.k8s.io/v1             true         LocalSubjectAccessReview
selfsubjectaccessreviews                         authorization.k8s.io/v1             false        SelfSubjectAccessReview
selfsubjectrulesreviews                          authorization.k8s.io/v1             false        SelfSubjectRulesReview
subjectaccessreviews                             authorization.k8s.io/v1             false        SubjectAccessReview
horizontalpodautoscalers            hpa          autoscaling/v2                      true         HorizontalPodAutoscaler
cronjobs                            cj           batch/v1                            true         CronJob
jobs                                             batch/v1                            true         Job
certificatesigningrequests          csr          certificates.k8s.io/v1              false        CertificateSigningRequest
leases                                           coordination.k8s.io/v1              true         Lease
bgpconfigurations                                crd.projectcalico.org/v1            false        BGPConfiguration
bgpfilters                                       crd.projectcalico.org/v1            false        BGPFilter
bgppeers                                         crd.projectcalico.org/v1            false        BGPPeer
blockaffinities                                  crd.projectcalico.org/v1            false        BlockAffinity
caliconodestatuses                               crd.projectcalico.org/v1            false        CalicoNodeStatus
clusterinformations                              crd.projectcalico.org/v1            false        ClusterInformation
felixconfigurations                              crd.projectcalico.org/v1            false        FelixConfiguration
globalnetworkpolicies                            crd.projectcalico.org/v1            false        GlobalNetworkPolicy
globalnetworksets                                crd.projectcalico.org/v1            false        GlobalNetworkSet
hostendpoints                                    crd.projectcalico.org/v1            false        HostEndpoint
ipamblocks                                       crd.projectcalico.org/v1            false        IPAMBlock
ipamconfigs                                      crd.projectcalico.org/v1            false        IPAMConfig
ipamhandles                                      crd.projectcalico.org/v1            false        IPAMHandle
ippools                                          crd.projectcalico.org/v1            false        IPPool
ipreservations                                   crd.projectcalico.org/v1            false        IPReservation
kubecontrollersconfigurations                    crd.projectcalico.org/v1            false        KubeControllersConfiguration
networkpolicies                                  crd.projectcalico.org/v1            true         NetworkPolicy
networksets                                      crd.projectcalico.org/v1            true         NetworkSet
tiers                                            crd.projectcalico.org/v1            false        Tier
endpointslices                                   discovery.k8s.io/v1                 true         EndpointSlice
events                              ev           events.k8s.io/v1                    true         Event
flowschemas                                      flowcontrol.apiserver.k8s.io/v1     false        FlowSchema
prioritylevelconfigurations                      flowcontrol.apiserver.k8s.io/v1     false        PriorityLevelConfiguration
ingressclasses                                   networking.k8s.io/v1                false        IngressClass
ingresses                           ing          networking.k8s.io/v1                true         Ingress
networkpolicies                     netpol       networking.k8s.io/v1                true         NetworkPolicy
runtimeclasses                                   node.k8s.io/v1                      false        RuntimeClass
poddisruptionbudgets                pdb          policy/v1                           true         PodDisruptionBudget
adminnetworkpolicies                anp          policy.networking.k8s.io/v1alpha1   false        AdminNetworkPolicy
clusterrolebindings                              rbac.authorization.k8s.io/v1        false        ClusterRoleBinding
clusterroles                                     rbac.authorization.k8s.io/v1        false        ClusterRole
rolebindings                                     rbac.authorization.k8s.io/v1        true         RoleBinding
roles                                            rbac.authorization.k8s.io/v1        true         Role
priorityclasses                     pc           scheduling.k8s.io/v1                false        PriorityClass
csidrivers                                       storage.k8s.io/v1                   false        CSIDriver
csinodes                                         storage.k8s.io/v1                   false        CSINode
csistoragecapacities                             storage.k8s.io/v1                   true         CSIStorageCapacity
storageclasses                      sc           storage.k8s.io/v1                   false        StorageClass
volumeattachments                                storage.k8s.io/v1                   false        VolumeAttachment
[root@localhost ~]# 

3.什么是API对象

  • 在 Kubernetes 中,API 对象(API Object)是集群中可管理的实体,是 Kubernetes 的核心概念之一
  • 简单来说,一切你在 Kubernetes 中操作的资源——Pod、Service、Deployment 等——都是 API 对象

Kubernetes 的 API 对象 是通过 Kubernetes API(REST API)声明和管理的资源。每个对象都有三个关键特征:

  1. 类型(Typemeta):对象的类型,例如 Pod、Service、Deployment 等。
  2. 元数据(Metadata):描述对象的名称、命名空间、标签、注解等信息。
  3. 规范(Spec):用户期望的状态(desired state),例如一个 Pod 想运行哪些容器。
  4. 状态(Status):系统实际的状态(current state),由 Kubernetes 控制器维护,例如 Pod 是否运行成功。

结构特征:

# typemeta
apiVersion: v1           # core核心组或group/v1  API 版本
kind: Pod                # 对象类型
metadata:                # 元数据
  name: my-pod           # 用户自定义
  namespace: default     # 命名空间,逻辑隔离,软隔离
  labels:                # 标签,方便查找
    app: myapp
  annotations:           # 附加功能
    key: values     
spec:                    # 用户期望状态
  containers:
  - name: nginx
    image: nginx:1.23
status:                  # 当前状态,由系统自动生成,kubelet定时上报
  phase: Running

补充——Group:将对象依据功能范围归入不同的分组,比如把支撑最基本功能的对象加入core组,把与应用部署相关的对象放入apps组

例:输出一个 YAML 配置文件,显示创建该资源所需的配置内容

[root@localhost ~]# kubectl run ngx --image=nginx:1.22.1 --dry-run=client -o yaml
apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: null
  labels:
    run: ngx
  name: ngx
spec:
  containers:
  - image: nginx:1.22.1
    name: ngx
    resources: {}
  dnsPolicy: ClusterFirst
  restartPolicy: Always
status: {}

4.常用命令

[root@localhost ~]# kubectl explain pod
KIND:       Pod
VERSION:    v1

二、Pod

1.简介

  • Pod:调度的最小单位
  • 一个Pod中多个容器可以共享网络、共享存储
  • 一个Pod里面最少也要跑两个容器

2.使用 YAML 描述 Pod

用命令 kubectl explain 来查看资源对象的详细说明,所以接下来我们一起看看写 YAML 时 Pod 里的一些常用字段:

[root@localhost ~]# kubectl explain pod
KIND:       Pod
VERSION:    v1

DESCRIPTION:
    Pod is a collection of containers that can run on a host. This resource is
    created by clients and scheduled onto hosts.
    
FIELDS:
  apiVersion	<string>
    APIVersion defines the versioned schema of this representation of an object.
    Servers should convert recognized schemas to the latest internal value, and
    may reject unrecognized values. More info:
    https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources

  kind	<string>
    Kind is a string value representing the REST resource this object
    represents. Servers may infer this from the endpoint the client submits
    requests to. Cannot be updated. In CamelCase. More info:
    https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds

  metadata	<ObjectMeta>
    Standard object's metadata. More info:
    https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata

  spec	<PodSpec>
    Specification of the desired behavior of the pod. More info:
    https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status

  status	<PodStatus>
    Most recently observed status of the pod. This data may not be up to date.
    Populated by the system. Read-only. More info:
    https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status

注:因为 Pod 也是 API 对象,所以它也必然具有 apiVersion、kind、metadata、spec 这四个基本组成部分。​“apiVersion”和“kind”这两个字段很简单,对于 Pod 来说分别是固定的值 v1 和 Pod,而一般来说,“metadata”里应该有 name 和 labels 这两个字段。​
下面这段 YAML 代码就描述了一个简单的 Pod,名字是“busy-pod”,再附加上一些标签:

apiVersion: v1​
kind: Pod​
metadata:​
  name: busy-pod​
  labels:​
    owner: xxhf​
    env: dev​
    region: beijing​
    tier: back

“containers”是一个数组,里面的每一个元素又是一个 container 对象,也就是容器。​
和 Pod 一样,container 对象也必须要有一个 name 表示名字,然后当然还要有一个 image 字段来说明它使用的镜像,这两个字段是必须要有的,否则 Kubernetes 会报告数据验证错误

container 对象常用字段:

  • ports:列出容器对外暴露的端口,和 Docker 的 -p 参数有点像。​
  • imagePullPolicy:指定镜像的拉取策略,可以是 Always/Never/IfNotPresent,一般默认是 IfNotPresent,也就是说只有本地不存在才会远程拉取镜像,可以减少网络消耗。​
  • env:定义 Pod 的环境变量,和 Dockerfile 里的 ENV 指令类似。​
  • command:定义容器启动时要执行的命令,相当于 Dockerfile 里的 ENTRYPOINT 指令。​
  • args:它是 command 运行时的参数,相当于 Dockerfile 里的 CMD 指令,这两个命令和Docker 的含义不同,要特别注意。

现在我们来编写“busy-pod”的 spec 部分,添加 env、command、args 等字段:

spec:​
  containers:​
  - image: busybox:latest​
    name: busy​
    imagePullPolicy: IfNotPresent​
    env:​
      - name: name​
        value: "xinxianghf"​
      - name: address​
        value: "beijing"​
    command:​
      - /bin/echo​
    args:​
      - "NAME=$(name), ADDRESS=$(address)"

# 这里我们为 Pod 指定使用镜像 busybox:latest,拉取策略是 IfNotPresent ,然后定义了 name 和 address 两个环境变量,启动命令是 /bin/echo,参数里输出刚才定义的环境变量

完整的 YAML 描述:

apiVersion: v1​
kind: Pod​
​
metadata:​
  name: busy-pod​
  labels:​
    owner: xxhf​
    env: dev​
    region: beijing​
    tier: back​
    ​
spec:​
  containers:​
  - image: busybox:latest​
    name: busy​
    imagePullPolicy: IfNotPresent​
    env:​
      - name: name​
        value: "xinxianghf"​
      - name: address​
        value: "beijing"​
    command:​
      - /bin/echo​
    args:​
      - "NAME=$(name), ADDRESS=$(address)"

3.使用 kubectl 操作 Pod

配置文件YAML:

[root@localhost 04-pod]# cat busy-pod.yaml 
apiVersion: v1
kind: Pod
metadata:
  #namespace: dev-xxhf
  name: busy-pod
  namespace: default
  labels:
    owner: xxhf
    env: dev 
    region: beijing
    tier: backend 
spec:
  #restartPolicy: OnFailure
  containers:
  - image: registry.cn-beijing.aliyuncs.com/xxhf/busybox:latest 
    name: busy
    imagePullPolicy: IfNotPresent
    env:
      - name: name
        value: "xinxianghf"
      - name: address
        value: "beijing"
    command:
      - /bin/echo
    args:
      - "NAME=$(name), ADDRESS=$(address)"

将YAML发送给k8s:

# 跟 etcd 中比较 ,如果配置有变化 就自动  更新
[root@localhost 04-pod]# kubectl apply -f busy-pod.yaml 
pod/busy-pod created

[root@localhost 04-pod]# kubectl  get pod
名字        就绪    状态      重启次数   创建时间
NAME       READY   STATUS    RESTARTS   AGE
busy-pod   0/1     Pending   0          29s

注:k8s 所有的容器 都是在后台容器;且一个容器运行起来之后是不能改名的

# 不能创建已存在的,建议使用apply
[root@localhost 04-pod]# kubectl create -f nginx-pod.yaml 
Error from server (AlreadyExists): error when creating "nginx-pod.yaml": pods "nginx-pod" already exists

删除资源:

# 默认省略了-n选项,即:-n default
[root@localhost 04-pod]# kubectl delete -f busy-pod.yaml 
pod "busy-pod" deleted

[root@localhost 04-pod]# kubectl  get pod
No resources found in default namespace.

# 强制删除 
kubectl  delete pods nginx-01 nginx-02 nginx-03 nginx-04  --force --grace-period 0

查看Pod启动过程中的详细信息:

# 移除控制平面污点
[root@localhost 04-pod]# kubectl taint nodes --all node-role.kubernetes.io/control-plane-

[root@localhost 04-pod]# kubectl describe  pod busy-pod
Name:             busy-pod
Namespace:        default
Priority:         0
Service Account:  default
Node:             master/192.168.5.110
Start Time:       Mon, 17 Nov 2025 20:42:20 +0800
Labels:           env=dev
                  owner=xxhf
                  region=beijing

Events:
  类型      原图                               来自哪个组件        详细信息
  Type     Reason            Age              From               Message
  ----     ------            ----             ----               -------
  Warning  FailedScheduling  114s             default-scheduler  0/2 nodes are available: 1 node(s) had untolerated taint {node-role.kubernetes.io/control-plane: }, 1 node(s) had untolerated taint {node.kubernetes.io/unreachable: }. preemption: 0/2 nodes are available: 2 Preemption is not helpful for scheduling.
  Normal   Scheduled         8s               default-scheduler  Successfully assigned default/busy-pod to master
  Normal   Pulling           7s               kubelet            Pulling image "registry.cn-beijing.aliyuncs.com/xxhf/busybox:latest"
  Normal   Pulled            3s               kubelet            Successfully pulled image "registry.cn-beijing.aliyuncs.com/xxhf/busybox:latest" in 3.692s (3.692s including waiting). Image size: 2221934 bytes.
  Normal   Created           2s (x2 over 3s)  kubelet            Created container: busy
  Normal   Started           2s (x2 over 3s)  kubelet            Started container busy
  Normal   Pulled            2s               kubelet            Container image "registry.cn-beijing.aliyuncs.com/xxhf/busybox:latest" already present on machine
  Warning  BackOff           0s (x2 over 1s)  kubelet            Back-off restarting failed container busy in pod busy-pod_default(c75e2115-4c95-42dd-a6c5-1d550dc1c23c)
[root@localhost 04-pod]#
  • 对于这个 busy-pod,因为它只执行了一条 echo 命令就退出了,而 Kubernetes 默认会重启Pod,所以就会进入一个反复停止 - 启动的循环错误状态

可以使用容器重启策略解决(下方会提到):

[root@localhost 04-pod]# kubectl get pod
NAME             READY   STATUS      RESTARTS       AGE
busy-pod         0/1     Completed   0              12s

注:Completed,即任务已完成,将不会再一直重启

或查看容器日志:

[root@localhost 04-pod]# kubectl  logs -f busy-pod

注:Events事件信息保存在etcd数据库中,默认只保存一个小时;但在工作中一般会统一收集到日志系统中保存;Event类型做告警

4.启动 Nginx 服务

配置文件:

[root@localhost 04-pod]# cat nginx-pod.yaml 
apiVersion: v1
kind: Pod
metadata:
  name: nginx-pod
    #namespace: dev-12305 
  labels:
    owner: xxhf-beijing
    env: fat 
    language: python 
spec:
  containers:
  - image: registry.cn-beijing.aliyuncs.com/xxhf/nginx:1.22.1 
    name: nginx-01
    imagePullPolicy: IfNotPresent 
    ports:
    - containerPort: 80

启动资源:

[root@localhost 04-pod]# kubectl apply -f nginx-pod.yaml 
pod/nginx-pod created

[root@localhost 04-pod]# kubectl  get pod
NAME        READY   STATUS             RESTARTS        AGE
busy-pod    0/1     CrashLoopBackOff   8 (2m10s ago)   19m
nginx-pod   1/1     Running            0               32s

查看详细信息:

[root@localhost 04-pod]# kubectl  get pod -o wide
                                                             Pod的ip         被调度到的节点
NAME        READY   STATUS             RESTARTS      AGE     IP              NODE     NOMINATED NODE   READINESS GATES
busy-pod    0/1     CrashLoopBackOff   9 (71s ago)   23m     172.17.219.71   master   <none>           <none>
nginx-pod   1/1     Running            0             4m34s   172.17.219.72   master   <none>           <none>
[root@localhost 04-pod]#
# 实时显示资源的变化情况
[root@localhost 04-pod]# kubectl  get pod -w
NAME        READY   STATUS             RESTARTS        AGE
busy-pod    0/1     CrashLoopBackOff   9 (2m43s ago)   25m
nginx-pod   1/1     Running            0               6m6s

进入到资源当中:

[root@localhost 04-pod]# kubectl exec -it nginx-pod -- sh
# exit
[root@localhost 04-pod]# 

把本地文件拷贝进 Pod:

[root@localhost 04-pod]# kubectl cp nginx-pod.yaml nginx-pod:/tmp/
[root@localhost 04-pod]# kubectl exec -it nginx-pod -- ls /tmp/
nginx-pod.yaml

5.使用标签组织

原因:对于微服务架构,部署的微服务数量可以轻松超过20个甚至更多。这些组件可能是副本(部署同一组件的多个副本)和多个不同的发布版本(stable、beta、canary等)同时运行。这样一来可能会导致我们在系统中拥有数百个pod,如果没有可以有效组织这些组件的机制,将会导致产生巨大的混乱。

我们需要一种能够基于任意标准将pod组织成更小群体的方式,希望通过一次操作对属于某个组的所有pod进行操作,即通过标签来组织pod和所有其他Kubernetes对象

(1)标签简介

  • 标签不仅可以组织pod,也可以组织所有其他的Kubernetes资源
  • 可以附加到资源的任意键值对,用以选择具有该确切标签的资源
  • 只要标签的key在资源内是唯一的,一个资源便可以拥有多个标签
  • 通常在我们创建资源时就会将标签附加到资源上,但之后我们也可以再添加其他标签,或者修改现有标签的值,而无须重新创建资源

(2)查看pod标签

[root@localhost 04-pod]# kubectl get pod --show-labels
NAME        READY   STATUS             RESTARTS         AGE   LABELS
busy-pod    0/1     CrashLoopBackOff   14 (2m56s ago)   51m   env=dev,owner=xxhf,region=beijing,tier=backend
nginx-pod   1/1     Running            0                31m   env=fat,language=python,owner=xxhf-beijing

# 只列出某些标签
[root@localhost 04-pod]# kubectl  get pods -L env
NAME        READY   STATUS             RESTARTS         AGE   ENV
busy-pod    0/1     CrashLoopBackOff   14 (3m31s ago)   51m   dev
nginx-pod   1/1     Running            0                32m   fat

(3)修改pod标签

# 添加
[root@localhost 04-pod]# kubectl  get pods  nginx-pod --show-labels
NAME        READY   STATUS    RESTARTS   AGE   LABELS
nginx-pod   1/1     Running   0          33m   env=fat,language=python,owner=xxhf-beijing
[root@localhost 04-pod]# kubectl  label  pod nginx-pod tier=front
pod/nginx-pod labeled
[root@localhost 04-pod]# kubectl  get pods  nginx-pod --show-labels
NAME        READY   STATUS    RESTARTS   AGE   LABELS
nginx-pod   1/1     Running   0          34m   env=fat,language=python,owner=xxhf-beijing,tier=front

# 修改
[root@localhost 04-pod]# kubectl label pod nginx-pod  env=production --overwrite
pod/nginx-pod labeled
[root@localhost 04-pod]# kubectl  get pods  nginx-pod --show-labels
NAME        READY   STATUS    RESTARTS   AGE   LABELS
nginx-pod   1/1     Running   0          35m   env=production,language=python,owner=xxhf-beijing,tier=front

# 删除
[root@localhost ~]# kubectl  label  pod nginx-pod  tier-
pod/nginx-pod unlabeled

6.标签选择运算符

注:目前支持两种类型的选择算符:基于等值的和基于集合的

基于等值​
基于等值或基于不等值的需求允许按标签键和值进行过滤。 匹配对象必须满足所有指定的标签约束,尽管它们也可能具有其他标签。 可接受的运算符有 =、== 和 != 三种。 前两个表示相等(并且是同义词),而后者表示不相等。例如:​

[root@localhost ~]# kubectl  get pods --show-labels   -l env=dev
NAME       READY   STATUS             RESTARTS        AGE   LABELS
busy-pod   0/1     CrashLoopBackOff   25 (2m2s ago)   12h   env=dev,owner=xxhf,region=beijing,tier=backend
[root@localhost ~]# kubectl  get pods --show-labels   -l env!=dev
NAME        READY   STATUS    RESTARTS        AGE   LABELS
nginx-pod   1/1     Running   1 (9m12s ago)   11h   env=production,language=python,owner=xxhf-beijing
复制
environment = production​
tier != frontend​

​基于集合​
基于集合的标签需求允许你通过一组值来过滤键。 支持三种操作符:in、notin 和 exists(只可以用在键标识符上)。例如:​

[root@localhost ~]# kubectl  get pods --show-labels   -l 'env in (dev,production)'
NAME        READY   STATUS             RESTARTS         AGE   LABELS
busy-pod    0/1     CrashLoopBackOff   25 (4m54s ago)   12h   env=dev,owner=xxhf,region=beijing,tier=backend
nginx-pod   1/1     Running            1 (11m ago)      11h   env=production,language=python,owner=xxhf-beijing

[root@localhost ~]# kubectl  get pods --show-labels   -l owner
NAME        READY   STATUS             RESTARTS       AGE   LABELS
busy-pod    0/1     CrashLoopBackOff   26 (80s ago)   12h   env=dev,owner=xxhf,region=beijing,tier=backend
nginx-pod   1/1     Running            1 (12m ago)    11h   env=production,language=python,owner=xxhf-beijing
[root@localhost ~]# kubectl  get pods --show-labels   -l '!owner'
No resources found in default namespace.
environment in (production, qa)​
tier notin (frontend, backend)​
    partition​
!partition​

7.使用命名空间组织

  • ​Kubernetes 的命名空间并不是一个实体对象,只是一个逻辑上的概念
  • 可以把集群切分成一个个彼此独立的区域,然后我们把对象放到这些区域里,就实现了类似容器技术里 namespace 的隔离效果
  • 应用只能在自己的命名空间里分配资源和运行,不会干扰到其他命名空间里的应用

命名空间类型:

  • 系统级命名空间:K8s 集群默认创建的命名空间,用来隔离系统级的对象和业务对​象
  • 用户自定义命名空间

(1)查看命名空间

[root@localhost ~]# kubectl get ns
NAME              STATUS   AGE
default           Active   3d13h    # 默认命名空间
kube-node-lease   Active   3d13h    # 和集群扩展相关的命名空间(预留)
kube-public       Active   3d13h    # 开放命名空间(预留)
kube-system       Active   3d13h    # 关键组件的命名空间
[root@localhost ~]# kubectl get pod -n kube-system
NAME                                       READY   STATUS    RESTARTS      AGE
calico-kube-controllers-77969b7d87-75wvq   1/1     Running   2 (21m ago)   3d12h
calico-node-l7xxv                          1/1     Running   1 (12h ago)   3d12h
calico-node-zdtq9                          0/1     Running   2 (21m ago)   3d12h
coredns-6766b7b6bb-c8ldf                   1/1     Running   2 (21m ago)   3d13h
coredns-6766b7b6bb-vhfqf                   1/1     Running   2 (21m ago)   3d13h
etcd-master                                1/1     Running   2 (21m ago)   3d13h
kube-apiserver-master                      1/1     Running   2 (21m ago)   3d13h
kube-controller-manager-master             1/1     Running   2 (21m ago)   3d13h
kube-proxy-q6fg8                           1/1     Running   2 (21m ago)   3d13h
kube-proxy-t8gsz                           1/1     Running   1 (12h ago)   3d13h
kube-scheduler-master                      1/1     Running   2 (21m ago)   3d13h

(2)创建命名空间

[root@localhost ~]# kubectl create namespace  dev-ns
namespace/dev-ns created
[root@localhost ~]# kubectl get ns
NAME              STATUS   AGE
default           Active   3d13h
dev-ns            Active   2s
kube-node-lease   Active   3d13h
kube-public       Active   3d13h
kube-system       Active   3d13h

(3)获取命名空间详细信息

[root@localhost ~]# kubectl describe  ns dev-ns
Name:         dev-ns
Labels:       kubernetes.io/metadata.name=dev-ns
Annotations:  <none>
Status:       Active

No resource quota.

No LimitRange resource.

(4)将对象放入命名空间

[root@localhost 04-pod]# kubectl  -n dev-ns  apply -f nginx-pod.yaml 
pod/nginx-pod created
[root@localhost 04-pod]# kubectl  -n dev-ns  get pods
NAME        READY   STATUS    RESTARTS   AGE
nginx-pod   1/1     Running   0          10s

注:也可以在yaml中直接指定命名空间

8.Pod 停止和移除

# 按名称删除​
kubectl delete pod nginx-pod​
​
# 使用标签选择器删除​
kubectl  get pods  --show-labels​
kubectl delete pods  -l env=dev ​
​
# 删除命名空间所有 Pod​
kubectl delete namespace  dev-ns​

三、特殊类型的容器

1.Pause 容器

  • pause 容器它为每个pod充当 PID 1,并接收僵尸进程;找 CNI Calico 申请一个 IP 地址
  • 是 pod 中Linux 命名空间共享的基础,在启动时申请命名空间,之后启动的容器加入命名空间,共享网络
  • pause 容器有时候也称为 infra 容器,它与用户容器”捆绑“运行在同一个 Pod 中,最大的作用是维护 Pod 网络协议栈

(1)查看pause容器

[root@localhost 04-pod]# nerdctl -n k8s.io ps | grep nginx
777e207946a3    registry.cn-beijing.aliyuncs.com/xxhf/nginx:1.22.1                         "/docker-entrypoint.…"    15 minutes ago    Up                 k8s://default/nginx-pod/nginx-01
a0c3bac106cb    registry.aliyuncs.com/google_containers/pause:3.8                          "/pause"                  15 minutes ago    Up                 k8s://default/nginx-pod

注:启动一个Pod  可以看到同时启动两个 docker 容器,其中之一就是pause

(2)共享pause网络和 IPC

# 1. 启动 pause 容器
[root@localhost 04-pod]# nerdctl run -d --name pause \
    -p 8880:80 \
    --ipc=shareable \
    registry.aliyuncs.com/google_containers/pause:3.8

# 2. 启动 nginx 共享 pause 的网络和 IPC
[root@localhost 04-pod]# nerdctl run -d --name nginx-pause \
  --net=container:pause \
  --ipc=container:pause \
  --pid=container:pause \
  registry.cn-beijing.aliyuncs.com/xxhf/nginx:1.22.1

# 3. 启动 centos 共享 pause 的网络和 IPC
[root@localhost 04-pod]# nerdctl run -it --name rocky-pause \
  --net=container:pause \
  --ipc=container:pause \
  --pid=container:pause \
  registry.cn-beijing.aliyuncs.com/xxhf/rockylinux:9 sh
sh-5.1# dnf -y install procps-ng

sh-5.1# ps -ef
UID          PID    PPID  C STIME TTY          TIME CMD
65535          1       0  0 08:11 ?        00:00:00 /pause
root           7       0  0 08:13 ?        00:00:00 nginx: master process nginx -g daemon off;
101           34       7  0 08:13 ?        00:00:00 nginx: worker process
101           35       7  0 08:13 ?        00:00:00 nginx: worker process
root          36       0  0 08:18 pts/0    00:00:00 sh
root          90      36  0 08:20 pts/0    00:00:00 ps -ef

sh-5.1# curl http://127.0.0.1
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }

补充:做完实验后,关键组件会出现一个问题

执行以下命令可以解决:

[root@localhost 04-pod]# kubectl set env daemonset/calico-node -n kube-system IP_AUTODETECTION_METHOD=interface=ens160

2.Init Containers

注:Pod 能够具有多个容器,应用运行在容器里面,但是它也可能有一个或多个先于应用容器启动的 Init 容器

(1)init容器特点

  • Init 容器总是运行到成功完成后退出
  • 每个 Init 容器都必须在下一个 Init 容器启动之前成功完成
  • 如果 Pod 的 Init 容器失败,Kubernetes 会不断地重启该 Pod,直到 Init 容器成功为止
  • 如果 Pod 对应的 restartPolicy 为 Never,它不会重新启动

(2)init容器功能

  • 等待其他模块 Ready:可以用来解决服务之间的依赖问题
  • 做初始化配置:比如集群里检测所有已经存在的成员节点
  • 其它场景:如将Pod注册到一个中央数据库、配置中心等

(3)init容器配置

[root@localhost 04-pod]# cat init-pod.yaml 
apiVersion: v1
kind: Pod
metadata:
  name: init-pod
  labels:
    app: init
spec:
  containers:
  - name: init-container
    image: registry.cn-beijing.aliyuncs.com/xxhf/busybox:latest
    command: ['sh', '-c', 'echo The app is running! && sleep 3600']
    imagePullPolicy: IfNotPresent 
  initContainers:
  - name: init-myservice
    image: registry.cn-beijing.aliyuncs.com/xxhf/busybox:latest 
    command: ['sh', '-c', 'until nslookup www.baidu.com; do echo waiting for myservice; sleep 2; done;']
    imagePullPolicy: IfNotPresent 
  - name: init-mydb
    image: registry.cn-beijing.aliyuncs.com/xxhf/busybox:latest
    command: ['sh', '-c', 'until nslookup www.163.com; do echo waiting for mydb; sleep 2; done;']
    imagePullPolicy: IfNotPresent 

若第一个初始化容器无法正常启动,则下一个初始化容器也无法正常运行:

[root@localhost 04-pod]# kubectl apply -f init-pod.yaml 
pod/init-pod3 created

查看日志检查报错信息:

[root@localhost 04-pod]# kubectl logs -f init-pod3 -c init-myservice
nslookup: write to '192.168.111.10': Message too long
;; connection timed out; no servers could be reached

waiting for myservice
nslookup: write to '192.168.111.10': Message too long
;; connection timed out; no servers could be reached

waiting for myservice
nslookup: write to '192.168.111.10': Message too long
;; connection timed out; no servers could be reached

注:如果有多个容器,单独的kubectl logs -f 容器名无法正常显示,需要加-c选项指明容器

如果一切正常运行,则:

[root@localhost 04-pod]# kubectl get pods -w
NAME             READY   STATUS      RESTARTS        AGE

init-pod3        0/1     Init:0/2      0               1s
init-pod3        0/1     Init:1/2      0               4s
init-pod3        0/1     PodInitializing   0               5s
init-pod3        1/1     Running           0               6s

四、Pod 生命周期

1.Pod 阶段

注:Pod 的 status 字段是一个 PodStatus 对象,其中包含一个 phase 字段

phase取值:

  • 挂起(Pending):Pod 信息已经提交给了集群,但是还没有被调度器调度到合适的节点或者 Pod 里的镜像正在下载​
  • 运行中(Running):该 Pod 已经绑定到了一个节点上,Pod 中所有的容器都已被创建。至少有一个容器正在运行,或者正处于启动或重启状态​
  • 成功(Succeeded):Pod 中的所有容器都被成功终止,并且不会再重启​
  • 失败(Failed):Pod 中的所有容器都已终止了,并且至少有一个容器是因为失败终止。也就是说,容器以非0状态退出或者被系统终止​
  • 未知(Unknown):因为某些原因无法取得 Pod 的状态,通常是因为与 Pod 所在主机通信失败导致的,kubelet不上报

2.容器状态

注:容器的状态有三种:Waiting(等待)、Running(运行中)和 Terminated(已终止)

  • Running(运行中):明容器正在执行状态并且没有问题发生
  • Terminated(已终止):处于 Terminated 状态的容器已经开始执行并且或者正常结束或者因为某些原因失败
  • Waiting (等待):如果容器并不处在 Running 或 Terminated 状态之一,它就处在 Waiting 状态。 处于 Waiting 状态的容器仍在运行它完成启动所需要的操作

3.容器重启策略

重启策略说明
Always当容器失效时,由kubelet自动重启该容器, 默认
OnFailure当容器终止运行且退出码不为0时,由kubelet自动重启该容器
Never不论容器运行状态如何,kubelet都不会重启该容器 
  • Pod 的 spec 中包含一个 restartPolicy 字段,其可能取值包括 Always、OnFailure 和 Never,默认值是 Always
  • restartPolicy 适用于 Pod 中的所有容器
  • restartPolicy 仅针对同一节点上 kubelet 的容器重启动作
  • 当 Pod 中的容器退出时,kubelet 会按指数回退方式计算重启的延迟(10s、20s、40s、...),其最长延迟为 5 分钟

4.钩子函数

注:容器生命周期回调(Hook),有两个回调暴露给容器

  • PostStart​:这个回调在容器被创建之后立即被执行。 但是,不能保证回调会在容器入口点(ENTRYPOINT)之前执行
  • PreStop:在容器被终止之前,此回调会被调用。在容器终止之前调用,常用于在容器结束前优雅的释放资源

配置文件:

[root@localhost 04-pod]# cat lifecycle-demo.yaml 
apiVersion: v1
kind: Pod
metadata:
  name: lifecycle-demo
spec:
  containers:
  - name: lifecycle-demo-container
    image: registry.cn-beijing.aliyuncs.com/xxhf/nginx:1.22.1
    lifecycle:
      postStart:
        exec:
          command: ["/bin/sh", "-c", "echo Hello from the postStart handler > /usr/share/message"]
      preStop:
        exec:
          command: ["/usr/sbin/nginx","-s","quit"]

启动服务:

[root@localhost 04-pod]# kubectl apply -f lifecycle-demo.yaml 
pod/lifecycle-demo created

[root@localhost 04-pod]# kubectl exec -it lifecycle-demo -- cat /usr/share/message
Hello from the postStart handler

注:在这个例子中,我们在容器成功启动之后,在 /usr/share/message 里写入了一句“欢迎信息”(即 postStart 定义的操作)。而在这个容器被删除之前,我们则先调用了 nginx 的退出指令(即 preStop 定义的操作),从而实现了容器的“优雅退出”

更多推荐