Kubernetes资源对象之Deployment

Deployment集成了上线部署、滚动升级、创建副本、暂停上线任务,恢复上线任务,回滚到以前某一版本(成功/稳定)的Deployment等功能,在某种程度上,Deployment可以实现无人值守的上线,大大降低上线过程的复杂沟通、操作风险。

1、Deployment的创建

创建方式与Pod类似,通过yaml或json描述文件来定义一个Deployment对象,一个典型的deploy描述文件如下:

# deploy-demo.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: myapp-deploy
  namespace: default
spec:
  replicas: 2
  selector:
    matchLabels:
      app: myapp
      release: cannary
  template:
    metadata:
      labels:
        app: myapp
        release: cannary
    spec:
      containers:
      - name: myapp
        image: ikubernetes/myapp:v1
        ports:
        - name: http
          containerPort: 80

通过kubectl apply -f声明式创建deploy

[root@node01 manifests]# kubectl apply -f deploy-demo.yaml

我们可以看到,kubernetes也自动创建了ReplicaSet

[root@node01 manifests]# kubectl get deploy
NAME           DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGE
myapp-deploy   2         2         2            2           25m
[root@node01 manifests]# kubectl get rs
NAME                      DESIRED   CURRENT   READY   AGE
myapp-deploy-76c79cd9b4   2         2         2       25m

可通过直接修改配置文件deploy-demo.yaml来更新,修改后再kubectl apply

[root@node01 manifests]# kubectl get rs
NAME                      DESIRED   CURRENT   READY   AGE
myapp-deploy-7545c5676c   3         3         3       28s
myapp-deploy-76c79cd9b4   0         0         0       49m

myapp-deploy-76c79cd9b4为上一个版本记录

2、Deployment的扩容,更新

以打补丁的方式

[root@node01 ~]# kubectl patch --help
Update field(s) of a resource using strategic merge patch, a JSON merge patch, or a JSON patch. 

JSON and YAML formats are accepted. 

Please refer to the models in
https://htmlpreview.github.io/?https://github.com/kubernetes/kubernetes/blob/HEAD/docs/api-reference/v1/definitions.html
to find if a field is mutable.

Examples:
  # Partially update a node using a strategic merge patch. Specify the patch as JSON.
  kubectl patch node k8s-node-1 -p '{"spec":{"unschedulable":true}}'
  
  # Partially update a node using a strategic merge patch. Specify the patch as YAML.
  kubectl patch node k8s-node-1 -p $'spec:\n unschedulable: true'
  
  # Partially update a node identified by the type and name specified in "node.json" using strategic merge patch.
  kubectl patch -f node.json -p '{"spec":{"unschedulable":true}}'
  
  # Update a container's image; spec.containers[*].name is required because it's a merge key.
  kubectl patch pod valid-pod -p '{"spec":{"containers":[{"name":"kubernetes-serve-hostname","image":"new image"}]}}'
  
  # Update a container's image using a json patch with positional arrays.
  kubectl patch pod valid-pod --type='json' -p='[{"op": "replace", "path": "/spec/containers/0/image", "value":"new
image"}]'

Options:
      --allow-missing-template-keys=true: If true, ignore any errors in templates when a field or map key is missing in
the template. Only applies to golang and jsonpath output formats.
      --dry-run=false: If true, only print the object that would be sent, without sending it.
  -f, --filename=[]: Filename, directory, or URL to files identifying the resource to update
      --local=false: If true, patch will operate on the content of the file, not the server-side resource.
  -o, --output='': Output format. One of:
json|yaml|name|templatefile|template|go-template|go-template-file|jsonpath|jsonpath-file.
  -p, --patch='': The patch to be applied to the resource JSON file.
      --record=false: Record current kubectl command in the resource annotation. If set to false, do not record the
command. If set to true, record the command. If not set, default to updating the existing annotation value only if one
already exists.
  -R, --recursive=false: Process the directory used in -f, --filename recursively. Useful when you want to manage
related manifests organized within the same directory.
      --template='': Template string or path to template file to use when -o=go-template, -o=go-template-file. The
template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].
      --type='strategic': The type of patch being provided; one of [json merge strategic]

Usage:
  kubectl patch (-f FILENAME | TYPE NAME) -p PATCH [options]

Use "kubectl options" for a list of global command-line options (applies to all commands).

使用kubectl patch动态扩容pod副本数

[root@node01 manifests]# kubectl patch deployment myapp-deploy -p '{"spec":{"replicas":5}}'
deployment.extensions/myapp-deploy patched
[root@node01 manifests]# kubectl get pods
NAME                            READY   STATUS    RESTARTS   AGE
myapp-9w2mz                     1/1     Unknown   0          11h
myapp-deploy-7545c5676c-2xllx   1/1     Running   0          2m31s
myapp-deploy-7545c5676c-9qjjq   1/1     Running   0          18m
myapp-deploy-7545c5676c-hl82s   1/1     Running   0          18m
myapp-deploy-7545c5676c-sf8lp   1/1     Running   0          18m
myapp-deploy-7545c5676c-z2psd   1/1     Running   0          2m31s

3、Deployment的更新策略

[root@node01 ~]# kubectl explain deploy.spec.strategy
KIND:     Deployment
VERSION:  extensions/v1beta1

RESOURCE: strategy <Object>

DESCRIPTION:
     The deployment strategy to use to replace existing pods with new ones.

     DeploymentStrategy describes how to replace existing pods with new ones.

FIELDS:
   rollingUpdate        <Object>
     Rolling update config params. Present only if DeploymentStrategyType =
     RollingUpdate.

   type <string>
     Type of deployment. Can be "Recreate" or "RollingUpdate". Default is
     RollingUpdate.

有两种更新策略,一种为“Recreate”,重建更新,就是删除一个,再重新创建一个;另一种是“RollingUpdate”,滚动更新,默认更新策略。

[root@node01 ~]# kubectl explain deploy.spec.strategy.rollingUpdate
KIND:     Deployment
VERSION:  extensions/v1beta1

RESOURCE: rollingUpdate <Object>

DESCRIPTION:
     Rolling update config params. Present only if DeploymentStrategyType =
     RollingUpdate.

     Spec to control the desired behavior of rolling update.

FIELDS:
   maxSurge     <string>
     The maximum number of pods that can be scheduled above the desired number
     of pods. Value can be an absolute number (ex: 5) or a percentage of desired
     pods (ex: 10%). This can not be 0 if MaxUnavailable is 0. Absolute number
     is calculated from percentage by rounding up. By default, a value of 1 is
     used. Example: when this is set to 30%, the new RC can be scaled up
     immediately when the rolling update starts, such that the total number of
     old and new pods do not exceed 130% of desired pods. Once old pods have
     been killed, new RC can be scaled up further, ensuring that total number of
     pods running at any time during the update is atmost 130% of desired pods.

   maxUnavailable       <string>
     The maximum number of pods that can be unavailable during the update. Value
     can be an absolute number (ex: 5) or a percentage of desired pods (ex:
     10%). Absolute number is calculated from percentage by rounding down. This
     can not be 0 if MaxSurge is 0. By default, a fixed value of 1 is used.
     Example: when this is set to 30%, the old RC can be scaled down to 70% of
     desired pods immediately when the rolling update starts. Once new pods are
     ready, old RC can be scaled down further, followed by scaling up the new
     RC, ensuring that the total number of pods available at all times during
     the update is at least 70% of desired pods.
  • maxSurge:更新过程中,最多能超出的pod副本数,可以是数字,也可以是百分比。
  • maxUnavailable:最多不可用个数

设置更新过程中,最多可以超出1个pod副本数,且不允许有不可用的pod副本

[root@node01 ~]# kubectl patch deployment myapp-deploy -p '{"spec":{"strategy":{"rollingUpdate":{"maxSurge":1, "maxUnavailable":0}}}}'
deployment.extensions/myapp-deploy patched

4、使用kubectl set更新

[root@node01 ~]# kubectl set --help
Configure application resources 

These commands help you make changes to existing application resources.

Available Commands:
  env            Update environment variables on a pod template
  image          更新一个 pod template 的镜像
  resources      在对象的 pod templates 上更新资源的 requests/limits
  selector       设置 resource 的 selector
  serviceaccount Update ServiceAccount of a resource
  subject        Update User, Group or ServiceAccount in a RoleBinding/ClusterRoleBinding

Usage:
  kubectl set SUBCOMMAND [options]

Use "kubectl <command> --help" for more information about a given command.
Use "kubectl options" for a list of global command-line options (applies to all commands).

更新myapp-deploy镜像版本为v3,并暂停更新,可看到立即创建了一个新的资源

[root@node01 ~]# kubectl set image deployment myapp-deploy myapp=ikubernetes/myapp:v3 && kubectl rollout pause deployment myapp-deploy
deployment.extensions/myapp-deploy image updated
deployment.extensions/myapp-deploy paused
[root@node01 ~]# kubectl get pods -l app=myapp -w
NAME                            READY   STATUS    RESTARTS   AGE
myapp-deploy-66678fbcb6-dh2fp   1/1     Running   0          108s
myapp-deploy-7545c5676c-2xllx   1/1     Running   0          137m
myapp-deploy-7545c5676c-9qjjq   1/1     Running   0          153m
myapp-deploy-7545c5676c-hl82s   1/1     Running   0          153m
myapp-deploy-7545c5676c-sf8lp   1/1     Running   0          153m
myapp-deploy-7545c5676c-z2psd   1/1     Running   0          137m

可监视更新过程的状态

[root@node01 ~]# kubectl rollout status deployment myapp-deploy
Waiting for deployment "myapp-deploy" rollout to finish: 1 out of 5 new replicas have been updated...

[root@node01 ~]# kubectl rollout --help
Manage the rollout of a resource.
  
Valid resource types include: 

  * deployments  
  * daemonsets  
  * statefulsets

Examples:
  # Rollback to the previous deployment
  kubectl rollout undo deployment/abc
  
  # Check the rollout status of a daemonset
  kubectl rollout status daemonset/foo

Available Commands:
  history     显示 rollout 历史
  pause       标记提供的 resource 为中止状态
  resume      继续一个停止的 resource
  status      显示 rollout 的状态
  undo        撤销上一次的 rollout

Usage:
  kubectl rollout SUBCOMMAND [options]

Use "kubectl <command> --help" for more information about a given command.
Use "kubectl options" for a list of global command-line options (applies to all commands).

使用kubectl rollout resume继续更新myapp-deploy,kubectl rollout status查看更新过程

[root@node01 ~]# kubectl rollout resume deployment myapp-deploy
deployment.extensions/myapp-deploy resumed
[root@node01 ~]# kubectl rollout status deployment myapp-deploy
Waiting for deployment "myapp-deploy" rollout to finish: 1 out of 5 new replicas have been updated...
Waiting for deployment spec update to be observed...
Waiting for deployment spec update to be observed...
Waiting for deployment "myapp-deploy" rollout to finish: 1 out of 5 new replicas have been updated...
Waiting for deployment "myapp-deploy" rollout to finish: 2 out of 5 new replicas have been updated...
Waiting for deployment "myapp-deploy" rollout to finish: 2 out of 5 new replicas have been updated...
Waiting for deployment "myapp-deploy" rollout to finish: 2 out of 5 new replicas have been updated...
Waiting for deployment "myapp-deploy" rollout to finish: 3 out of 5 new replicas have been updated...
Waiting for deployment "myapp-deploy" rollout to finish: 3 out of 5 new replicas have been updated...
Waiting for deployment "myapp-deploy" rollout to finish: 3 out of 5 new replicas have been updated...
Waiting for deployment "myapp-deploy" rollout to finish: 4 out of 5 new replicas have been updated...
Waiting for deployment "myapp-deploy" rollout to finish: 4 out of 5 new replicas have been updated...
Waiting for deployment "myapp-deploy" rollout to finish: 4 out of 5 new replicas have been updated...
Waiting for deployment "myapp-deploy" rollout to finish: 1 old replicas are pending termination...
Waiting for deployment "myapp-deploy" rollout to finish: 1 old replicas are pending termination...
deployment "myapp-deploy" successfully rolled out

可以看到,这里就有了3个资源版本

[root@node01 ~]# kubectl get rs -o wide
NAME                      DESIRED   CURRENT   READY   AGE     CONTAINERS   IMAGES                 SELECTOR
myapp-deploy-66678fbcb6   5         5         5       11m     myapp        ikubernetes/myapp:v3   app=myapp,pod-template-hash=66678fbcb6,release=cannary
myapp-deploy-7545c5676c   0         0         0       163m    myapp        ikubernetes/myapp:v2   app=myapp,pod-template-hash=7545c5676c,release=cannary
myapp-deploy-76c79cd9b4   0         0         0       3h32m   myapp        ikubernetes/myapp:v1   app=myapp,pod-template-hash=76c79cd9b4,release=cannary

若发现更新过程中有问题,则可以使用kubectl rollout undo进行回滚,默认回滚到上一个版本,可以使用kubectl rollout undo --help查看具体用法

[root@node01 ~]# kubectl rollout history deployment myapp-deploy
deployment.extensions/myapp-deploy 
REVISION  CHANGE-CAUSE
1         <none>
2         <none>
3         <none>
[root@node01 ~]# kubectl rollout undo deployment myapp-deploy --to-revision=1
deployment.extensions/myapp-deploy

可以看到,当前正在工作的是v1版本

[root@node01 ~]# kubectl get rs -o wide
NAME                      DESIRED   CURRENT   READY   AGE     CONTAINERS   IMAGES                 SELECTOR
myapp-deploy-66678fbcb6   0         0         0       19m     myapp        ikubernetes/myapp:v3   app=myapp,pod-template-hash=66678fbcb6,release=cannary
myapp-deploy-7545c5676c   0         0         0       171m    myapp        ikubernetes/myapp:v2   app=myapp,pod-template-hash=7545c5676c,release=cannary
myapp-deploy-76c79cd9b4   5         5         5       3h40m   myapp        ikubernetes/myapp:v1   app=myapp,pod-template-hash=76c79cd9b4,release=cannary
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容