k8sPod introduction and configuration

Posted by bradymills on Tue, 21 Sep 2021 21:42:49 +0200


Introduction to Pod

Structure of Pod

  • Each Pod contains one or more containers, which can be divided into two categories:
  • The number of containers where the user program is located can be more or less.
  • Pause container, which is a root container for each Pod. It has two functions:
  • It can be used as a basis to evaluate the health status of the whole Pod.
  • The IP address can be set on the root container, and other containers share this IP (the IP of the Pod) to realize the internal network communication of the Pod (here is the internal communication of the Pod, the communication between the pods is realized by the virtual layer-2 network technology, and our current environment uses Flannel).

Pod definition

• the following is a list of Pod resources:

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

• syntax: View configurable items for each resource

 View the first level configuration that a resource can be configured
kubectl explain Resource type 
 View sub attributes of attributes
kubectl explain Resource type.attribute
• Example: View resource type as pod Configurable items for
kubectl explain pod
• Example: View resource type as Pod of metadata Configurable item for the property of
kubectl explain pod.metadata

In kubernetes, the primary attributes of almost all resources are the same, mainly including five parts:

  • apiVersion: version, which is internally defined by kubernetes. The version number must be queried by kubectl API versions.
  • kind: type, which is internally defined by kubernetes. The type must be queried with kubectl API resources.
  • Metadata: metadata, mainly resource identification and description. Commonly used are name, namespace, labels, etc.
  • spec: description, which is the most important part of configuration. It contains detailed descriptions of various resource configurations.
  • Status: status information. The contents do not need to be defined and are automatically generated by kubernetes.

Among the above attributes, spec is the focus of next research. Continue to look at its common sub attributes:

  • Containers < [] Object >: container list, used to define container details.
  • NodeName: schedules the Pod to the specified Node according to the value of nodeName.
  • Node selector < map [] >: select and schedule the Pod to the nodes containing these labels according to the information defined in NodeSelector.
  • hostNetwork: 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, used to define the storage information mounted on the Pod.
  • Restart policy: restart policy, which indicates the processing policy of Pod in case of failure.

Configuration of Pod

summary

  • This section mainly studies the pod.spec.containers attribute, which is also the most critical configuration in Pod configuration.
  • Example: view the optional configuration items of pod.spec.containers
    kubectl explain pod.spec.containers
 Important properties returned
KIND:     Pod
VERSION:  v1
RESOURCE: containers <[]Object>   # Array representing 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
Create the pod-base.yaml file as follows:

apiVersion: v1
kind: Pod
metadata:
  name: pod-base
  namespace: dev
  labels:
    user: xudaxian
spec:
  containers:
    - name: nginx # Container name
      image: nginx:1.17.1 # The mirror address required by the container
    - name: busybox # Container name
      image: busybox:1.30 # The mirror address required by the container

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

  • Nginx: created using the nginx image of version 1.17.1 (nginx is a lightweight web container).
  • Busybox: it is created with the busybox image of version 1.30 (busybox is a small collection of linux commands).

To create a Pod:

kubectl apply -f pod-base.yaml

To view Pod status:

kubectl get pod -n dev

View internal details through describe:

#At this point, a basic Pod has been running, although it has a problem for the time being
kubectl describe pod pod-base -n dev

Image pull strategy

Create the pod-imagepullpolicy.yaml file as follows:

apiVersion: v1
kind: Pod
metadata:
  name: pod-imagepullpolicy
  namespace: dev
  labels:
    user: xudaxian
spec:
  containers:
    - name: nginx # Container name
      image: nginx:1.17.1 # The mirror address required by the container
      imagePullPolicy: Always # Used to set the pull policy of the image
    - name: busybox # Container name
      image: busybox:1.30 # The mirror address required by the container

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

  • Always: always pull the image from the remote warehouse (always download it remotely).
  • IfNotPresent: if there is a local image, use the local image; if there is no local image, pull the image from the remote warehouse (if there is a local image, use the local image; if there is no local image, use the 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, and report an error if there is no 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, the default policy is Always.
#To create a Pod:
kubectl apply -f pod-imagepullpolicy.yaml

#View Pod details:
kubectl describe pod pod-imagepullpolicy -n dev

Start command

In the previous case, there has always been a problem that has not been solved, that is, the busybox container has not been running successfully. What is the reason for the failure of this container?
Originally, busybox is not a program, but a collection of tool classes. After the kubernetes cluster starts management, it will close automatically. The solution is to keep it running, which requires the command configuration.
Create the pod-command.yaml file as follows:

apiVersion: v1
kind: Pod
metadata:
  name: pod-command
  namespace: dev
  labels:
    user: xudaxian
spec:
  containers:
    - name: nginx # Container name
      image: nginx:1.17.1 # The mirror address required by the container
      imagePullPolicy: IfNotPresent # Set image pull policy
    - name: busybox # Container name
      image: busybox:1.30 # The mirror address required by the container
      command: ["/bin/sh","-c","touch /tmp/hello.txt;while true;do /bin/echo $(date +%T) >> /tmp/hello.txt;sleep 3;done;"]
command: Used in Pod After the container in is initialized, execute a command.
#Here is a brief explanation of the meaning of the command in command:
- "/bin/sh","-c": use sh Execute the command.
- touch /tmp/hello.txt: Create a/tmp/hello.txt File.
- while true;do /bin/echo $(date +%T) >> /tmp/hello.txt;sleep 3;done: Write the current time to the file every 3 seconds
# Create Pod
kubectl apply -f pod-command.yaml

# View Pod status:
kubectl get pod pod-command -n dev

# Enter the busybox container in the Pod to view the contents of the file:
# Execute command in container
kubectl exec -it pod Name of -n Namespace -c Container name /bin/sh
kubectl exec -it pod-command -n dev -c busybox /bin/sh
Special note: it is found through the above command The function of starting commands and passing parameters can be completed. Why provide one args Option for passing parameters? Actually and Docker It doesn't matter, kubernetes Medium command and args Two parameters are actually used to achieve coverage Dockerfile Medium ENTRYPOINT Functions of:
• If command and args It's not written, so use it Dockerfile Configuration of.
• If command Yes, but args No, so Dockerfile The default configuration will be ignored and injected command. 
• If command No, but args Yes, so Dockerfile Configured in ENTRYPOINT The command will be executed using the current args Parameters for.
• If command and args It's all written, so Dockerfile The configuration in will be ignored and executed command And add args Parameters.

Environment variables (not recommended)

• create the pod-evn.yaml file as follows:

apiVersion: v1
kind: Pod
metadata:
  name: pod-env
  namespace: dev
  labels:
    user: xudaxian
spec:
  containers:
    - name: nginx # Container name
      image: nginx:1.17.1 # The mirror address required by the container
      imagePullPolicy: IfNotPresent # Set image pull policy
    - name: busybox # Container name
      image: busybox:1.30 # The mirror address required by the container
      command: ["/bin/sh","-c","touch /tmp/hello.txt;while true;do /bin/echo $(date +%T) >> /tmp/hello.txt;sleep 3;done;"]
      env:
        - name: "username"
          value: "admin"
        - name: "password"
          value: "123456"
env: Environment variables for Pod Set environment variables for containers in.
• establish Pod: 
kubectl create -f pod-env.yaml
• Enter the container and output the environment variable:
kubectl exec -it pod-env -n dev -c busybox -it /bin/sh

This method is not recommended. It is recommended to store these configurations separately in the configuration file, which will be described later.

port settings

• see ports Supported sub options:
kubectl explain pod.spec.containers.ports
KIND:     Pod
VERSION:  v1
RESOURCE: ports <[]Object>
FIELDS:
  name <string> # The port name, if specified, must be unique in the pod
  containerPort <integer> # Port on which the container will listen (0 < x < 65536)
  hostPort <integer> # The port on which the container is to be exposed on the host. If set, only one copy of the container can be run on the host (generally omitted)
  hostIP <string>  # Host IP to which the external port is bound (generally omitted)
  protocol <string>  # Port protocol. Must be UDP, TCP or SCTP. Default is "TCP"
• establish pod-ports.yaml Document, which reads as follows:
apiVersion: v1
kind: Pod
metadata:
  name: pod-ports
  namespace: dev
  labels:
    user: xudaxian
spec:
  containers:
    - name: nginx # Container name
      image: nginx:1.17.1 # The mirror address required by the container
      imagePullPolicy: IfNotPresent # Set image pull policy
      ports:
        - name: nginx-port # The port name, if executed, must be unique in the Pod
          containerPort: 80 # Port on which the container will listen (0 ~ 65536)
          protocol: TCP # Port protocol
• establish Pod: 
kubectl create -f pod-ports.yaml

The program accessing the container in the Pod uses PodIp + containerPort.

Resource quota

If a program in a container wants to run, it will certainly occupy certain resources, such as CPU and memory. If the resources of a container are not limited, it may eat a lot of resources and make other containers unable to run. In this case, kubernetes provides a mechanism to quota memory and CPU resources. This mechanism is mainly realized through the resources option There are two sub options:

  • Limits: used to limit the maximum resources occupied by the running container. 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.

You can set the upper and lower limits of resources through the above two options.

establish pod-resoures.yaml Document, which reads as follows:
apiVersion: v1
kind: Pod
metadata:
  name: pod-resoures
  namespace: dev
  labels:
    user: xudaxian
spec:
  containers:
    - name: nginx # Container name
      image: nginx:1.17.1 # The mirror address required by the container
      imagePullPolicy: IfNotPresent # Set image pull policy
      ports: # port settings
        - name: nginx-port # The port name, if executed, must be unique in the Pod
          containerPort: 80 # Port on which the container will listen (0 ~ 65536)
          protocol: TCP # Port protocol
      resources: # Resource quota
        limits: # Limit the upper limit of resources
          cpu: "2" # CPU limit, in core s
          memory: "10Gi" # Memory limit
        requests: # Limit the lower limit of resources
          cpu: "1" # CPU limit, in core s 
          memory: "10Mi" # Memory limit
cpu: core Number, which can be integer or decimal.
memory: Memory size, can use Gi,Mi,G,M Etc.
• establish Pod: 
kubectl create -f pod-resource.yaml
• View findings Pod Normal operation:
kubectl get pod pod-resoures -n dev
• Next, stop Pod: 
kubectl delete -f pod-resource.yaml
• edit Pod,modify resources.requests.memory The value of is 10 Gi: 
apiVersion: v1
kind: Pod
metadata:
  name: pod-resoures
  namespace: dev
  labels:
    user: xudaxian
spec:
  containers:
    - name: nginx # Container name
      image: nginx:1.17.1 # The mirror address required by the container
      imagePullPolicy: IfNotPresent # Set image pull policy
      ports: # port settings
        - name: nginx-port # The port name, if executed, must be unique in the Pod
          containerPort: 80 # Port on which the container will listen (0 ~ 65536)
          protocol: TCP # Port protocol
      resources: # Resource quota
        limits: # Limit the upper limit of resources
          cpu: "2" # CPU limit, in core s
          memory: "10Gi" # Memory limit
        requests: # Limit the lower limit of resources
          cpu: "1" # CPU limit, in core s 
          memory: "10Gi" # Memory limit
• Restart Pod: 
kubectl create -f pod-resource.yaml
• see Pod Status, discovery Pod Startup failed:
kubectl get pod pod-resoures -n dev -o wide
• see Pod You will find the following tips:
kubectl describe pod pod-resoures -n dev

Topics: Kubernetes