当前位置:网站首页>Kubesphere - deploy the actual combat with the deployment file (3)

Kubesphere - deploy the actual combat with the deployment file (3)

2022-07-06 10:38:00 Zhuang Xiaoyan

Abstract

without KubeSphere Visual interface , It can also maintain the ability of deployment . Therefore use deployment File to deploy related applications .Deployment object , seeing the name of a thing one thinks of its function , Is the object used to deploy the application . It makes Kubernetes One of the most commonly used objects in , It's for ReplicaSet and Pod The creation of provides a declarative definition method , This eliminates the need to manually create... As in the previous two articles ReplicaSet and Pod object ( Use Deployment Instead of directly creating ReplicaSet Because Deployment Objects have many ReplicaSet No features , For example, rolling upgrade and rollback ).

One 、Deployment The document explains in detail

apiVersion: extensions/v1beta1   # Interface version 
kind: Deployment                 # Interface type 
metadata:
  name: cango-demo               #Deployment name 
  namespace: cango-prd           # Namespace 
  labels:
    app: cango-demo              # label 
spec:
  replicas: 3
   strategy:
    rollingUpdate:  ## because replicas by 3, Then the whole upgrade ,pod The number is 2-4 Between the two 
      maxSurge: 1      # When rolling upgrade, it will start first 1 individual pod
      maxUnavailable: 1 # Maximum allowed for rolling upgrade Unavailable Of pod Number 
  template:         
    metadata:
      labels:
        app: cango-demo  # Template name is required 
    sepc: # Define container templates , The template can contain multiple containers 
      containers:                                                                   
        - name: cango-demo                                                           # Image name 
          image: swr.cn-east-2.myhuaweicloud.com/cango-prd/cango-demo:0.0.1-SNAPSHOT # Mirror address 
          command: [ "/bin/sh","-c","cat /etc/config/path/to/special-key" ]    # Start command 
          args:                                                                # Launch parameters 
            - '-storage.local.retention=$(STORAGE_RETENTION)'
            - '-storage.local.memory-chunks=$(STORAGE_MEMORY_CHUNKS)'
            - '-config.file=/etc/prometheus/prometheus.yml'
            - '-alertmanager.url=http://alertmanager:9093/alertmanager'
            - '-web.external-url=$(EXTERNAL_URL)'
    # If command and args They didn't write , Then use Docker Default configuration .
    # If command Yes , but args Didn't write , that Docker The default configuration is ignored and only executed .yaml Of documents command( Without any parameters ).
    # If command Not written , but args Yes , that Docker Default configured ENTRYPOINT The command line will be executed , But the parameters are called .yaml Medium args.
    # If command and args It's all written , that Docker The default configuration is ignored , Use .yaml Configuration of .
          imagePullPolicy: IfNotPresent  # If not, pull 
          livenessProbe:       # Express container Is it in live state . If LivenessProbe Failure ,LivenessProbe Will be notified kubelet Corresponding container Not healthy . And then kubelet take kill fall container, And according to RestarPolicy Carry out further operations . By default LivenessProbe The initialization value is... Before the first detection Success, If container Not provided LivenessProbe, It's also thought to be Success;
            httpGet:
              path: /health # If there is no heartbeat detection interface, it will be /
              port: 8080
              scheme: HTTP
            initialDelaySeconds: 60 ## How long does it take to run the test after startup 
            timeoutSeconds: 5
            successThreshold: 1
            failureThreshold: 5
            readinessProbe:
          readinessProbe:
            httpGet:
              path: /health # If there is no heartbeat detection interface, it will be /
              port: 8080
              scheme: HTTP
            initialDelaySeconds: 30 ## How long does it take to run the test after startup 
            timeoutSeconds: 5
            successThreshold: 1
            failureThreshold: 5
          resources:              ##CPU Memory limit 
            requests:
              cpu: 2
              memory: 2048Mi
            limits:
              cpu: 2
              memory: 2048Mi
          env:                    ## Through environment variables , Direct delivery pod= Customize Linux OS environment variable 
            - name: LOCAL_KEY     # Local Key
              value: value
            - name: CONFIG_MAP_KEY  # Bureau strategy can be used configMap Configuration of Key,
              valueFrom:
                configMapKeyRef:
                  name: special-config   #configmap Find name by special-config
                  key: special.type      # find name by special-config in data Under the key
          ports:
            - name: http
              containerPort: 8080 # Yes service Exposed port 
          volumeMounts:     # mount volumes Disk defined in 
          - name: log-cache
            mount: /tmp/log
          - name: sdb       # Common usage , The volume is destroyed following the container , Mount a directory 
            mountPath: /data/media    
          - name: nfs-client-root    # How to mount the hard disk directly , If you mount the nfs Directory to /mnt/nfs
            mountPath: /mnt/nfs
          - name: example-volume-config  # Advanced usage No 1 Kind of , take ConfigMap Of log-script,backup-script Mount to respectively /etc/config A relative path under the directory path/to/... Next , If there is a file with the same name , Directly covered .
            mountPath: /etc/config       
          - name: rbd-pvc                # Advanced usage No 2 in , mount PVC(PresistentVolumeClaim)

# Use volume take ConfigMap Mount directly as a file or directory , Each of them key-value Key value pairs will generate a file ,key For the file name ,value For content ,
  volumes:  #  Define the disk to it volumeMounts mount 
  - name: log-cache
    emptyDir: {}
  - name: sdb  # Mount the directory on the host 
    hostPath:
      path: /any/path/it/will/be/replaced
  - name: example-volume-config  #  for ConfigMap File content to the specified path to use 
    configMap:
      name: example-volume-config  #ConfigMap Chinese name 
      items:
      - key: log-script           #ConfigMap Medium Key
        path: path/to/log-script  # Specify a relative path under the directory path/to/log-script
      - key: backup-script        #ConfigMap Medium Key
        path: path/to/backup-script  # Specify a relative path under the directory path/to/backup-script
  - name: nfs-client-root         # For mounting NFS Storage type 
    nfs:
      server: 10.42.0.55          #NFS Server address 
      path: /opt/public           #showmount -e  Take a look at the path 
  - name: rbd-pvc                 # mount PVC disk 
    persistentVolumeClaim:
      claimName: rbd-pvc1         # Mount the applied pvc disk 

Two 、 To write Deployment file :

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
spec:
  #  If specified , .spec.selector  Must match  .spec.template.metadata.labels, Otherwise it will be API Refuse . If  .spec.selector  Not specified , .spec.selector.matchLabels  The default is  .spec.template.metadata.labels.
  replicas: 3
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.7.9
        ports:
        - containerPort: 80
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: frontend
spec:
  minReadySeconds: 5
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 3
      maxUnavailable: 2
  replicas: 25
  template:
    metadata:
      labels:
        app: guestbook
        tier: frontend
    spec:
      containers:
      - name: php-redis
        image: gcr.io/google-samples/gb-frontend:v4
        resources:
          requests:
            cpu: 100m
            memory: 100Mi
        env:
        - name: GET_HOSTS_FROM
          value: dns
          # If your cluster config does not include a dns service, then to
          # instead access environment variables to find service host
          # info, comment out the 'value: dns' line above, and uncomment the
          # line below:
          # value: env
        ports:
        - containerPort: 80

adopt kubectl create -f nginx-deployment.yaml Order or kubectl apply -f nginx-deployment.yaml The command creation name is nginx-deployment Of Deployment object .

adopt Deployment object , You can easily do the following things :

  • establish ReplicaSet and Pod
  • Rolling upgrade ( Upgrade without stopping the old service ) And rollback application ( Roll back the application to the previous version )
  • Smoothly expand and shrink
  • Pause and resume Deployment

3、 ... and 、Deployment The creation of :

On the surface of the above nginx-deployment.yaml File as an example , Use the following command to create a nginx Of Deployment:

kubectl create -f nginx-deployment.yaml --record

--record Parameter can record the current version Deployment What commands have been executed . Execute immediately after creation get The command can view this Deployment:

$kubectl get deployments

NAME               DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE
nginx-deployment   3         0         0            0           1s

NAME representative Deployment Name ,DESIRED On behalf of the Deployment Expected number of copies ,CURRENT Represents the number of copies that have been created ,UP-TO-DATE Represents the number of copies that have been updated ,AVAILABLE Represents the number of copies available to the current user ,AGE On behalf of the current Deployment How long has it been running . Wait a few seconds , Run again get command , You can see the changes :

$ kubectl get deployments
NAME               DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE
nginx-deployment   3         3         3            3           18s

adopt kubectl get rs To view ReplicaSet object , From this we can see that Deployment It will automatically create one ReplicaSet object . adopt kubectl get pods --show-labels Command to view... In the current system Pod object , Can successfully observe nginx-deployment Created 3 individual Pod.

Four 、Deployment Update

If we want to let nginx pod Use nginx:1.9.1 Instead of the original nginx:1.7.9 Mirror image , Run the following command :

kubectl set image deployment/nginx-deployment nginx=nginx:1.9.1

Or we can use edit Command to edit Deployment, take image from nginx:1.7.9 Rewrite into nginx:1.9.1.

kubectl edit deployment/nginx-deployment

View update progress :

$ kubectl rollout status deployment/nginx-deployment
Waiting for rollout to finish: 2 out of 3 new replicas have been updated...
deployment "nginx-deployment" successfully rolled out

Capacity expansion :

kubectl scale deployment nginx-deployment --replicas 10

If the cluster supports horizontal pod autoscaling Words , It can also be Deployment Set auto extend :

kubectl autoscale deployment nginx-deployment --min=10 --max=15 --cpu-percent=80

Deployment A new... Will be created when updating ReplicaSet, Then the new ReplicaSet Medium Pod Slowly expand the capacity to the specified number of copies , Put the old ReplicaSet Slowly shrink to 0. therefore , When updating, you can always ensure that the old service will not stop , This is rolling update .

5、 ... and 、Deployment Roll back of

When we update as above Deployment after , We found that nginx:1.9.1 Your image is not very stable , So I want to modify it back to nginx:1.7.9 Version of , At this point, we do not need to manually change Deployment file , But the use of Deployment The rollback function of .

Use rollout history Command view Deployment Version of (revision):

$ kubectl rollout history deployment/nginx-deployment
deployments "nginx-deployment":
REVISION    CHANGE-CAUSE
1           kubectl create -f docs/user-guide/nginx-deployment.yaml --record
2           kubectl set image deployment/nginx-deployment nginx=nginx:1.9.1

Because we created Deployment It's time to use it —recored Parameters can record commands , We can check every time conveniently revison The change of .

Look at the individual revision Details of :

kubectl rollout history deployment/nginx-deployment --revision=2

Now? , have access to rollout undo The command rolls back to the previous revision:

$ kubectl rollout undo deployment/nginx-deployment
deployment "nginx-deployment" rolled back

You can also use --to-revision Parameter to specify a historical version :

$ kubectl rollout undo deployment/nginx-deployment --to-revision=2
deployment "nginx-deployment" rolled back

You can set up .spec.revisonHistoryLimit Item deployment How much at most revison Historical record . The default will keep all revision; If the item is set to 0,Deployment It's not allowed to go back .

Only Deployment Of rollout Triggered to create a revision! Be careful ! If and only if Deployment Of Pod template Changed , For example, update template Medium label When mirrored with a container , It will trigger one rollout, Thus for Deployment Create a new revision.

rollout More use of commands :

  • history( View historical version )
  • pause( Pause Deployment)
  • resume( Resume suspended Deployment)
  • status( View resource status )
  • undo( Rollback version )

Rolling update related configurations :

  • .spec.minReadySeconds: The newly created Pod Status as Ready For at least .spec.minReadySeconds Just think Pod Available(Ready).
  • .spec.strategy.rollingUpdate.maxSurge: specifies the maximum number of Pods that can be created over the desired number of Pods. The value cannot be 0 if MaxUnavailable is 0. It can be an integer or percentage , The default is desired Pods Count 25%. Scale Up new ReplicaSet when , Calculate the allowable in proportion MaxSurge, Round up when calculating ( such as 3.4, take 4).
  • .spec.strategy.rollingUpdate.maxUnavailable: specifies the maximum number of Pods that can be unavailable during the update process. The value cannot be 0 if maxSurge is 0. It can be an integer or percentage , The default is desired Pods Count 25%. Scale Down old ReplicaSet when , Calculate the allowable in proportion maxUnavailable, Round down during calculation ( such as 3.6, take 3).

therefore , stay Deployment rollout when , Need assurance Available(Ready) Pods The number shall not be less than desired pods number - maxUnavailable; Make sure that all Pods It's not more than desired pods number + maxSurge.

Blog reference

Kubernetes(k8s)Deployment、StatefulSet、DaemonSet、Job、CronJob Detailed explanation of five controllers _ spirit of craftsman , Persevere !-CSDN Blog

原网站

版权声明
本文为[Zhuang Xiaoyan]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131704488421.html