preface

We must build up the environment, see is not to solve the problem, must be actual combat.

Kubernetes series:
  1. Kubernetes is introduced
  2. Kubernetes environment setup
  3. Kubernetes – kubectl is introduced
  4. Introduce Kubernetes – Pod (-)

Pod life cycle

The time range of a Pod object from its creation to its termination and exit is called its life cycle. During this time, the Pod is in a number of different states and performs several operations; Where creating the main container is required, Other options include running init Container, Post Start hook, LiVENESS probe, Readiness probe, and pre-container termination hook (PRE) Stop hook, etc., depending on the definition of Pod. As shown below:

Pod phase

The Pod phase represents the phase of its life cycle. The Pod phase is not intended to represent the state of its container, nor is it a strict state machine. Defined in the phase field of the Pod’s PodStatus object, the possible cases of phase are:

Pod conditions

A Pod has a PodStatus object, which contains an array of PodConditions that describes whether the Pod meets some specified condition. PodCondition contains the following fields:

Important behaviors in the Pod lifecycle

In addition to creating application containers, users can define various behaviors for Pod objects in their life cycle, such as initializing containers, viability probes, and readiness probes.

init container

Init Containers are containers that are run before the primary container of an application is started. They are often used to perform some preset operations on the primary container. They have two typical characteristics:

  1. The initialization container must run until complete. If an initialization container fails, Kubernetes needs to restart it until it completes successfully.
  2. Each initialization container must be run sequentially in a defined order;
What can I do when I initialize a container

Many scenarios require initialization before the application container is started. For example, configuration files are generated for the application based on environment variables or configuration templates, and configurations are obtained from the configuration center. Typical application scenarios for initializing containers are as follows:

  1. Used to run specific detection programs that, for security reasons, are not convenient to include in the master container image;
  2. Provides a way for container image builders and deployers to work separately and independently, so that they do not have to collaborate to create a single image file.
  3. The initialization container and the primary container are in different file system views, so sensitive data, such as Secrets resources, can be safely used separately;
  4. The initialization container should be started and run before the application container, so it can be used to delay the start of the application container until its dependent conditions are met.

Note: Initialization containers do not support Readiness probes because they must be run before a Pod is ready, whereas Readiness probes start later.

In actual combat
  1. Delete Pod, here first clean up the previous implementation of Demo, this step can be ignored;
kubectl delete -f nginx-deployment.yaml
Copy the code
  1. Create a new nginx-init-container.yaml file and initialize busyBox to create an index. HTML for nginx before starting nginx. Init Container shares Volume with nginx. To ensure that Nginx accesses the index.html page set by init Container;
apiVersion: v1
kind: Pod
metadata:
  name: nginx
spec:
  # Download index.html from wget
  initContainers:
    - name: install
      image: busybox
      command:
      - wget
      - "-O"
      - "/workdir/index.html"
      - http://www.baidu.com
      volumeMounts:
      - name: workdir
        mountPath: /workdir
  containers:
  - name: nginx
    image: nginx
    resources:
      limits:
        memory: "128Mi"
        cpu: "128m"
    ports:
    - containerPort: 80
    volumeMounts:
    - name: workdir
      mountPath: /usr/share/nginx/html
  volumes:
  - name: workdir
    emptyDir: {}
Copy the code
  1. Create a Pod resource.
kubectl apply -f nginx-init-container.yaml
Copy the code
  1. View Pod running events;
kubectl describe pod nginx
Copy the code

  1. Go to the container directory and verify that index. HTML is generated for init Container.
kubectl exec -it nginx /bin/bash
Copy the code

Lifecycle hook functions

Lifecycle hooks are commonly used in some frameworks to provide visibility into critical moments in a program’s lifecycle and give the user the ability to take action. Similarly, container lifecycle hooks enable it to sense events in its own lifecycle management and run user-specified handler code when the appropriate time comes. Kubernetes provides two types of lifecycle hooks for containers:

  1. PostStart: a hook handler that runs immediately after the container is created, but Kubernetes cannot guarantee that it will run before ENTRYPOINT in Docker;
  2. PreStop: A hook handler that runs immediately before the container terminates the operation. It is called synchronously, so it blocks the call to delete the container until it completes.
Hook function implementation

The container can access the callback through a handler that implements and registers the callback. There are two types of callback handlers that can be implemented for containers:

  1. Exec: Runs user-defined commands directly in the current container when hook time is triggered. The resources consumed by commands are counted as the resource consumption of the container.
  2. HTTP: Sends an HTTP request to a URL in the current container.
In actual combat
  1. Delete the Pod;
kubectl delete -f nginx-init-container.yaml
Copy the code
  1. Edit nginx-init-container.yaml to add postStart and preStop hook functions.
apiVersion: v1
kind: Pod
metadata:
  name: nginx
spec:
  initContainers:
    - name: install
      image: busybox
      command:
      - wget
      - "-O"
      - "/workdir/index.html"
      - http://www.baidu.com
      volumeMounts:
      - name: workdir
        mountPath: /workdir
  containers:
  - name: nginx
    image: nginx
    lifecycle:
      postStart:
        exec:
          command: ["/bin/sh"."-c"."echo postStart handler > /usr/share/message"]
      preStop:
        exec:
          command: ["/bin/sh"."-c"."nginx -s quit; while killall -0 nginx; do sleep 1; done"]
    resources:
      limits:
        memory: "128Mi"
        cpu: "128m"
    ports:
      - containerPort: 80
    volumeMounts:
      - name: workdir
        mountPath: /usr/share/nginx/html
  volumes:
  - name: workdir
    emptyDir: {}
Copy the code
  1. Create a Pod resource.
kubectl apply -f nginx-init-container.yaml
Copy the code
  1. Verify that the /usr/share/message directory outputs postStart handler.
kubectl exec -it nginx -- /bin/bash
Copy the code

Health check

Kubernetes checks Pod’s health status through three types of probes, among which the most important probes are LivenessProbe and ReadinessProbe. Kubelet will periodically execute these two types of probes to diagnose the container’s check status, as described below:

  1. LivenessProbe: If LivenessProbe detects that the container is in an unhealthy state, kubelet will kill the process of the container and perform corresponding processing according to the restart strategy of the container. If a container does not contain LivenessProbe, Kubelet will assume that the container’s LivenessProbe always returns true;
  2. ReadinessProbe: Checks whether the container service is in the Ready state. Only the Pod in the Ready state can receive requests. If Ready is false, the Service will not load a Pod managed by the Service. ReadinessProbe is triggered periodically and exists throughout the Pod life cycle;
  3. StartupProbe: health check for container startup. It is used for services that start slowly to prevent services from being killed by the previous probe after a long time.
Probe detection mode

Container probe is an important daily task in the Pod object life cycle. It is a health diagnosis performed periodically by Kubelet for the container. The diagnostic operation is defined by the handler of the container. Kubernetes supports three processors for Pod detection:

  1. ExecAction: Executes the specified command within the container. If the return code is 0, the diagnosis is successful.
  2. TCPSocketAction: TCP checks the IP address of the container on the specified port. If the port is open, the diagnosis is considered successful;
  3. HTTPGetAction: Performs an HTTPGet request on the specified port and the container’s IP address on the path. Diagnosis is considered successful if the status code of the response is greater than or equal to 200 and less than 400;
Probe results

Each type of probe has three results:

  1. Success: The container passed the check.
  2. Failure: the container failed the check;
  3. Unknown: No action is taken because the check is not performed.
In actual combat
  1. Delete the Pod;
kubectl delete -f nginx-init-container.yaml
Copy the code
  1. New Lifecycle -pod.yaml, continue to use the nginx container, add postStart and preStop hook functions, define LivenessProbe and ReadinessProbe probes, verify the execution of events in the main container;
apiVersion: v1
kind: Pod
metadata:
  name: nginx
spec:
  containers:
  - name: nginx
    image: nginx
    lifecycle:
      postStart:
        exec:
          command: ["/bin/sh"."-c"."echo postStart handler >> /usr/share/message"]
      preStop:
        exec:
          command: ["/bin/sh"."-c"."echo preStop handler >> /usr/share/message"]
    resources:
      limits:
        memory: "128Mi"
        cpu: "128m"
    ports:
      - containerPort: 80
    livenessProbe:
      exec:
        command: ["/bin/sh"."-c"."echo livenessProbe >> /usr/share/message"]
      initialDelaySeconds: 5
      periodSeconds: 5
    readinessProbe:
      exec:
        command: ["/bin/sh"."-c"."echo readinessProbe >> /usr/share/message"]
      initialDelaySeconds: 5
      periodSeconds: 5
Copy the code
  1. Create a Pod resource.
kubectl apply -f lifecycle-pod.yaml
Copy the code
  1. Go to the container directory to verify the output of /usr/share/message. Here we verify the events for the entire lifecycle pair;
kubectl exec -it nginx -- /bin/bash
Copy the code

Pod Restart Policy

Whether a Pod object should be rebuilt depends on the definition of its restartPolicy restartPolicy property.

The Pod restart policy is closely related to the control mode. Controllers that can manage pods include Replication Controller, Job, DaemonSet, and Kubelet (static Pod). Note the following for different controllers:

  1. Replication Controller and DaemonSet: Must be set to Always to ensure that the container continues to run.
  2. Job: set it to OnFailure or Never to ensure that the container does not restart after execution.
  3. Kubelet: Restart Pod when it fails, regardless of the value set by RestartPolicy, and no health check is performed on Pod;

Another important point to keep in mind is the time it takes to restart containers. Kubelet’s restart interval for failed containers increases exponentially, with a maximum delay of 300 seconds.

The end of the

Welcome everyone little attention, little praise!