5. 基础篇-K8S基本概念

错误手册

0. Kubernetes-Error

Master节点

什么是master节点

  1. 整个集群的控制中枢。
  2. master节点中包含了如下组件:
    1. Kube-APIServer
    2. Controller-Manager
    3. Scheduler
    4. Etcd

Kube-APIServer

  1. Kube-APIServer是集群的控制中枢。
  2. 各个模块之间的信息交互都需要经过Kube-APIServer。
  3. Kube-APIServer也是集群管理、资源配置、集群安全机制的入口。

Controller-Manager

  1. Controller-Manager是集群的状态管理器。
  2. Controller-Manager可以保证Pod或其他资源达到期望值。
  3. Controller-Manager也是需要和Kube-APIServer进行通信。
  4. Controller-Manager可以创建、更新、删除它所管理的资源。

Scheduler

  1. Scheduler是集群的调度中心。
  2. Scheduler会根据指定的一些列条件,选择一个或一批最佳节点部署Pod。

Etcd Cluster

  1. Etcd是k8s集群的键值数据库。
  2. k8s中的所有操作都保存到了Etcd中。
  3. 如果集群非常庞大,建议Etcd单独部署,且Etcd需要使用SSD硬盘。
  4. 建议部署奇数个节点,建议3个以上。

Node节点

什么是Node节点

  1. 整个集群的工作节点,可以称为worker节点、node节点、minion节点。
  2. node节点中包含了如下组件:
    1. kubelet
    2. kube-proxy

kubelet

  1. kubelet负责监听节点上Pod的状态。
  2. 同时负责上报节点和节点上Pod的状态。
  3. 负责与master节点通信,并管理节点上的Pod。

Kube-Proxy

  1. 负责Pod之间的通信和负载均衡。
  2. kube-proxy将指定的流量分发到后端正常的机器上。
  3. kube-proxy有两种运行模式:ipvs和iptables,常用的是ipvs模式。

ipvs

  1. 监听master节点增加和删除service及endpoint的消息。
  2. 调用netlink接口创建相应的ipvs规则。
  3. 通过ipvs规则,将流量转发至相应的pod上。

iptables

  1. 监听master节点增加和删除service及endpoint的消息。
  2. 对每个service都会创建一个iptables规则。
  3. 将service的clusterIP代理到后端对应的pod。
  4. iptables规则量过大时,会影响集群的性能。

网络组件

Calico

  1. calico是一个符合CNI标准的网络插件。
  2. calico给每个pod生成一个唯一的IP地址。
  3. calico将每个节点当做一个路由器,从而支持每个pod直接的通信。

CoreDNS

  1. CoreDNS用于k8s集群内部Service的解析。
  2. 可以让Pod把Service名称解析成IP地址。
  3. 然后通过Service的IP地址进行连接到对应的应用上。

Pod

什么是Pod

  1. pod是k8s中最小单元。
  2. pod由一个或多个或一组容器组成。
  3. 每个pod中还包含了一个Pause容器。
  4. Pause容器是pod的父容器,主要负责僵尸进程的回收管理。
  5. Pause容器可以让同一个pod里面的多个容器共享存储、网络、PID、IPC等。
  6. 创建pod可以使用命令也可以使用yaml,一般使用yaml创建pod。

Pod属性

apiVersion

  1. 必选项,定义apiVersion的版本号。例如:apiVersion: v1。
  2. apiVersion的版本必须可以用 kubectl api-version 可以查询到的。
  3. apiVersion常用的版本一般是v1版本。
  4. 查看apiVersion的版本:
kubectl api-versions 

admissionregistration.k8s.io/v1
admissionregistration.k8s.io/v1beta1
apiextensions.k8s.io/v1
apiextensions.k8s.io/v1beta1
apiregistration.k8s.io/v1
apiregistration.k8s.io/v1beta1
apps/v1
authentication.k8s.io/v1
authentication.k8s.io/v1beta1
authorization.k8s.io/v1
authorization.k8s.io/v1beta1
autoscaling/v1
autoscaling/v2beta1
autoscaling/v2beta2
batch/v1
batch/v1beta1
certificates.k8s.io/v1
certificates.k8s.io/v1beta1
coordination.k8s.io/v1
coordination.k8s.io/v1beta1
crd.projectcalico.org/v1
discovery.k8s.io/v1beta1
events.k8s.io/v1
events.k8s.io/v1beta1
extensions/v1beta1
flowcontrol.apiserver.k8s.io/v1beta1
metrics.k8s.io/v1beta1
networking.k8s.io/v1
networking.k8s.io/v1beta1
node.k8s.io/v1
node.k8s.io/v1beta1
policy/v1beta1
rbac.authorization.k8s.io/v1
rbac.authorization.k8s.io/v1beta1
scheduling.k8s.io/v1
scheduling.k8s.io/v1beta1
storage.k8s.io/v1
storage.k8s.io/v1beta1
v1
  1. 举例:
apiVersion: v1

kind

  1. 必选项,定义所属资源类型,例如:kind: Pod。
  2. kind定义的资源类型必须可以用 kubectl api-resources 可以查询到的。
  3. 查看kind的资源类型:
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
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
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/v1                         true         HorizontalPodAutoscaler
cronjobs                          cj           batch/v1beta1                          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
bgppeers                                       crd.projectcalico.org/v1               false        BGPPeer
blockaffinities                                crd.projectcalico.org/v1               false        BlockAffinity
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
kubecontrollersconfigurations                  crd.projectcalico.org/v1               false        KubeControllersConfiguration
networkpolicies                                crd.projectcalico.org/v1               true         NetworkPolicy
networksets                                    crd.projectcalico.org/v1               true         NetworkSet
endpointslices                                 discovery.k8s.io/v1beta1               true         EndpointSlice
events                            ev           events.k8s.io/v1                       true         Event
ingresses                         ing          extensions/v1beta1                     true         Ingress
flowschemas                                    flowcontrol.apiserver.k8s.io/v1beta1   false        FlowSchema
prioritylevelconfigurations                    flowcontrol.apiserver.k8s.io/v1beta1   false        PriorityLevelConfiguration
nodes                                          metrics.k8s.io/v1beta1                 false        NodeMetrics
pods                                           metrics.k8s.io/v1beta1                 true         PodMetrics
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/v1beta1                         true         PodDisruptionBudget
podsecuritypolicies               psp          policy/v1beta1                         false        PodSecurityPolicy
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
storageclasses                    sc           storage.k8s.io/v1                      false        StorageClass
volumeattachments                              storage.k8s.io/v1                      false        VolumeAttachment
  1. 举例:
apiVersion: v1
kind: pod

metadata

  1. 必选项,metadata定义元数据。
  2. 常见定义有:
    1. name(设置Pod名称);
    2. namespace(设置Pod所在名称空间);
    3. labels(设置Pod标签);
    4. annotations(设置Pod的描述);
name
  1. 必选项,命名要符合RFC1035规范。
  2. 命名在命名空间中必须唯一。
  3. 详情:
kubectl explain pod.metadata.name
KIND:     Pod
VERSION:  v1

FIELD:    name <string>

DESCRIPTION:
     Name must be unique within a namespace. Is required when creating
     resources, although some resources may allow a client to request the
     generation of an appropriate name automatically. Name is primarily intended
     for creation idempotence and configuration definition. Cannot be updated.
     More info: http://kubernetes.io/docs/user-guide/identifiers#names
  1. 举例:
apiVersion: v1
kind: pod
metadata:
  name: nginx-web-01
namespace
  1. 可选项,不指定时默认命名空间为default。
  2. 定义的命名空间必须是唯一的。
  3. 详情:
kubectl explain pod.metadata.namespace
KIND:     Pod
VERSION:  v1

FIELD:    namespace <string>

DESCRIPTION:
     Namespace defines the space within which each name must be unique. An empty
     namespace is equivalent to the "default" namespace, but "default" is the
     canonical representation. Not all objects are required to be scoped to a
     namespace - the value of this field for those objects will be empty.

     Must be a DNS_LABEL. Cannot be updated. More info:
     http://kubernetes.io/docs/user-guide/namespaces
  1. 举例:
apiVersion: v1
kind: pod
metadata:
  name: nginx-web-01
  namespace: lxpt
labels
  1. 可选项,一般用于过滤或区分Pod使用。
  2. 以键值对的形式设置标签,注意自定义键值对。
  3. 标签可以设置多个。
  4. 详情:
kubectl explain pod.metadata.labels
KIND:     Pod
VERSION:  v1

FIELD:    labels <map[string]string>

DESCRIPTION:
     Map of string keys and values that can be used to organize and categorize
     (scope and select) objects. May match selectors of replication controllers
     and services. More info: http://kubernetes.io/docs/user-guide/labels
  1. 举例:
apiVersion: v1
kind: pod
metadata:
  name: nginx-web-01
  namespace: pxpt-test
  labels:
  	- area: shanghai
  	- school: shlg
annotations
  1. 可选项,可以写多个,用于描述Pod信息。
  2. 以键值对的形式设置描述,注意自定义键值对。
  3. 详情:
kubectl explain pod.metadata.annotations
KIND:     Pod
VERSION:  v1

FIELD:    annotations <map[string]string>

DESCRIPTION:
     Annotations is an unstructured key value map stored with a resource that
     may be set by external tools to store and retrieve arbitrary metadata. They
     are not queryable and should be preserved when modifying objects. More
     info: http://kubernetes.io/docs/user-guide/annotations
  1. 举例:
apiVersion: v1
kind: pod
metadata:
  name: nginx-web-01
  namespace: pxpt-test
  labels:
  	- area: shanghai
  	- school: shlg
	annotations:
  	- describe: Test system for student training at University of Shanghai for Science and Technology
  	- user: Students and teachers

spec

  1. 必选项,spec定义资源的各种配置信息。
  2. 常见定义有:
    1. containers(设置Pod的容器配置);
    2. restartPolicy(设置Pod的启动规则);
    3. nodeName(指定Pod运行在哪个节点);
    4. hostNetwork(设置Pod是否使用主机网络模式);
    5. volumes(设置Pod的共享存储资源);
containers
  1. 必选项,通过containers设置Pod使用的容器信息。
  2. 一个containers中可以设置多个容器。
  3. 常见定义:
    1. name
    2. image
    3. imagePullPolicy
    4. command
    5. workingDir
    6. ports
    7. env
name
  1. 必选项,名称定义需要符合RFC1035规范。
  2. Pod中的每个容器名称必须是唯一的。
  3. name属性在contrainers中一般写在第一行。
  4. 详情:
kubectl explain pod.spec.containers.name
KIND:     Pod
VERSION:  v1

FIELD:    name <string>

DESCRIPTION:
     Name of the container specified as a DNS_LABEL. Each container in a pod
     must have a unique name (DNS_LABEL). Cannot be updated.
  1. 举例:
apiVersion: v1
kind: pod
metadata:
  name: nginx-web-01
  namespace: pxpt-test
  labels:
  	- area: shanghai
  	- school: shlg
	annotations:
  	- describe: Test system for student training at University of Shanghai for Science and Technology
  	- user: Students and teachers
spec:
  containers:
  	- name: nginx-01
image
  1. 必选项,容器的镜像名称。
  2. 可以指定镜像获取的地址和版本。
  3. 详情:
kubectl explain pod.spec.containers.image
KIND:     Pod
VERSION:  v1

FIELD:    image <string>

DESCRIPTION:
     Docker image name. More info:
     https://kubernetes.io/docs/concepts/containers/images This field is
     optional to allow higher level config management to default or override
     container images in workload controllers like Deployments and StatefulSets.
  1. 举例:
apiVersion: v1
kind: pod
metadata:
  name: nginx-web-01
  namespace: pxpt-test
  labels:
  	- area: shanghai
  	- school: shlg
	annotations:
  	- describe: Test system for student training at University of Shanghai for Science and Technology
  	- user: Students and teachers
spec:
  containers:
  	- name: nginx-01
  	  image: registry.cn-beijing.aliyuncs.com/publicspaces/nginx:1.21.5
imagePullPolicy
  1. 可选项,镜像拉取的策略。
  2. 拉取策略有三种:
    1. Always(总是拉取镜像);
    2. Never(不管是否有,都不拉镜像);
    3. IfNotPresent(如果宿主机没有这个镜像,就拉取;有就不需要拉取);
  3. 详情:
kubectl explain pod.spec.containers.imagePullPolicy
KIND:     Pod
VERSION:  v1

FIELD:    imagePullPolicy <string>

DESCRIPTION:
     Image pull policy. One of Always, Never, IfNotPresent. Defaults to Always
     if :latest tag is specified, or IfNotPresent otherwise. Cannot be updated.
     More info:
     https://kubernetes.io/docs/concepts/containers/images#updating-images
  1. 举例:
apiVersion: v1
kind: pod
metadata:
  name: nginx-web-01
  namespace: pxpt-test
  labels:
  	- area: shanghai
  	- school: shlg
	annotations:
  	- describe: Test system for student training at University of Shanghai for Science and Technology
  	- user: Students and teachers
spec:
  containers:
  	- name: nginx-01
  	  image: registry.cn-beijing.aliyuncs.com/publicspaces/nginx:1.21.5
  	  imagePullPolicy: IfNotPresent
command
  1. 可选项,设置容器的启动命令。
  2. 如果没有指定,则使用容器运行时的默认值。
  3. 详情:
kubectl explain pod.spec.containers.command
KIND:     Pod
VERSION:  v1

FIELD:    command <[]string>

DESCRIPTION:
     Entrypoint array. Not executed within a shell. The docker image's
     ENTRYPOINT is used if this is not provided. Variable references $(VAR_NAME)
     are expanded using the container's environment. If a variable cannot be
     resolved, the reference in the input string will be unchanged. The
     $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME).
     Escaped references will never be expanded, regardless of whether the
     variable exists or not. Cannot be updated. More info:
     https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell
  1. 举例:
apiVersion: v1
kind: pod
metadata:
  name: nginx-web-01
  namespace: pxpt-test
  labels:
  	- area: shanghai
  	- school: shlg
	annotations:
  	- describe: Test system for student training at University of Shanghai for Science and Technology
  	- user: Students and teachers
spec:
  containers:
  	- name: nginx-01
  	  image: registry.cn-beijing.aliyuncs.com/publicspaces/nginx:1.21.5
  	  imagePullPolicy: IfNotPresent
    	command: ["/bin/bash","nginx","-v"]
workingDir
  1. 可选项,指定容器工作的目录。
  2. 如果没有指定,则使用容器运行时的默认值。
  3. 详情:
kubectl explain pod.spec.containers.workingDir
KIND:     Pod
VERSION:  v1

FIELD:    workingDir <string>

DESCRIPTION:
     Container's working directory. If not specified, the container runtime's
     default will be used, which might be configured in the container image.
     Cannot be updated.
  1. 举例:
apiVersion: v1
kind: pod
metadata:
  name: nginx-web-01
  namespace: pxpt-test
  labels:
  	- area: shanghai
  	- school: shlg
	annotations:
  	- describe: Test system for student training at University of Shanghai for Science and Technology
  	- user: Students and teachers
spec:
  containers:
  	- name: nginx-01
  	  image: registry.cn-beijing.aliyuncs.com/publicspaces/nginx:1.21.5
  	  imagePullPolicy: IfNotPresent
    	command: ["/bin/bash","nginx","-v"]
    	workingDir: /usr/local/
ports
  1. 可选项,设置容器要暴露的端口。
  2. 常见属性:
    1. name(设置端口的名称);
    2. containerPort(指定容器暴露的端口);
    3. protocol(指定容器暴露端口的协议);
  3. 详情:
kubectl explain pod.spec.containers.ports
KIND:     Pod
VERSION:  v1

RESOURCE: ports <[]Object>

DESCRIPTION:
     List of ports to expose from the container. Exposing a port here gives the
     system additional information about the network connections a container
     uses, but is primarily informational. Not specifying a port here DOES NOT
     prevent that port from being exposed. Any port which is listening on the
     default "0.0.0.0" address inside a container will be accessible from the
     network. Cannot be updated.

     ContainerPort represents a network port in a single container.

FIELDS:
   containerPort	<integer> -required-
     Number of port to expose on the pod's IP address. This must be a valid port
     number, 0 < x < 65536.

   hostIP	<string>
     What host IP to bind the external port to.

   hostPort	<integer>
     Number of port to expose on the host. If specified, this must be a valid
     port number, 0 < x < 65536. If HostNetwork is specified, this must match
     ContainerPort. Most containers do not need this.

   name	<string>
     If specified, this must be an IANA_SVC_NAME and unique within the pod. Each
     named port in a pod must have a unique name. Name for the port that can be
     referred to by services.

   protocol	<string>
     Protocol for port. Must be UDP, TCP, or SCTP. Defaults to "TCP".
  1. 举例:
apiVersion: v1
kind: pod
metadata:
  name: nginx-web-01
  namespace: pxpt-test
  labels:
  	- area: shanghai
  	- school: shlg
	annotations:
  	- describe: Test system for student training at University of Shanghai for Science and Technology
  	- user: Students and teachers
spec:
  containers:
  	- name: nginx-01
  	  image: registry.cn-beijing.aliyuncs.com/publicspaces/nginx:1.21.5
  	  imagePullPolicy: IfNotPresent
    	command: ["/bin/bash","nginx","-v"]
    	workingDir: /usr/local/
    	ports:
    	- name: http
      	containerPort: 80
      	protocol: TCP
env
  1. 可选项,设置容器的环境变量。
  2. 常见属性:
    1. name(设置变量的名称);
    2. value(设置变量的值);
  3. 详情:
kubectl explain pod.spec.containers.env
KIND:     Pod
VERSION:  v1

RESOURCE: env <[]Object>

DESCRIPTION:
     List of environment variables to set in the container. Cannot be updated.

     EnvVar represents an environment variable present in a Container.

FIELDS:
   name	<string> -required-
     Name of the environment variable. Must be a C_IDENTIFIER.

   value	<string>
     Variable references $(VAR_NAME) are expanded using the previous defined
     environment variables in the container and any service environment
     variables. If a variable cannot be resolved, the reference in the input
     string will be unchanged. The $(VAR_NAME) syntax can be escaped with a
     double $$, ie: $$(VAR_NAME). Escaped references will never be expanded,
     regardless of whether the variable exists or not. Defaults to "".

   valueFrom	<Object>
     Source for the environment variable's value. Cannot be used if value is not
     empty.
  1. 举例:
apiVersion: v1
kind: pod
metadata:
  name: nginx-web-01
  namespace: pxpt-test
  labels:
  	- area: shanghai
  	- school: shlg
	annotations:
  	- describe: Test system for student training at University of Shanghai for Science and Technology
  	- user: Students and teachers
spec:
  containers:
  	- name: nginx-01
  	  image: registry.cn-beijing.aliyuncs.com/publicspaces/nginx:1.21.5
  	  imagePullPolicy: IfNotPresent
    	command: ["/bin/bash","nginx","-v"]
    	workingDir: /usr/local/
    	ports:
    	- name: http
      	containerPort: 80
      	protocol: TCP
    	env:
    	- name: TZ
      	value: Asia/Shanghai
    	- name: LANG
      	value: en_US.utf8
restartPolicy
  1. 可选项,容器启动规则。
  2. 容器启动规则有三种:
    1. Always(容器故障或没有启动成功,就自动重启容器);
    2. Onfailure(容器终止状态不为0时,就自动重启容器);
    3. Never(不论什么状态,都不重启容器);
  3. 详情:
kubectl explain pod.spec.restartPolicy
KIND:     Pod
VERSION:  v1

FIELD:    restartPolicy <string>

DESCRIPTION:
     Restart policy for all containers within the pod. One of Always, OnFailure,
     Never. Default to Always. More info:
     https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#restart-policy
  1. 举例:
apiVersion: v1
kind: pod
metadata:
  name: nginx-web-01
  namespace: pxpt-test
  labels:
  	- area: shanghai
  	- school: shlg
	annotations:
  	- describe: Test system for student training at University of Shanghai for Science and Technology
  	- user: Students and teachers
spec:
  containers:
  	- name: nginx-01
  	  image: registry.cn-beijing.aliyuncs.com/publicspaces/nginx:1.21.5
  	  imagePullPolicy: IfNotPresent
    	command: ["/bin/bash","nginx","-v"]
    	workingDir: /usr/local/
    	ports:
    	- name: http
      	containerPort: 80
      	protocol: TCP
    	env:
    	- name: TZ
      	value: Asia/Shanghai
    	- name: LANG
      	value: en_US.utf8
  	restartPolicy: Always

总结

  1. 可以使用命令查看每种资源的可配置项。
  2. 有两种语法:
    1. kubectl explain 资源类型

查看某种资源可以配置的一级属性。

  1. kubectl explain 资源类型.属性

查看某个属性可以配置的子属性。

  1. 语法举例:
kubectl explain pod

kubectl explain pod.metadata

kubectl explain pod.metadata.annotations
  1. 注意定义的属性中,后缀带有s的,一般都可以定义多个配置。
    1. 如containers,可以定义多个容器;
    2. 如labels,可以定义多个标签;

Pod创建

创建Pod的yaml文件

cat >> /root/nginx.yaml << EOF
apiVersion: v1 # 必选,API的版本号
kind: Pod       # 必选,类型Pod
metadata:       # 必选,元数据
  name: nginx   # 必选,符合RFC 1035规范的Pod名称
  namespace: default # 可选,Pod所在的命名空间,不指定默认为default,可以使用-n 指定namespace 
  labels:       # 可选,标签选择器,一般用于过滤和区分Pod
    app: nginx
    role: frontend # 可以写多个
  annotations:  # 可选,注释列表,可以写多个
    app: nginx
spec:   # 必选,用于定义容器的详细信息
  containers:   # 必选,容器列表
  - name: nginx # 必选,符合RFC 1035规范的容器名称
    image: nginx:1.15.2    # 必选,容器所用的镜像的地址
    imagePullPolicy: IfNotPresent     # 可选,镜像拉取策略, IfNotPresent: 如果宿主机有这个镜像,那就不需要拉取了. Always: 总是拉取, Never: 不管是否存储都不拉去
    command: # 可选,容器启动执行的命令 ENTRYPOINT, arg --> cmd
    - nginx 
    - -g
    - "daemon off;"
    workingDir: /usr/share/nginx/html       # 可选,容器的工作目录
    ports:  # 可选,容器需要暴露的端口号列表
    - name: http    # 端口名称
      containerPort: 80     # 端口号
      protocol: TCP # 端口协议,默认TCP
    env:    # 可选,环境变量配置列表
    - name: TZ      # 变量名
      value: Asia/Shanghai # 变量的值
    - name: LANG
      value: en_US.utf8
  restartPolicy: Always   # 可选,默认为Always,容器故障或者没有启动成功,那就自动该容器,Onfailure: 容器以不为0的状态终止,自动重启该容器, Never:无论何种状态,都不会重启
EOF

启动Pod

kubectl apply -f /root/nginx.yaml

查看Pod

kubectl get pod -n default -owide
NAME    READY   STATUS    RESTARTS   AGE   IP            NODE           NOMINATED NODE   READINESS GATES
nginx   1/1     Running   0          73s   83.12.140.3   k8s-worker-2   <none>           <none>

Pod探针

什么是Pod探针

  1. 灵活使用Pod探针,可以实现零宕机发布项目。
  2. 注意:探针只能再容器中设置。
  3. 注意三种检查探测机制同时只能使用一种。
  4. Pod探针有三种类型:
    1. startupProbe(启动探针);
    2. readinessProbe(就绪探针);
    3. livenessProbe(存活探针);
  5. Pod探针的三种检查探测机制:
    1. exec(命令行探测);
    2. tcpSocket(api探测);
    3. httpGet(端口探测);
  6. 每种探测机制都适用于三种探针类型。

探针的三种类型

startupProbe
  1. 可选项,判断容器内的应用程序是否已启动完成。
  2. 如果配置了启动探测,则会先禁用所有其它的探测,直到startupProbe检测成功为止。
  3. 如果startupProbe探测失败,则kubelet将杀死容器,容器将按照重启策略进行下一步操作。
  4. 如果容器没有提供启动探测,则默认状态为成功。
  5. 详情:
kubectl explain pod.spec.containers.startupProbe
3.KIND:     Pod
VERSION:  v1

RESOURCE: startupProbe <Object>

DESCRIPTION:
StartupProbe indicates that the Pod has successfully initialized. If
specified, no other probes are executed until this completes successfully.
If this probe fails, the Pod will be restarted, just as if the
livenessProbe failed. This can be used to provide different probe
parameters at the beginning of a Pod's lifecycle, when it might take a long
time to load data or warm a cache, than during steady-state operation. This
cannot be updated. More info:
https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes

Probe describes a health check to be performed against a container to
determine whether it is alive or ready to receive traffic.

FIELDS:
exec	<Object>
One and only one of the following should be specified. Exec specifies the
action to take.

failureThreshold	<integer>
Minimum consecutive failures for the probe to be considered failed after
having succeeded. Defaults to 3. Minimum value is 1.

httpGet	<Object>
HTTPGet specifies the http request to perform.

initialDelaySeconds	<integer>
Number of seconds after the container has started before liveness probes
are initiated. More info:
https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes

periodSeconds	<integer>
How often (in seconds) to perform the probe. Default to 10 seconds. Minimum
value is 1.

successThreshold	<integer>
Minimum consecutive successes for the probe to be considered successful
after having failed. Defaults to 1. Must be 1 for liveness and startup.
Minimum value is 1.

tcpSocket	<Object>
TCPSocket specifies an action involving a TCP port. TCP hooks not yet
supported

timeoutSeconds	<integer>
Number of seconds after which the probe times out. Defaults to 1 second.
Minimum value is 1. More info:
https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes
readinessProbe
  1. 可选项,如果就绪探测失败,端点控制器将从与Pod匹配的所有Service的端点中(endpoint)删除该Pod的IP地址。
  2. 初始延迟之前的就绪状态默认为Failure(失败)。
  3. 如果容器不提供就绪探针,则默认状态为 Success。
  4. readinessProbe用于控制pod是否添加至service。
  5. 详情:
kubectl explain pod.spec.containers.readinessProbe
KIND:     Pod
VERSION:  v1

RESOURCE: readinessProbe <Object>

DESCRIPTION:
Periodic probe of container service readiness. Container will be removed
from service endpoints if the probe fails. Cannot be updated. More info:
https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes

Probe describes a health check to be performed against a container to
determine whether it is alive or ready to receive traffic.

FIELDS:
exec	<Object>
One and only one of the following should be specified. Exec specifies the
action to take.

failureThreshold	<integer>
Minimum consecutive failures for the probe to be considered failed after
having succeeded. Defaults to 3. Minimum value is 1.

httpGet	<Object>
HTTPGet specifies the http request to perform.

initialDelaySeconds	<integer>
Number of seconds after the container has started before liveness probes
are initiated. More info:
https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes

periodSeconds	<integer>
How often (in seconds) to perform the probe. Default to 10 seconds. Minimum
value is 1.

successThreshold	<integer>
Minimum consecutive successes for the probe to be considered successful
after having failed. Defaults to 1. Must be 1 for liveness and startup.
Minimum value is 1.

tcpSocket	<Object>
TCPSocket specifies an action involving a TCP port. TCP hooks not yet
supported

timeoutSeconds	<integer>
Number of seconds after which the probe times out. Defaults to 1 second.
Minimum value is 1. More info:
https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes
livenessProbe
  1. 可选项,检测容器容器是否正在运行。
  2. 如果存活探测失败,则kubelet会杀死容器,并且容器将受到其重启策略的影响。
  3. 如果容器不提供存活探针,则默认状态为 Success。
  4. livenessProbe用于控制是否重启pod。
  5. 详情:
kubectl explain pod.spec.containers.livenessProbe
KIND:     Pod
VERSION:  v1

RESOURCE: livenessProbe <Object>

DESCRIPTION:
     Periodic probe of container liveness. Container will be restarted if the
     probe fails. Cannot be updated. More info:
     https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes

     Probe describes a health check to be performed against a container to
     determine whether it is alive or ready to receive traffic.

FIELDS:
   exec	<Object>
     One and only one of the following should be specified. Exec specifies the
     action to take.

   failureThreshold	<integer>
     Minimum consecutive failures for the probe to be considered failed after
     having succeeded. Defaults to 3. Minimum value is 1.

   httpGet	<Object>
     HTTPGet specifies the http request to perform.

   initialDelaySeconds	<integer>
     Number of seconds after the container has started before liveness probes
     are initiated. More info:
     https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes

   periodSeconds	<integer>
     How often (in seconds) to perform the probe. Default to 10 seconds. Minimum
     value is 1.

   successThreshold	<integer>
     Minimum consecutive successes for the probe to be considered successful
     after having failed. Defaults to 1. Must be 1 for liveness and startup.
     Minimum value is 1.

   tcpSocket	<Object>
     TCPSocket specifies an action involving a TCP port. TCP hooks not yet
     supported

   timeoutSeconds	<integer>
     Number of seconds after which the probe times out. Defaults to 1 second.
     Minimum value is 1. More info:
     https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes

探针的三种探测机制

tcpSocket
  1. 可选项,对指定端口上的容器的IP地址进行TCP检查,如果端口打开,则诊断被认为是成功的。
  2. 常见属性:
    1. host(容器的IP地址);
    2. port(容器的端口);
  3. 详情:
kubectl explain pod.spec.containers.livenessProbe.tcpSocket
KIND:     Pod
VERSION:  v1

RESOURCE: tcpSocket <Object>

DESCRIPTION:
     TCPSocket specifies an action involving a TCP port. TCP hooks not yet
     supported

     TCPSocketAction describes an action based on opening a socket

FIELDS:
   host	<string>
     Optional: Host name to connect to, defaults to the pod IP.

   port	<string> -required-
     Number or name of the port to access on the container. Number must be in
     the range 1 to 65535. Name must be an IANA_SVC_NAME.
host
  1. 指定容器的IP地址
  2. 详情:
kubectl explain pod.spec.containers.livenessProbe.tcpSocket.host
KIND:     Pod
VERSION:  v1

FIELD:    host <string>

DESCRIPTION:
     Optional: Host name to connect to, defaults to the pod IP.
  1. 举例:
apiVersion: v1
kind: pod
metadata:
  name: nginx-web-01
  namespace: pxpt-test
  labels:
  	- area: shanghai
  	- school: shlg
	annotations:
  	- describe: Test system for student training at University of Shanghai for Science and Technology
  	- user: Students and teachers
spec:
  containers:
  	- name: nginx-01
  	  image: registry.cn-beijing.aliyuncs.com/publicspaces/nginx:1.21.5
  	  imagePullPolicy: IfNotPresent
    	command: ["/bin/bash","nginx","-v"]
    	workingDir: /usr/local/
    	ports:
    	- name: http
      	containerPort: 80
      	protocol: TCP
    	env:
    	- name: TZ
      	value: Asia/Shanghai
    	- name: LANG
      	value: en_US.utf8
    	livenessProbe:
      	tcpSocket:
        	host: 127.0.0.1
  	restartPolicy: Always
port
  1. 指定容器的port端口。
  2. 详情:
kubectl explain pod.spec.containers.livenessProbe.tcpSocket.port
KIND:     Pod
VERSION:  v1

FIELD:    port <string>

DESCRIPTION:
     Number or name of the port to access on the container. Number must be in
     the range 1 to 65535. Name must be an IANA_SVC_NAME.

     IntOrString is a type that can hold an int32 or a string. When used in JSON
     or YAML marshalling and unmarshalling, it produces or consumes the inner
     type. This allows you to have, for example, a JSON field that can accept a
     name or number.
  1. 举例:
apiVersion: v1
kind: pod
metadata:
  name: nginx-web-01
  namespace: pxpt-test
  labels:
  	- area: shanghai
  	- school: shlg
	annotations:
  	- describe: Test system for student training at University of Shanghai for Science and Technology
  	- user: Students and teachers
spec:
  containers:
  	- name: nginx-01
  	  image: registry.cn-beijing.aliyuncs.com/publicspaces/nginx:1.21.5
  	  imagePullPolicy: IfNotPresent
    	command: ["/bin/bash","nginx","-v"]
    	workingDir: /usr/local/
    	ports:
    	- name: http
      	containerPort: 80
      	protocol: TCP
    	env:
    	- name: TZ
      	value: Asia/Shanghai
    	- name: LANG
      	value: en_US.utf8
    	livenessProbe:
      	tcpSocket:
        	host: 127.0.0.1
        	port: 80
  	restartPolicy: Always
httpGet
  1. 可选项,对指定的端口和路径上的容器的IP地址执行HTTPGet请求,如果响应的状态码大于等于200且小于 400,则诊断被认为是成功的。
  2. 常见属性:
    1. host(检查的IP);
    2. httpHeaders(检查的请求头);
    3. path(检查路径);
    4. port(监控端口);
    5. scheme(监控协议);
  3. 详情:
kubectl explain pod.spec.containers.livenessProbe.httpGet
KIND:     Pod
VERSION:  v1

RESOURCE: httpGet <Object>

DESCRIPTION:
     HTTPGet specifies the http request to perform.

     HTTPGetAction describes an action based on HTTP Get requests.

FIELDS:
   host	<string>
     Host name to connect to, defaults to the pod IP. You probably want to set
     "Host" in httpHeaders instead.

   httpHeaders	<[]Object>
     Custom headers to set in the request. HTTP allows repeated headers.

   path	<string>
     Path to access on the HTTP server.

   port	<string> -required-
     Name or number of the port to access on the container. Number must be in
     the range 1 to 65535. Name must be an IANA_SVC_NAME.

   scheme	<string>
     Scheme to use for connecting to the host. Defaults to HTTP.
host
  1. 指定容器的IP地址。
  2. 详情:
kubectl explain pod.spec.containers.livenessProbe.httpGet.host
KIND:     Pod
VERSION:  v1

FIELD:    host <string>

DESCRIPTION:
     Host name to connect to, defaults to the pod IP. You probably want to set
     "Host" in httpHeaders instead.
  1. 举例:
apiVersion: v1
kind: pod
metadata:
  name: nginx-web-01
  namespace: pxpt-test
  labels:
  	- area: shanghai
  	- school: shlg
	annotations:
  	- describe: Test system for student training at University of Shanghai for Science and Technology
  	- user: Students and teachers
spec:
  containers:
  	- name: nginx-01
  	  image: registry.cn-beijing.aliyuncs.com/publicspaces/nginx:1.21.5
  	  imagePullPolicy: IfNotPresent
    	command: ["/bin/bash","nginx","-v"]
    	workingDir: /usr/local/
    	ports:
    	- name: http
      	containerPort: 80
      	protocol: TCP
    	env:
    	- name: TZ
      	value: Asia/Shanghai
    	- name: LANG
      	value: en_US.utf8
    	livenessProbe:
      	httpGet:
        	host: 127.0.0.1
  	restartPolicy: Always
path
  1. 指定容器的路径。
  2. 开发指定的监控路径。
  3. 详情:
kubectl explain pod.spec.containers.livenessProbe.httpGet.path
KIND:     Pod
VERSION:  v1

FIELD:    path <string>

DESCRIPTION:
     Path to access on the HTTP server.
  1. 举例:
apiVersion: v1
kind: pod
metadata:
  name: nginx-web-01
  namespace: pxpt-test
  labels:
  	- area: shanghai
  	- school: shlg
	annotations:
  	- describe: Test system for student training at University of Shanghai for Science and Technology
  	- user: Students and teachers
spec:
  containers:
  	- name: nginx-01
  	  image: registry.cn-beijing.aliyuncs.com/publicspaces/nginx:1.21.5
  	  imagePullPolicy: IfNotPresent
    	command: ["/bin/bash","nginx","-v"]
    	workingDir: /usr/local/
    	ports:
    	- name: http
      	containerPort: 80
      	protocol: TCP
    	env:
    	- name: TZ
      	value: Asia/Shanghai
    	- name: LANG
      	value: en_US.utf8
    	livenessProbe:
      	httpGet:
        	host: 127.0.0.1
        	path: /index/plat/check
  	restartPolicy: Always
port
  1. 指定容器的端口。
  2. 详情:
kubectl explain pod.spec.containers.livenessProbe.httpGet.port
KIND:     Pod
VERSION:  v1

FIELD:    port <string>

DESCRIPTION:
     Name or number of the port to access on the container. Number must be in
     the range 1 to 65535. Name must be an IANA_SVC_NAME.

     IntOrString is a type that can hold an int32 or a string. When used in JSON
     or YAML marshalling and unmarshalling, it produces or consumes the inner
     type. This allows you to have, for example, a JSON field that can accept a
     name or number.
  1. 举例:
apiVersion: v1
kind: pod
metadata:
  name: nginx-web-01
  namespace: pxpt-test
  labels:
  	- area: shanghai
  	- school: shlg
	annotations:
  	- describe: Test system for student training at University of Shanghai for Science and Technology
  	- user: Students and teachers
spec:
  containers:
  	- name: nginx-01
  	  image: registry.cn-beijing.aliyuncs.com/publicspaces/nginx:1.21.5
  	  imagePullPolicy: IfNotPresent
    	command: ["/bin/bash","nginx","-v"]
    	workingDir: /usr/local/
    	ports:
    	- name: http
      	containerPort: 80
      	protocol: TCP
    	env:
    	- name: TZ
      	value: Asia/Shanghai
    	- name: LANG
      	value: en_US.utf8
    	livenessProbe:
      	httpGet:
        	host: 127.0.0.1
        	path: /index/plat/check
        	port: 80
  	restartPolicy: Always
scheme
  1. 指定容器端口的协议。
  2. 详情:
kubectl explain pod.spec.containers.livenessProbe.httpGet.scheme
KIND:     Pod
VERSION:  v1

FIELD:    scheme <string>

DESCRIPTION:
     Scheme to use for connecting to the host. Defaults to HTTP.
  1. 举例:
apiVersion: v1
kind: pod
metadata:
  name: nginx-web-01
  namespace: pxpt-test
  labels:
  	- area: shanghai
  	- school: shlg
	annotations:
  	- describe: Test system for student training at University of Shanghai for Science and Technology
  	- user: Students and teachers
spec:
  containers:
  	- name: nginx-01
  	  image: registry.cn-beijing.aliyuncs.com/publicspaces/nginx:1.21.5
  	  imagePullPolicy: IfNotPresent
    	command: ["/bin/bash","nginx","-v"]
    	workingDir: /usr/local/
    	ports:
    	- name: http
      	containerPort: 80
      	protocol: TCP
    	env:
    	- name: TZ
      	value: Asia/Shanghai
    	- name: LANG
      	value: en_US.utf8
    	livenessProbe:
      	httpGet:
        	host: 127.0.0.1
        	path: /index/plat/check
        	port: 80
        	scheme: HTTP
  	restartPolicy: Always
exec
  1. 可选项,在容器内执行指定命令,如果命令退出时返回码为0则认为诊断成功。
  2. 常见属性:
    1. command();
  3. 详情:
kubectl explain pod.spec.containers.livenessProbe.exec
KIND:     Pod
VERSION:  v1

RESOURCE: exec <Object>

DESCRIPTION:
     One and only one of the following should be specified. Exec specifies the
     action to take.

     ExecAction describes a "run in container" action.

FIELDS:
   command	<[]string>
     Command is the command line to execute inside the container, the working
     directory for the command is root ('/') in the container's filesystem. The
     command is simply exec'd, it is not run inside a shell, so traditional
     shell instructions ('|', etc) won't work. To use a shell, you need to
     explicitly call out to that shell. Exit status of 0 is treated as
     live/healthy and non-zero is unhealthy.
command
  1. 指定容器端口的协议。
  2. 详情:
kubectl explain pod.spec.containers.livenessProbe.exec.command
KIND:     Pod
VERSION:  v1

FIELD:    command <[]string>

DESCRIPTION:
     Command is the command line to execute inside the container, the working
     directory for the command is root ('/') in the container's filesystem. The
     command is simply exec'd, it is not run inside a shell, so traditional
     shell instructions ('|', etc) won't work. To use a shell, you need to
     explicitly call out to that shell. Exit status of 0 is treated as
     live/healthy and non-zero is unhealthy.
  1. 举例:
apiVersion: v1
kind: pod
metadata:
  name: nginx-web-01
  namespace: pxpt-test
  labels:
  	- area: shanghai
  	- school: shlg
	annotations:
  	- describe: Test system for student training at University of Shanghai for Science and Technology
  	- user: Students and teachers
spec:
  containers:
  	- name: nginx-01
  	  image: registry.cn-beijing.aliyuncs.com/publicspaces/nginx:1.21.5
  	  imagePullPolicy: IfNotPresent
    	command: ["/bin/bash","nginx","-v"]
    	workingDir: /usr/local/
    	ports:
    	- name: http
      	containerPort: 80
      	protocol: TCP
    	env:
    	- name: TZ
      	value: Asia/Shanghai
    	- name: LANG
      	value: en_US.utf8
    	livenessProbe:
      	exec:
        	command: ["cat", "/usr/local/health/health.txt"]
  	restartPolicy: Always

探针的五种通用属性

failureThreshold
  1. 可选项,检查失败。
  2. 检查多少次失败后表示未就绪。
  3. 单位次。
initialDelaySeconds
  1. 可选项,初始化时间。
  2. 等待多久后进行探测检查。
  3. 单位秒。
periodSeconds
  1. 可选项,检测间隔时间。
  2. 间隔多久探测一次。
  3. 单位秒。
successThreshold
  1. 可选项,检查就绪。
  2. 检查多少次成功后表示就绪
  3. 单位次
timeoutSeconds
  1. 可选项,超时时间。
  2. 超时多久重新检测。
  3. 单位秒。

探针的应用总结

startupProbe
apiVersion: v1
kind: pod
metadata:
  name: nginx-web-01
  namespace: pxpt-test
  labels:
  	- area: shanghai
  	- school: shlg
	annotations:
  	- describe: Test system for student training at University of Shanghai for Science and Technology
  	- user: Students and teachers
spec:
  containers:
  	- name: nginx-01
  	  image: registry.cn-beijing.aliyuncs.com/publicspaces/nginx:1.21.5
  	  imagePullPolicy: IfNotPresent
    	command: ["/bin/bash","nginx","-v"]
    	workingDir: /usr/local/
    	ports:
    	- name: http
      	containerPort: 80
      	protocol: TCP
    	env:
    	- name: TZ
      	value: Asia/Shanghai
    	- name: LANG
      	value: en_US.utf8
    	startupProbe:
      	tcpSocket:
        	host: 127.0.0.1
        	port: 80
        initialDelaySeconds: 60
        timeoutSeconds: 2
        periodSeconds: 5
        successThreshold: 1
        failureThreshold: 2
  	restartPolicy: Always
readinessProbe
apiVersion: v1
kind: pod
metadata:
  name: nginx-web-01
  namespace: pxpt-test
  labels:
  	- area: shanghai
  	- school: shlg
	annotations:
  	- describe: Test system for student training at University of Shanghai for Science and Technology
  	- user: Students and teachers
spec:
  containers:
  	- name: nginx-01
  	  image: registry.cn-beijing.aliyuncs.com/publicspaces/nginx:1.21.5
  	  imagePullPolicy: IfNotPresent
    	command: ["/bin/bash","nginx","-v"]
    	workingDir: /usr/local/
    	ports:
    	- name: http
      	containerPort: 80
      	protocol: TCP
    	env:
    	- name: TZ
      	value: Asia/Shanghai
    	- name: LANG
      	value: en_US.utf8
    	readinessProbe:
      	tcpSocket:
        	host: 127.0.0.1
        	port: 80
        initialDelaySeconds: 60
        timeoutSeconds: 2
        periodSeconds: 5
        successThreshold: 1
        failureThreshold: 2
  	restartPolicy: Always
livenessProbe
apiVersion: v1
kind: pod
metadata:
  name: nginx-web-01
  namespace: pxpt-test
  labels:
  	- area: shanghai
  	- school: shlg
	annotations:
  	- describe: Test system for student training at University of Shanghai for Science and Technology
  	- user: Students and teachers
spec:
  containers:
  	- name: nginx-01
  	  image: registry.cn-beijing.aliyuncs.com/publicspaces/nginx:1.21.5
  	  imagePullPolicy: IfNotPresent
    	command: ["/bin/bash","nginx","-v"]
    	workingDir: /usr/local/
    	ports:
    	- name: http
      	containerPort: 80
      	protocol: TCP
    	env:
    	- name: TZ
      	value: Asia/Shanghai
    	- name: LANG
      	value: en_US.utf8
    	livenessProbe:
      	tcpSocket:
        	host: 127.0.0.1
        	port: 80
        initialDelaySeconds: 60
        timeoutSeconds: 2
        periodSeconds: 5
        successThreshold: 1
        failureThreshold: 2
  	restartPolicy: Always

Pod生命周期

什么是pod的生命周期

Pod对象从创建到删除的这段时间范围称为Pod的生命周期,主要包括一下几个方面:

  1. pod创建
  2. 运行初始化容器
  3. 运行主容器
  4. pod删除

在整个生命周期中,pod会出现5中状态:

  1. 挂起(Pending):API Server已经创建了Pod资源对象,但它尚未被调度完成或者仍处于下载镜像的过程中。
  2. 运行中(Running):Pod已经被调度到某节点,并且所有容器都已经被kubelet创建完成。
  3. 成功(Succeeded):Pod中的所有容器都已经成功删除并且不会被重启。
  4. 失败(Failed):所有容器都已经删除,但至少有一个容器删除失败,即容器返回了非0值的退出状态。
  5. 未知(Unknown):API Server无法正常获取到Pod对象的状态信息,通常由于网络通信失败所导致。

pod创建删除过程

pod创建过程
  1. 用户通过kubectl或其他API客户端提交Pod Spec给API Server。
  2. API Server尝试着将Pod对象的相关信息存入etcd中,待写入操作执行完成,API Server即会返回确认信息至客户端。
  3. Scheduler(调度器)通过其watcher监测到API Server创建了新的Pod对象,于是为该Pod对象挑选一个工作节点并将结果信息更新至API Server。
  4. 调度结果信息由API Server更新至etcd存储系统,并同步给Scheduler。
  5. 相应节点的kubelet监测到由调度器绑定于本节点的Pod后会读取其配置信息,并由本地容器运行时创建相应的容器启动Pod对象后将结果回存至API Server。
  6. API Server将kubelet发来的Pod状态信息存入etcd系统,并将确认信息发送至相应的kubelet。

示意图:
578721-20220430120106971-1876035189.png

pod删除过程
  1. 用户发送删除Pod对象的命令。
  2. API服务器中的Pod对象会随着时间的推移而更新,在宽限期内(默认为30秒),Pod被视为dead。
  3. 将Pod标记为Terminating状态。
  4. (与第3步同时运行)kubelet在监控到Pod对象转为Terminating状态的同时启动Pod关闭过程。
  5. (与第3步同时运行)端点控制器监控到Pod对象的关闭行为时将其从所有匹配到此端点的Service资源的端点列表中移除。
  6. 如果当前Pod对象定义了preStop钩子句柄,在其标记为terminating后即会以同步方式启动执行;如若宽限期结束后,preStop仍未执行完,则重新执行第2步并额外获取一个时长为2秒的小宽限期。
  7. Pod对象中的容器进程收到TERM信号。
  8. 宽限期结束后,若存在任何一个仍在运行的进程,Pod对象即会收到SIGKILL信号。
  9. Kubelet请求API Server将此Pod资源的宽限期设置为0从而完成删除操作,它变得对用户不再可见。

示意图:
1.png

钩子函数

kubernetes在主容器启动之后和删除之前提供了两个钩子函数:

  • postStart:容器创建后立即执行,注意由于是异步执行,它无法保证一定在 ENTRYPOINT 之前运行。如果失败,容器会被杀死,并根据 RestartPolicy 决定是 否重启。
  • preStop:容器终止前执行,常用于资源清理。执行完成之后容器将成功终止,如果失败,容器同样也会被杀死。在其完成之前 会阻塞删除容器的操作。
kubectl explain pod.spec.containers.lifecycle
KIND:     Pod
VERSION:  v1

RESOURCE: lifecycle <Object>

DESCRIPTION:
     Actions that the management system should take in response to container
     lifecycle events. Cannot be updated.

     Lifecycle describes actions that the management system should take in
     response to container lifecycle events. For the PostStart and PreStop
     lifecycle handlers, management of the container blocks until the action is
     complete, unless the container process fails, in which case the handler is
     aborted.

FIELDS:
   postStart	<Object>
     PostStart is called immediately after a container is created. If the
     handler fails, the container is terminated and restarted according to its
     restart policy. Other management of the container blocks until the hook
     completes. More info:
     https://kubernetes.io/docs/concepts/containers/container-lifecycle-hooks/#container-hooks

   preStop	<Object>
     PreStop is called immediately before a container is terminated due to an
     API request or management event such as liveness/startup probe failure,
     preemption, resource contention, etc. The handler is not called if the
     container crashes or exits. The reason for termination is passed to the
     handler. The Pod's termination grace period countdown begins before the
     PreStop hooked is executed. Regardless of the outcome of the handler, the
     container will eventually terminate within the Pod's termination grace
     period. Other management of the container blocks until the hook completes
     or until the termination grace period is reached. More info:
     https://kubernetes.io/docs/concepts/containers/container-lifecycle-hooks/#container-hooks
postStart
kubectl explain pod.spec.containers.lifecycle.postStart
KIND:     Pod
VERSION:  v1

RESOURCE: postStart <Object>

DESCRIPTION:
     PostStart is called immediately after a container is created. If the
     handler fails, the container is terminated and restarted according to its
     restart policy. Other management of the container blocks until the hook
     completes. More info:
     https://kubernetes.io/docs/concepts/containers/container-lifecycle-hooks/#container-hooks

     Handler defines a specific action that should be taken

FIELDS:
   exec	<Object>
     One and only one of the following should be specified. Exec specifies the
     action to take.

   httpGet	<Object>
     HTTPGet specifies the http request to perform.

   tcpSocket	<Object>
     TCPSocket specifies an action involving a TCP port. TCP hooks not yet
     supported
preStop
kubectl explain pod.spec.containers.lifecycle.preStop
KIND:     Pod
VERSION:  v1

RESOURCE: preStop <Object>

DESCRIPTION:
     PreStop is called immediately before a container is terminated due to an
     API request or management event such as liveness/startup probe failure,
     preemption, resource contention, etc. The handler is not called if the
     container crashes or exits. The reason for termination is passed to the
     handler. The Pod's termination grace period countdown begins before the
     PreStop hooked is executed. Regardless of the outcome of the handler, the
     container will eventually terminate within the Pod's termination grace
     period. Other management of the container blocks until the hook completes
     or until the termination grace period is reached. More info:
     https://kubernetes.io/docs/concepts/containers/container-lifecycle-hooks/#container-hooks

     Handler defines a specific action that should be taken

FIELDS:
   exec	<Object>
     One and only one of the following should be specified. Exec specifies the
     action to take.

   httpGet	<Object>
     HTTPGet specifies the http request to perform.

   tcpSocket	<Object>
     TCPSocket specifies an action involving a TCP port. TCP hooks not yet
     supported

钩子定义方式

exec

在容器内执行命令,如果命令的退出状态码是 0 表示执行成功,否则表示失败

kubectl explain pod.spec.containers.lifecycle.preStop.exec
KIND:     Pod
VERSION:  v1

RESOURCE: exec <Object>

DESCRIPTION:
     One and only one of the following should be specified. Exec specifies the
     action to take.

     ExecAction describes a "run in container" action.

FIELDS:
   command	<[]string>
     Command is the command line to execute inside the container, the working
     directory for the command is root ('/') in the container's filesystem. The
     command is simply exec'd, it is not run inside a shell, so traditional
     shell instructions ('|', etc) won't work. To use a shell, you need to
     explicitly call out to that shell. Exit status of 0 is treated as
     live/healthy and non-zero is unhealthy.
tcpSocket

向指定 URL 发起 GET 请求,如果返回的 HTTP 状态码在 [200, 400) 之间表示请求成功,否则表示失败

kubectl explain pod.spec.containers.lifecycle.preStop.tcpSocket
KIND:     Pod
VERSION:  v1

RESOURCE: tcpSocket <Object>

DESCRIPTION:
     TCPSocket specifies an action involving a TCP port. TCP hooks not yet
     supported

     TCPSocketAction describes an action based on opening a socket

FIELDS:
   host	<string>
     Optional: Host name to connect to, defaults to the pod IP.

   port	<string> -required-
     Number or name of the port to access on the container. Number must be in
     the range 1 to 65535. Name must be an IANA_SVC_NAME.
httpGet

在容器尝试访问指定的socket

kubectl explain pod.spec.containers.lifecycle.preStop.httpGet
KIND:     Pod
VERSION:  v1

RESOURCE: httpGet <Object>

DESCRIPTION:
     HTTPGet specifies the http request to perform.

     HTTPGetAction describes an action based on HTTP Get requests.

FIELDS:
   host	<string>
     Host name to connect to, defaults to the pod IP. You probably want to set
     "Host" in httpHeaders instead.

   httpHeaders	<[]Object>
     Custom headers to set in the request. HTTP allows repeated headers.

   path	<string>
     Path to access on the HTTP server.

   port	<string> -required-
     Name or number of the port to access on the container. Number must be in
     the range 1 to 65535. Name must be an IANA_SVC_NAME.

   scheme	<string>
     Scheme to use for connecting to the host. Defaults to HTTP.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值