Kubernetes -- detailed explanation of Pod -- configuration method of Pod

Posted by Ark3typ3 on Thu, 20 Jan 2022 03:27:14 +0100

Pod introduction

The smallest operating unit in K8s is Pod, and the container must be placed in the Pod before it can operate. The containers in Pod in K8s are divided into two types:

  • User defined container
  • Pause container. This is a container that every Pod will have

Setting up the Pause container has the following two benefits:

  • When a group of containers operate as a unit, it is difficult to judge the overall operation of the Pod. Instead, we introduce a Pause container independent of business as the root container of the Pod, and use its state to represent the operation state of the overall container
  • Multiple containers in the Pod share the IP of the Pause container. 'congratulations on the Volume mounted by the Pause container, which enables the containers between pods to communicate with each other and solves the problem of file sharing

K8s assigns an IP class to each Pod to become a Pod IP. Multiple containers in a Pod share the Pod IP address. K8s requires the underlying network to support communication between any two pods in the cluster. It is generally implemented by virtual network technology, so the container in one Pod can communicate directly with the Pod container on another host

Kubectl explain

There are three ways to configure a resource: command object management, command object configuration and declarative object configuration. The latter two configuration methods are commonly used. Therefore, it is necessary to write a ymal configuration file. There are many configurable options in the configuration file, including the following:

apiVersion: v1     #Required, version number, e.g. v1
kind: Pod         #Required, resource type, such as Pod
metadata:         #Required, metadata
  name: string     #Required, Pod name
  namespace: string  #The namespace to which the Pod belongs. The default is "default"
  labels:           #Custom label list
    - name: string                 
spec:  #Required, detailed definition of container in Pod
  containers:  #Required, container list in Pod
  - name: string   #Required, container name
    image: string  #Required, the image name of the container
    imagePullPolicy: [ Always|Never|IfNotPresent ]  #Get the policy of the mirror 
    command: [string]   #The list of startup commands of the container. If not specified, the startup commands used during packaging shall be used
    args: [string]      #List of startup command parameters for the container
    workingDir: string  #Working directory of the container
    volumeMounts:       #Configuration of storage volumes mounted inside the container
    - name: string      #Refer to the name of the shared storage volume defined by the pod. The volume name defined in the volumes [] section is required
      mountPath: string #The absolute path of the storage volume mount in the container should be less than 512 characters
      readOnly: boolean #Is it read-only mode
    ports: #List of port library numbers to be exposed
    - name: string        #Name of the port
      containerPort: int  #The port number that the container needs to listen on
      hostPort: int       #The port number that the host of the Container needs to listen to. It is the same as the Container by default
      protocol: string    #Port protocol, support TCP and UDP, default TCP
    env:   #List of environment variables to be set before the container runs
    - name: string  #Environment variable name
      value: string #Value of environment variable
    resources: #Setting of resource limits and requests
      limits:  #Resource limit settings
        cpu: string     #Cpu limit, in the number of core s, will be used for the docker run -- Cpu shares parameter
        memory: string  #Memory limit. The unit can be Mib/Gib. It will be used for the docker run --memory parameter
      requests: #Settings for resource requests
        cpu: string    #Cpu request, initial available quantity of container startup
        memory: string #Memory request, initial available number of container starts
    lifecycle: #Lifecycle hook
		postStart: #This hook is executed immediately after the container is started. If the execution fails, it will be restarted according to the restart policy
		preStop: #Execute this hook before the container terminates, and the container will terminate regardless of the result
    livenessProbe:  #For the setting of health check of each container in the Pod, when there is no response for several times, the container will be restarted automatically
      exec:         #Set the inspection mode in the Pod container to exec mode
        command: [string]  #Command or script required for exec mode
      httpGet:       #Set the health check method of containers in Pod to HttpGet, and specify Path and port
        path: string
        port: number
        host: string
        scheme: string
        HttpHeaders:
        - name: string
          value: string
      tcpSocket:     #Set the health check mode of containers in the Pod to tcpSocket mode
         port: number
       initialDelaySeconds: 0       #The time of the first detection after the container is started, in seconds
       timeoutSeconds: 0          #Timeout for container health check probe waiting for response, unit: seconds, default: 1 second
       periodSeconds: 0           #Set the periodic detection time for container monitoring and inspection, in seconds, once every 10 seconds by default
       successThreshold: 0
       failureThreshold: 0
       securityContext:
         privileged: false
  restartPolicy: [Always | Never | OnFailure]  #Restart strategy of Pod
  nodeName: <string> #Setting NodeName means that the Pod is scheduled to the node node with the specified name
  nodeSelector: obeject #Setting NodeSelector means scheduling the Pod to the node containing the label
  imagePullSecrets: #The secret name used to Pull the image, specified in the format of key: secret key
  - name: string
  hostNetwork: false   #Whether to use the host network mode. The default is false. If it is set to true, it means to use the host network
  volumes:   #Define a list of shared storage volumes on this pod
  - name: string    #Shared storage volume name (there are many types of volumes)
    emptyDir: {}       #The storage volume of type emtyDir is a temporary directory with the same life cycle as Pod. Null value
    hostPath: string   #The storage volume of type hostPath represents the directory of the host where the Pod is mounted
      path: string                #The directory of the host where the Pod is located will be used for the directory of mount in the same period
    secret:          #For the storage volume of type secret, mount the cluster and the defined secret object inside the container
      scretname: string  
      items:     
      - key: string
        path: string
    configMap:         #The storage volume of type configMap mounts predefined configMap objects inside the container
      name: string
      items:
      - key: string
        path: string

The above configuration options can be memorized through the hierarchical level and matched with Kubectl explain, for example

[root@master ~]# 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     <Object>
     Standard object's metadata. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata

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

The first level configuration in pod has been listed above, which mainly includes five parts. At the same time, the website is also given. You can view the details:

  • Apiversion < string > version is defined internally by kubernetes. The version number must be available through kubectl API versions

  • Kind < string > type is internally defined by kubernetes. The version number must be available through kubectl API resources

  • Metadata < Object > metadata, mainly resource identification and description, commonly used are name, namespace, labels, etc

  • Spec < Object > description, which is the most important part of configuration, contains a detailed description of various resource configurations

  • Status < Object > status information. The contents do not need to be defined and are automatically generated by kubernetes

You can continue to use kubectl explain pod Spec view the configuration options under the spec. the common options are as follows:

  • Containers < [] Object > container list, used to define container details
  • NodeName < string > dispatch the pod to the specified Node according to the value of nodeName
  • NodeSelector < map [] > select and schedule the Pod to the Node containing these label s according to the information defined in NodeSelector
  • Hostnetwork < Boolean > whether to use the host network mode. The default is false. If it is set to true, it means to use the host network
  • Volumes < [] Object > storage volume is used to define the storage information hung on the Pod
  • Restartpolicy < string > Restart policy, which indicates the processing policy of Pod in case of failure

Pod configuration

You can see some options of Pod configuration through kubectl explain above. The most important one is Pod Spec.contains attribute, which is the most critical configuration in configuring Pod

[root@master ~]# kubectl explain pod.spec.containers
KIND:     Pod
VERSION:  v1
RESOURCE: containers <[]Object>   # Array, representing that there can be multiple containers
FIELDS:
   name  <string>     # Container name
   image <string>     # The mirror address required by the container
   imagePullPolicy  <string> # Image pull strategy 
   command  <[]string> # The list of startup commands of the container. If not specified, the startup commands used during packaging shall be used
   args     <[]string> # List of parameters required for the container's start command
   env      <[]Object> # Configuration of container environment variables
   ports    <[]Object>     # List of port numbers that the container needs to expose
   resources <Object>      # Setting of resource limits and resource requests

Basic configuration

apiVersion: v1
kind: Pod
metadata:
        name: pod-base
        namespace: dev
        labels:
                user: root
spec:
        containers:
        - name: nginx
          image: nginx:1.17.1
        - name: busybox
          image: busybox:1.30 

The above defines a relatively simple Pod configuration with two containers:

  • Nginx: created with the nginx image of version 1.17.1, (nginx is a lightweight web container)
  • Busybox: created with the busybox image of version 1.30, (busybox is a small collection of linux commands)
[root@master ~]# kubectl create -f  pod-base.yaml 
pod/pod-base created
[root@master ~]# kubectl get pod -n dev
NAME       READY   STATUS             RESTARTS   AGE
pod-base   1/2     CrashLoopBackOff   1          5s
[root@master ~]# kubectl get pod -n dev
NAME       READY   STATUS             RESTARTS   AGE
pod-base   1/2     CrashLoopBackOff   1          9s

When viewing the startup status, you can find that only one container is started. This problem also occurs in docker. Because the started container is busybox without a background process, the pod controller will always try to restart the container

Image pull strategy

imagePullPolicy is used to set the image pull policy. kubernetes supports configuring three kinds of pull policies:

  • Always: always pull images from remote warehouses (always download remotely)
  • IfNotPresent: if there is a local image, the local image is used. If there is no local image, the image is pulled from the remote warehouse (if there is a local image, there is no remote download)
  • Never: only use the local image, never pull from the remote warehouse, and report an error if there is no local image (always use the local image)

Default value Description:

If the image tag is a specific version number, the default policy is IfNotPresent

If the image tag is: latest (final version), the default policy is always

apiVersion: v1
kind: Pod
metadata:
  name: pod-imagepullpolicy
  namespace: dev
spec:
  containers:
  - name: nginx
    image: nginx:1.17.1
    imagePullPolicy: Always # Used to set the image pull policy
  - name: busybox
    image: busybox:1.30

Start command

Command configuration allows the container to execute this command when starting. For example, you can run an endless process when busybox starts, so that busybox can always start in the background

apiVersion: v1
kind: Pod
metadata:
  name: pod-command
  namespace: dev
spec:
  containers:
  - name: nginx
    image: nginx:1.17.1
  - name: busybox
    image: busybox:1.30
    command: ["/bin/sh","-c","touch /tmp/hello.txt;while true;do /bin/echo $(date +%T) >> /tmp/hello.txt; sleep 3; done;"]
[root@master ~]# kubectl create -f pod-command.yaml 
pod/pod-command created
[root@master ~]# 
[root@master ~]# 
[root@master ~]# kubectl get pod -n dev
NAME                  READY   STATUS             RESTARTS   AGE
pod-base              1/2     CrashLoopBackOff   10         26m
pod-command           2/2     Running            0          7s
pod-imagepullpolicy   1/2     CrashLoopBackOff   8          17m

You can use kubectl exec to enter the container to view

[root@master ~]# kubectl exec pod-command -n dev -it -c busybox /bin/sh

To exit, you can use ctrl + p + q

Here you can briefly review the difference between the entry point in Dockerfile and the CMD command:

  • When docker run is used, the entry point instruction will not be overwritten if other parameters are included
  • When docker run is used, the CMD instruction will be overwritten if other parameters are included

At the same time, an args option appears in the configuration item to pass parameters. The args option and command option can override the entry point function in Dockerfile

1. If both command and args are not written, use the configuration of Dockerfile.
2 if the command is written but args is not written, the default configuration of Dockerfile will be ignored and the entered command will be executed
3 if the command is not written but args is written, the ENTRYPOINT command configured in the Dockerfile will be executed using the current args parameter
4 if both command and args are written, the configuration of Dockerfile is ignored. Execute command and append args parameter

environment variable

Use the env configuration item to set the environment variables of the container

apiVersion: v1
kind: Pod
metadata:
  name: pod-env
  namespace: dev
spec:
  containers:
  - name: busybox
    image: busybox:1.30
    command: ["/bin/sh","-c","while true;do /bin/echo $(date +%T);sleep 60; done;"]
    env: # Set environment variable list
    - name: "username"
      value: "admin"
    - name: "password"
      value: "123456"
[root@master ~]# kubectl create -f pod-env.yaml 
pod/pod-env created
[root@master ~]# kubectl exec pod-env -it -n dev -c busybox /bin/sh
/ # 
/ # echo $username
admin

port settings

Use the ports option in containers to configure ports

apiVersion: v1
kind: Pod
metadata:
  name: pod-ports
  namespace: dev
spec:
  containers:
  - name: nginx
    image: nginx:1.17.1
    ports: # Sets the list of ports exposed by the container
    - name: nginx-port
      containerPort: 80
      protocol: TCP
[root@master ~]# vim pod-ports.yaml
[root@master ~]#  kubectl create -f pod-ports.yaml
pod/pod-ports created
[root@master ~]# kubectl get pods 
NAME                     READY   STATUS    RESTARTS   AGE
nginx-6867cdf567-lt9wz   1/1     Running   0          44h
[root@master ~]# kubectl get pods -n dev
NAME                  READY   STATUS             RESTARTS   AGE
pod-base              1/2     CrashLoopBackOff   14         48m
pod-command           2/2     Running            0          21m
pod-env               1/1     Running            0          6m56s
pod-imagepullpolicy   1/2     CrashLoopBackOff   12         39m
pod-ports             1/1     Running            0          89s
[root@master ~]# kubectl get pods pod-ports  -n dev
NAME        READY   STATUS    RESTARTS   AGE
pod-ports   1/1     Running   0          111s
[root@master ~]# kubectl get pods pod-ports  -n dev -o wide
NAME        READY   STATUS    RESTARTS   AGE    IP           NODE    NOMINATED NODE   READINESS GATES
pod-ports   1/1     Running   0          115s   10.244.1.8   node1   <none>           <none>
[root@master ~]# curl 10.244.1.8:80

Resource quota

Resource quota is easy to understand. It is similar to the resource quota under Linux. Resource quota for a container can isolate resources between pods and prevent a container from using too many resources, which makes other resources under the pod unusable. K8s provides a mechanism for quota of memory and cpu resources, which is realized through the resources option, There are generally two sub items:

  • Limits: used to limit the maximum resources occupied by the container at runtime. When the resources occupied by the container exceed the limits, it will be terminated and restarted

  • requests: used to set the minimum resources required by the container. If the environment resources are insufficient, the container will not start

apiVersion: v1
kind: Pod
metadata:
  name: pod-resources
  namespace: dev
spec:
  containers:
  - name: nginx
    image: nginx:1.17.1
    resources: # Resource quota
      limits:  # Limit resources (upper limit)
        cpu: "2" # CPU limit, in core s
        memory: "10Gi" # Memory limit
      requests: # Requested resources (lower limit)
        cpu: "1"  # CPU limit, in core s
        memory: "10Mi"  # Memory limit
[root@master ~]# kubectl create -f pod-resources.yaml 
pod/pod-resources created

Topics: Docker Kubernetes