Kubernetes进阶实战读书笔记:POD对象的生命周期

一、Pod生命周期

二、Pod的相位

1、Pod相位含义

 2、Pod相位图解

三、Pod的创建过程

1、用户通过kubectl或其他API客户端提交pod spec给API Server

2、API Server尝试着将pod对象的相关信息存入etcd中、待写入操作之执行完成,API Server即会返回确认信息至客户端

3、API Server开始反映etcd中的变化

4、所有组件均使用"watch"机制来跟踪检查API Server上的相关变动

5、kube-scheduler通过其"watcher" 觉察到API Server创建新的pod对象但尚未绑定至任何工作节点

6、kube-scheduler为pod对象挑选一个工作节点并将结果信息更新至API Server

 

7、调度结果信息由API Server更新至etcd存储系统,而且API Server也开始反映此pod对象的调度结果

8、pod被调度到目标工作节点上的kubelet尝试在当前节点上调用docker启动容器并将容器的结果状态会送至API Server

9、API Server将pod信息存入etcd系统中

10、在etcd确认写入操作成功完成后,API Server将确认信息发送至相关的kubelet,事件将通过它被接受

四、Pod生命周期过程中的重要阶段(初始化容器)

1、官方手册

kubectl explain pod.spec.initContainers

[root@master ~]# kubectl explain pod.spec.initContainers
KIND:     Pod
VERSION:  v1

RESOURCE: initContainers <[]Object>

DESCRIPTION:
     List of initialization containers belonging to the pod. Init containers are
     executed in order prior to containers being started. If any init container
     fails, the pod is considered to have failed and is handled according to its
     restartPolicy. The name for an init container or normal container must be
     unique among all containers. Init containers may not have Lifecycle
     actions, Readiness probes, Liveness probes, or Startup probes. The
     resourceRequirements of an init container are taken into account during
     scheduling by finding the highest request/limit for each resource type, and
     then using the max of of that value or the sum of the normal containers.
     Limits are applied to init containers in a similar fashion. Init containers
     cannot currently be added or removed. Cannot be updated. More info:
     https://kubernetes.io/docs/concepts/workloads/pods/init-containers/

     A single application container that you want to run within a pod.

FIELDS:
   args	<[]string>
     Arguments to the entrypoint. The docker image's CMD 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

   command	<[]string>
     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

   env	<[]Object>
     List of environment variables to set in the container. Cannot be updated.

   envFrom	<[]Object>
     List of sources to populate environment variables in the container. The
     keys defined within a source must be a C_IDENTIFIER. All invalid keys will
     be reported as an event when the container is starting. When a key exists
     in multiple sources, the value associated with the last source will take
     precedence. Values defined by an Env with a duplicate key will take
     precedence. Cannot be updated.

   image	<string>
     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.

   imagePullPolicy	<string>
     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

   lifecycle	<Object>
     Actions that the management system should take in response to container
     lifecycle events. Cannot be updated.

   livenessProbe	<Object>
     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

   name	<string> -required-
     Name of the container specified as a DNS_LABEL. Each container in a pod
     must have a unique name (DNS_LABEL). Cannot be updated.

   ports	<[]Object>
     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.

   readinessProbe	<Object>
     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

   resources	<Object>
     Compute Resources required by this container. Cannot be updated. More info:
     https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/

   securityContext	<Object>
     Security options the pod should run with. More info:
     https://kubernetes.io/docs/concepts/policy/security-context/ More info:
     https://kubernetes.io/docs/tasks/configure-pod-container/security-context/

   startupProbe	<Object>
     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. This is a beta feature enabled by the StartupProbe
     feature flag. More info:
     https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes

   stdin	<boolean>
     Whether this container should allocate a buffer for stdin in the container
     runtime. If this is not set, reads from stdin in the container will always
     result in EOF. Default is false.

   stdinOnce	<boolean>
     Whether the container runtime should close the stdin channel after it has
     been opened by a single attach. When stdin is true the stdin stream will
     remain open across multiple attach sessions. If stdinOnce is set to true,
     stdin is opened on container start, is empty until the first client
     attaches to stdin, and then remains open and accepts data until the client
     disconnects, at which time stdin is closed and remains closed until the
     container is restarted. If this flag is false, a container processes that
     reads from stdin will never receive an EOF. Default is false

   terminationMessagePath	<string>
     Optional: Path at which the file to which the container's termination
     message will be written is mounted into the container's filesystem. Message
     written is intended to be brief final status, such as an assertion failure
     message. Will be truncated by the node if greater than 4096 bytes. The
     total message length across all containers will be limited to 12kb.
     Defaults to /dev/termination-log. Cannot be updated.

   terminationMessagePolicy	<string>
     Indicate how the termination message should be populated. File will use the
     contents of terminationMessagePath to populate the container status message
     on both success and failure. FallbackToLogsOnError will use the last chunk
     of container log output if the termination message file is empty and the
     container exited with an error. The log output is limited to 2048 bytes or
     80 lines, whichever is smaller. Defaults to File. Cannot be updated.

   tty	<boolean>
     Whether this container should allocate a TTY for itself, also requires
     'stdin' to be true. Default is false.

   volumeDevices	<[]Object>
     volumeDevices is the list of block devices to be used by the container.

   volumeMounts	<[]Object>
     Pod volumes to mount into the container's filesystem. Cannot be updated.

   workingDir	<string>
     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.

2、初始化过程详解

1、用于运行特定的工具程序,处于安全等方面的原因、这些程序不适于包含在主容器镜像中

2、提供主容器镜像中不具备的工具程序或自定义代码

3、为容器镜像的构建和部署人员提供了分离、独立工作的途径、使的他们不必协同起来制作单个镜像文件

4、初始化容器和主容器处于不同的文件系统视图中、因此可以分贝安全地使用敏感数据,例如Secrets资源

5、初始化容器要先于应用容器穿行启动并运行完成,因此可用于延后应用容器的启动直至其依赖的条件的到满足

3、初始化容器注意事项

4、模板示例

apiVersion: apps/v1
kind: DaemonSet
metadata:
......
spec:
  selector:
....
  template:
              - matchExpressions:
.....
      initContainers:
      - name: install-cni
        image: quay.io/coreos/flannel:v0.12.0-arm64
        command:
        - cp
        args:
        - -f
        - /etc/kube-flannel/cni-conf.json
        - /etc/cni/net.d/10-flannel.conflist
        volumeMounts:
        - name: cni
          mountPath: /etc/cni/net.d
        - name: flannel-cfg
          mountPath: /etc/kube-flannel/

五、Pod生命周期过程中的重要阶段(容器启动后钩子)

1、容器启动后钩子

2、两种生命周期钩子

1、官方文档

[root@master chapter4]#  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

2、钩子函数

args不能强依赖postStart里的command

 

 

 

 

3、钩子处理程序的实现

 4、模板用例

apiVersion: v1
kind: Pod
metadata:
  name: lifecycle-demo
spec:
  containers:
  - name: lifecycle-demo-container
    image: ikubernetes/myapp:v1
    lifecycle:
      postStart:
        exec:
          command: ["/bin/sh","-c","echo $(hostname) | lifecycle hooks handler > /usr/share/nginx/html/test.html"]

六、Pod生命周期过程中的重要阶段(容器探针检测及重启策略)

1、容器的存活性探针

1、检查方法

2、livenessProbe

2、就绪性探针

3、重启策略

容器程序发生崩溃或容器身亲高潮处限制的资源等原因都可能会导致pod对象的终止此时是否应该重建改pod对象则屈居于其重启策略属性的定义

1、always:但凡pod对象终止就重启,此为默认重启
2、onfailure:仅在pod对象出错时方才将其重启
3、never从不重启

需要注意的是:重启策略适用于pod对象中的所有容器,而且他仅用于控制在同一节点上重新启动pod对象的相关容器

首次需要重启的容器,将在其需要时立即进行重启,随后再次需要重启的操作将有kubelet延迟一段时间后进行

且反复的重启操作的延时时常一次为10秒、20秒、40秒、80秒、160秒和300秒、300秒是最大延迟时长

事实上、一旦绑定到一个节点、pod对象将永远不会被绑定到另外一个节点,它要么重启、要么终止、直到节点发生故障被删除

五、Pod的终止过程

1、用户发送删除pod对象的命令

2、API Server中的pod对象会随着实践的推移而更新,在宽限期内(默认为30秒),pod视为"dead"

3、将pod标记为"terminating" 状态

4、(与第3步同时运行)kubelet在监控到pod对象转为"terminating"状态的同时启用pod关闭过程

5、(与第3步同时运行)端点控制器监控到pod对象的关闭行为时从所有匹配到端点的service资源的端点列表中移除

6、如果当前pod对象定义了prestop钩子处理器,则在其标记为"terminating"后即会以同步的方式启动指定;若宽限期结束后则第2步被重新执行额外获取一个时长为2秒的小宽期限

7、pod对象中的容器进程收到TRRM信号

8、宽限期结束后,若存在任何一个仍在运行的进行,那么pod对象即会受到SIGKILL信号

9、kubelet请求API Server将此pod资源的宽限期设置为0从而完成删除操作。它变得对用户不可见

默认情况下,所有删除操作的宽限期都是30秒,不过kubelet delete命令可以使用 "--grace-period=<seconds>" 选项自定义其时长,若使用0值则表示直接强制删除制定的资源,不过、此时需要同时为命令使用 "--force" 选项

posted @ 2020-08-07 21:59  活的潇洒80  阅读(114)  评论(0编辑  收藏