编程知识 cdmana.com

1. The standard yaml file

apiVersion: v1
kind: Pod
metadata:
  name: pod-base
  namespace: dev
  labels:
    user: slq
spec:
  #nodeName: node1
  #nodeSelector:
   # env: uat
  affinity:
    podAntiAffinity:
    #podAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
      - labelSelector:
          matchExpressions:
          - key: user
            operator: In
            values: ["slq"]
        topologyKey: kubernetes.io/hostname
    #nodeAffinity:
    #  preferredDuringSchedulingIgnoredDuringExecution:
    #  - weight: 1
    #    preference:
    #      matchExpressions:
    #      - key: env
    #        operator: In
    #        values: ["uat","test"]
    #nodeAffinity:
    #  requiredDuringSchedulingIgnoredDuringExecution:
    #    nodeSelectorTerms:
    #    - matchExpressions:
    #      - key: env
    #        operator: In
    #        values: ["uat"]
  containers:
  - name: nginx
    image: nginx
    imagePullPolicy: IfNotPresent # newer IfNotPresent
    ports: 
    - name: nginx-port
      containerPort: 80
      protocol: TCP
    resources:
      limits: #   cpu: "1"
        memory: "10Gi"
      requests: #        cpu: "1"
        memory: "10Mi"
    lifecycle:
      postStart:
        exec:
          command: ["/bin/sh","-c", "echo poststart... > /usr/share/nginx/html/index.html"]
        #tcpSocket:
          #port: 80
      preStop:
        exec:
          command: ["/usr/sbin/nginx","-s","quit"]
    livenessProbe:
      #exec:
       # command: ["/bin/ls","/tmp/"]
      #tcpSocket:
        #port: 80
      httpGet:
        scheme: HTTP
        port: 80
        path: /
  restartPolicy: Never #Always OnFailure Never
  initContainers:
  - name: busybox
    image: busybox:1.30
    imagePullPolicy: IfNotPresent
#    command: ["/bin/sh","-c","touch /tmp/hello.txt;while true;do /bin/echo $(date +%T) >> /tmp/hello.txt; sleep 10;done;"]
    command: ["/bin/sh","-c","touch /tmp/hello.txt"]
    env: 
    - name: "username"
      value: "root"
    - name: "pwd"
      value: "123456"

2.pod Important point record

pod Resource list :
       
apiVersion: v1     # Mandatory , Version number , for example v1
kind: Pod         # Mandatory , The resource type , for example  Pod
metadata:         # Mandatory , Metadata 
  name: string     # Mandatory ,Pod name 
  namespace: string  #Pod The namespace to which it belongs , The default is "default"
  labels:           # Custom tag list 
    - name: string                 
spec:  # Mandatory ,Pod Detailed definition of container in 
  containers:  # Mandatory ,Pod List of containers in 
  - name: string   # Mandatory , Container name 
    image: string  # Mandatory , Image name of the container 
    imagePullPolicy: [ Always|Never|IfNotPresent ]  # The strategy of getting images  
    command: [string]   # Start command list of container , If not specified , Use the startup command used when packaging 
    args: [string]      # Start command parameter list of container 
    workingDir: string  # Working directory of the container 
    volumeMounts:       # Storage volume configuration mounted inside the container 
    - name: string      # quote pod The name of the defined shared storage volume , need volumes[] The volume name of the partial definition 
      mountPath: string # The storage volume is in the container mount The absolute path of , Should be less than 512 character 
      readOnly: boolean # Is it read-only mode 
    ports: # List of port library numbers to be exposed 
    - name: string        # The name of the port 
      containerPort: int  # The port number the container needs to listen on 
      hostPort: int       # The port number that the host of the container needs to listen to , Default and Container identical 
      protocol: string    # Port agreement , 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 # The value of the environment variable 
    resources: # Resource limits and request settings 
      limits:  # Resource limit settings 
        cpu: string     #Cpu The limitation of , Unit is core Count , Will be used for docker run --cpu-shares Parameters 
        memory: string  # Memory limit , The unit can be Mib/Gib, Will be used for docker run --memory Parameters 
      requests: # Settings for resource requests 
        cpu: string    #Cpu request , Initial available number of container starts 
        memory: string # Memory request , Initial available number of container starts 
    lifecycle: # Lifecycle hook 
        postStart: # Execute this hook immediately after the container starts , If execution fails , It will be restarted according to the restart policy 
        preStop: # Execute this hook before the container terminates , Whatever the outcome , The container will terminate 
    livenessProbe:  # Yes Pod Setting of health examination for each container inside , The container will restart automatically after several times of no response 
      exec:         # Yes Pod The in container inspection mode is set to exec The way 
        command: [string]  #exec A command or script that needs to be formulated 
      httpGet:       # Yes Pod The internal container health check method is set to HttpGet, Need to make Path、port
        path: string
        port: number
        host: string
        scheme: string
        HttpHeaders:
        - name: string
          value: string
      tcpSocket:     # Yes Pod Internal container health check mode is set to tcpSocket The way 
         port: number
       initialDelaySeconds: 0       # Time of the first detection after the start of the container , The unit is in seconds 
       timeoutSeconds: 0          # Timeout for container health probe to wait for response , Unit second , Default 1 second 
       periodSeconds: 0           # Set the regular detection time for container monitoring and inspection , Unit second , Default 10 Seconds at a time 
       successThreshold: 0
       failureThreshold: 0
       securityContext:
         privileged: false
  restartPolicy: [Always | Never | OnFailure]  #Pod The restart strategy of 
  nodeName: <string> # Set up NodeName It means that you should Pod Dispatch to the named node Node 
  nodeSelector: obeject # Set up NodeSelector It means that you should Pod Schedule to include this label Of node On 
  imagePullSecrets: #Pull Used when mirroring secret name , With key:secretkey Format designation 
  - name: string
  hostNetwork: false   # Whether to use the host network mode , The default is false, If set to true, Indicates that the host network is used 
  volumes:   # In the pod List of shared storage volumes defined on 
  - name: string    # Shared storage volume name  (volumes There are many types )
    emptyDir: {}       # The type is emtyDir The storage volume of , And Pod A temporary directory in the same lifecycle . Null value 
    hostPath: string   # The type is hostPath The storage volume of , Means mount Pod Directory of host 
      path: string                #Pod Directory of host , Will be used in the same period mount The catalog of 
    secret:          # The type is secret The storage volume of , Mount the cluster with the defined secret Object to the inside of the container 
      scretname: string  
      items:     
      - key: string
        path: string
    configMap:         # The type is configMap The storage volume of , Mount predefined configMap Object to the inside of the container 
      name: string
      items:
      - key: string
        path: string
           
           
kubectl explain pod 


containers:   Multiple container objects can be defined 
 name
 image
 imagePullPolicy
 command
 args
 env 
 ports
 
 
apiVersion: v1
kind: Pod
metadata:
  name: pod-base
  namespace: dev
  labels:
    user: slq
spec:
  containers:
  - name: nginx
    image: nginx
    imagePullPolicy: IfNotPresent
  - name: busybox
    image: busybox:1.3.0
    imagePullPolicy: IfNotPresent
   
   
 Enter the container and execute the command 
kubectl exec pod-base -n dev -it -c busybox /bin/sh   //pod-base pod name   dev  Namespace   busybox  Container name  

limit: 
    cpu: "1"
    memory: "1024M"
requests: 
    cpu: "2"
    memory: "10M"
    
pod Life cycle of :
     establish 
     Run the initialization container 
     Run the main container process 
         After the container starts, the hook 、 Hook function before container termination 
         Survival of containers   Detection readiness detection 
        
 Create and terminate processes :
     The creation process :
         establish api Ask to api-server,api-server Save the request information to etcd in , Direct return response , The scheduler passes etcd watch Mechanism to get and create pod Information about , Then calculate which nodes are assigned to create containers according to the algorithm 
         The specific nodes pass through watch The mechanism observes the need to create containers , Then create the container , After the creation, the result is returned to api-server,api-server modify pod Information 
        
     The termination process :
        api-server Received termination pod Request , First, there is a grace period 30s, take pod Change the status of to the termination status ,kubelet Monitoring to pod In the termination state, it turns on and off pod The process of 
         The endpoint controller monitors pod The object is in a terminated state , It will be removed from the accessible list 
         If there is prestop Hook function , The execution will be started immediately after it is marked as terminated 
         After the grace period ,pod If it's still running , You will receive an immediate stop signal ,kubelet Will ask api-server Change the grace period for this resource to 0, Delete directly 
    
     Initialize container process :
         The start predecessor of the main container 
        
        kubectl get pod pod-base -n dev -w  dynamic viewing pod-base pod The change of 
        
         Hook function before container startup :post start
         Hook function before container termination : pre stop
        
        lifecycle:
          poststart:
            exec: 
              command:
              - cat 
              - /tmp/healthy
            tcpSocket:
              port: 80
            httpGet:
              path: /abc #url Address 
              port: 80
              host: 192.168.109.100
              scheme: HTTP 
              
The Pod "pod-base" is invalid: spec.containers[0].lifecycle.postStart.tcpSocket: Forbidden: may not specify more than 1 handler type

[root@node1 ~]# kubectl get pod pod-base -n dev
NAME       READY   STATUS             RESTARTS   AGE
pod-base   0/1     CrashLoopBackOff   3          63s

 Container survival detection : liveness probes  The representative service can provide services normally 

 Readiness detection : readiness probes   The representative service is ready 

 Both methods support three methods : Only one of the three methods can be used , You can't use two or three at the same time 

---
livenessProbe:
    exec: 
     command:
     - cat
     - /tmp/healthy
---
livenessProbe:
    tcpSocket:
      port: 8080
---
livenessProbe:
    httpGet:
      path: /
      port: 80
      host: 127.0.0.1
      scheme: HTTP
---

kubectl describe pod pod-base -n dev
------------------------------------------
Events:
  Type     Reason     Age                 From               Message
  ----     ------     ----                ----               -------
  Normal   Scheduled  96s                 default-scheduler  Successfully assigned dev/pod-base to node2
  Normal   Created    104s                kubelet            Created container busybox
  Normal   Pulled     104s                kubelet            Container image "busybox:1.30" already present on machine
  Normal   Started    103s                kubelet            Started container busybox
  Normal   Created    45s (x3 over 103s)  kubelet            Created container nginx
  Normal   Started    44s (x3 over 102s)  kubelet            Started container nginx
  Normal   Pulled     15s (x4 over 103s)  kubelet            Container image "nginx" already present on machine
  Warning  Unhealthy  15s (x9 over 95s)   kubelet            Liveness probe failed: /bin/cat: /tmp/hello.txt: No such file or directory
  Normal   Killing    15s (x3 over 75s)   kubelet            Container nginx failed liveness probe, will be restarted
  -----------------------------------------
           
kubectl explain pod.spec.containers.livenessProbe  

pod The restart strategy of :
    Always
    OnFailure
    Never
-------------------------------------------------------------------------------------------------------------------------------------
pod The scheduling 

 Directional scheduling :NodeName NodeSelector
 Affinity scheduling :NodeAffinity PodAffinity PodAntiAffinity
 The stain : Taints  Toleration

NodeName: node1
NodeSelector:
    env: uat

kubectl label nodes node1 env=prod
kubectl label nodes node2 env=dev
kubectl label nodes node3 env=uat


 Affinity scheduling :
nodeAffinity (node Affinity ): 
    pod.spec.affinity.nodeAffinity
        requiredDuringSchedulingIgnoredDuringExecution  
        
        
        key Exists DoesNotExist

- matchExpressions:
  - key: env                    # Match has env Node of label    Exists  DoesNotExist 
    operator: Exists
  - key: env                    # matching env Label value is dev and uat The node of    In NotIn
    operator: In
    values: ["dev","uat"]
  - key: env                    # matching env The tag value is greater than dev The node of    Gt  Lt   Less used 
    operator: Gt
    values: "dev"
    
preferredDuringSchedulingIgnoreDuringExecution: # Priority scheduling to meet the specified rules node 
   preference:
   
  
// matters needing attention :
1. At the same time, if nodeSelector and nodeAffinity, Then both must be satisfied ,pod To run on the specified node On 
2. If nodeAffinity More than one... Was specified nodeSelectorTerms, Then only one of them can match successfully 
3. If one nodeSelectorTerms There are multiple matchExpressions, Then a node must satisfy all the requirements in order to match successfully 
4. If one pod Where node stay pod Changes occurred during operation , No longer fit for pod The node affinity requirements of , The system will ignore this change 

podAffinity (pod Affinity ):

podAntiAffinity (pod Anti affinity ): 


pod Affinity : 
pod.spec.affinity.podAffinity:
    requiredDuringSchedulingIgnoredDuringExecution: # Hard limit 
        namespace
        topologyKey
        labelSelector
          matchExpressions 
            key
            values
            operator
          matchLabels
    preferredDuringSchedulingIgnoreDuringExecution: # Soft limit 
      podAffinityTerm
        namespace
        topologyKey
        labelSelector
          matchExpressions
            key
            values
            operator
          matchLabels
        weight
        
 Anti affinity 
podAntiAffinity:  Others and podAntiAffinity Agreement 

 Both directed scheduling and affinity scheduling start from pod Define scheduling information from the perspective of 

 The stain :

 stay node Some properties are configured to define scheduling information 
 Set up node The information on the determines pod Whether to dispatch to , Stain exclusion relationship 

key=value:effect
PreferNoSchedular  Try not to schedule to this node 
NoSchedular        The scheduler will not schedule to this node , It will not put the... On this node pod Schedule to other nodes 
NoExecute          Will not be scheduled to this node , And the node's node  Dispatch to other nodes 


 Set stain  : kubectl taint nodes node3 key=value:effect
 Remove the stain :  kubectl taint nodes node3 taintEff-
 Remove all stains : kubectl taint nodes node1 key-
 Look at the stain : kubectl describe nodes node1 ---------------->Taints 

kubectl run taint1 --image=nginx -n dev 
kubectl run taint2 --image=nginx -n dev 
kubectl run taint3 --image=nginx -n dev 

kubectl taint nodes node3 taintEff=eff:PreferNoSchedule
kubectl taint nodes node3 taintEff:PreferNoSchedule-
kubectl taint nodes node3 taintEff-

 If set multiple times , Or with duplicate values 

 tolerate :
    
    Toleration:
        key: "taintEff"
        operator: "Equal"
        value: "eff"
        effect: "NoExecute"
        tolerationSeconds # Tolerate time ,pod stay node Stay time on 

版权声明
本文为[If you are well, it will be sunny]所创,转载请带上原文链接,感谢
https://cdmana.com/2021/08/20210804211905879H.html

Tags k8s pod notes
Scroll to Top