1. 程式人生 > 實用技巧 >Kubernetes進階實戰讀書筆記:POD物件的生命週期

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、鉤子函式

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" 選項