研发工程师玩转Kubernetes——使用Deployment进行版本升级

软件升级是一件非常常见的事,本节我们将尝试使用Deployment进行软件升级。

更新simple_http版本

我们还是借助《研发工程师玩转Kubernetes——构建、推送自定义镜像》中的代码库,只是稍微修改一下Dockerfile——将版本变成2。

# Dockerfile
From python:3.11
RUN pip install --upgrade pip
COPY requirements.txt /requirements.txt
RUN pip install -r /requirements.txt
COPY main.py /main.py
CMD ["python","main.py","-port","8888","-version","2"]

在这里插入图片描述

构建镜像

docker build -t simple_http:v2 .
Sending build context to Docker daemon  16.25MB
Step 1/6 : From python:3.11
 ---> 815c8c75dfc0
Step 2/6 : RUN pip install --upgrade pip
 ---> Using cache
 ---> e26af84d8b3e
Step 3/6 : COPY requirements.txt /requirements.txt
 ---> Using cache
 ---> 9e14379efd70
Step 4/6 : RUN pip install -r /requirements.txt
 ---> Using cache
 ---> 964f97edf3b5
Step 5/6 : COPY main.py /main.py
 ---> Using cache
 ---> 183ac054cd4d
Step 6/6 : CMD ["python","main.py","-port","8888","-version","2"]
 ---> Running in 1fc7e3afb2c9
Removing intermediate container 1fc7e3afb2c9
 ---> 57ab1ae7f5de
Successfully built 57ab1ae7f5de
Successfully tagged simple_http:v2

推送镜像

docker tag simple_http:v2 localhost:32000/simple_http:v2
docker push localhost:32000/simple_http:v2

上线老版本

直接借用《研发工程师玩转Kubernetes——使用Deployment进行多副本维护》的案例。具体请转到这篇文章。只要部署了2个Pod即可。
使用下面指令查看Pod

kubectl describe pod
Name:             simple-http-deployment-5995f574dc-lzs8v
Namespace:        default
Priority:         0
Service Account:  default
Node:             fangliang-virtual-machine/172.30.45.36
Start Time:       Mon, 22 May 2023 21:27:01 +0800
Labels:           app=simple_http
                  pod-template-hash=5995f574dc
Annotations:      cni.projectcalico.org/containerID: 311e41d76878cb77546a754ad1123556a58c3b3b3ea087634d80dcf6f12240e8
                  cni.projectcalico.org/podIP: 10.1.62.150/32
                  cni.projectcalico.org/podIPs: 10.1.62.150/32
Status:           Running
IP:               10.1.62.150
IPs:
  IP:           10.1.62.150
Controlled By:  ReplicaSet/simple-http-deployment-5995f574dc
Containers:
  simple-http-container:
    Container ID:   containerd://5f722b33ba614ae1c4351567e0fb07946cb26b8529d55ab1ca9168f1af4563b8
    Image:          localhost:32000/simple_http:v1
    Image ID:       localhost:32000/simple_http@sha256:cbee584f83426593efb95a9e2213bb40143a1c86c3d217e65d30430033f846d4
    Port:           8888/TCP
    Host Port:      0/TCP
    State:          Running
      Started:      Mon, 22 May 2023 21:27:03 +0800
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-62cr6 (ro)
Conditions:
  Type              Status
  Initialized       True 
  Ready             True 
  ContainersReady   True 
  PodScheduled      True 
Volumes:
  kube-api-access-62cr6:
    Type:                    Projected (a volume that contains injected data from multiple sources)
    TokenExpirationSeconds:  3607
    ConfigMapName:           kube-root-ca.crt
    ConfigMapOptional:       <nil>
    DownwardAPI:             true
QoS Class:                   BestEffort
Node-Selectors:              <none>
Tolerations:                 node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                             node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
  Type    Reason     Age   From               Message
  ----    ------     ----  ----               -------
  Normal  Scheduled  22s   default-scheduler  Successfully assigned default/simple-http-deployment-5995f574dc-lzs8v to fangliang-virtual-machine
  Normal  Pulled     22s   kubelet            Container image "localhost:32000/simple_http:v1" already present on machine
  Normal  Created    22s   kubelet            Created container simple-http-container
  Normal  Started    21s   kubelet            Started container simple-http-container


Name:             simple-http-deployment-5995f574dc-l7zwv
Namespace:        default
Priority:         0
Service Account:  default
Node:             fangliang-virtual-machine/172.30.45.36
Start Time:       Mon, 22 May 2023 21:27:01 +0800
Labels:           app=simple_http
                  pod-template-hash=5995f574dc
Annotations:      cni.projectcalico.org/containerID: 613a62e30933c3715b43de4e83ccf1baa93e53ac1434cf63dd93178a5214c992
                  cni.projectcalico.org/podIP: 10.1.62.149/32
                  cni.projectcalico.org/podIPs: 10.1.62.149/32
Status:           Running
IP:               10.1.62.149
IPs:
  IP:           10.1.62.149
Controlled By:  ReplicaSet/simple-http-deployment-5995f574dc
Containers:
  simple-http-container:
    Container ID:   containerd://e52726f94486008b8bd375e0dac3243ad534186ea63d7ca5ae522c68fb05d89a
    Image:          localhost:32000/simple_http:v1
    Image ID:       localhost:32000/simple_http@sha256:cbee584f83426593efb95a9e2213bb40143a1c86c3d217e65d30430033f846d4
    Port:           8888/TCP
    Host Port:      0/TCP
    State:          Running
      Started:      Mon, 22 May 2023 21:27:03 +0800
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-5hpdv (ro)
Conditions:
  Type              Status
  Initialized       True 
  Ready             True 
  ContainersReady   True 
  PodScheduled      True 
Volumes:
  kube-api-access-5hpdv:
    Type:                    Projected (a volume that contains injected data from multiple sources)
    TokenExpirationSeconds:  3607
    ConfigMapName:           kube-root-ca.crt
    ConfigMapOptional:       <nil>
    DownwardAPI:             true
QoS Class:                   BestEffort
Node-Selectors:              <none>
Tolerations:                 node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                             node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
  Type    Reason     Age   From               Message
  ----    ------     ----  ----               -------
  Normal  Scheduled  22s   default-scheduler  Successfully assigned default/simple-http-deployment-5995f574dc-l7zwv to fangliang-virtual-machine
  Normal  Pulled     22s   kubelet            Container image "localhost:32000/simple_http:v1" already present on machine
  Normal  Created    22s   kubelet            Created container simple-http-container
  Normal  Started    21s   kubelet            Started container simple-http-container

可以看到两个Pod(simple-http-deployment-5995f574dc-lzs8v和simple-http-deployment-5995f574dc-l7zwv)对应的Image都是localhost:32000/simple_http:v1。

查看Deployment

kubectl describe deployments.apps simple-http-deployment 
Name:                   simple-http-deployment
Namespace:              default
CreationTimestamp:      Mon, 22 May 2023 21:27:01 +0800
Labels:                 <none>
Annotations:            deployment.kubernetes.io/revision: 1
Selector:               app=simple_http
Replicas:               2 desired | 2 updated | 2 total | 2 available | 0 unavailable
StrategyType:           RollingUpdate
MinReadySeconds:        0
RollingUpdateStrategy:  25% max unavailable, 25% max surge
Pod Template:
  Labels:  app=simple_http
  Containers:
   simple-http-container:
    Image:        localhost:32000/simple_http:v1
    Port:         8888/TCP
    Host Port:    0/TCP
    Environment:  <none>
    Mounts:       <none>
  Volumes:        <none>
Conditions:
  Type           Status  Reason
  ----           ------  ------
  Available      True    MinimumReplicasAvailable
  Progressing    True    NewReplicaSetAvailable
OldReplicaSets:  <none>
NewReplicaSet:   simple-http-deployment-5995f574dc (2/2 replicas created)
Events:
  Type    Reason             Age    From                   Message
  ----    ------             ----   ----                   -------
  Normal  ScalingReplicaSet  3m16s  deployment-controller  Scaled up replica set simple-http-deployment-5995f574dc to 2

此时我们看到该Deployment管理的ReplicaSet是simple-http-deployment-5995f574dc。

更新

kubectl set image deployments/simple-http-deployment simple-http-container=localhost:32000/simple_http:v2

deployment.apps/simple-http-deployment image updated

我们查看下Pod

Name:             simple-http-deployment-576c865db-k48mn
Namespace:        default
Priority:         0
Service Account:  default
Node:             fangliang-virtual-machine/172.30.45.36
Start Time:       Mon, 22 May 2023 21:32:16 +0800
Labels:           app=simple_http
                  pod-template-hash=576c865db
Annotations:      cni.projectcalico.org/containerID: e35c8331fb45eeef955671d86bcd5156082246875362f2a87b87ac8be05fdfe6
                  cni.projectcalico.org/podIP: 10.1.62.147/32
                  cni.projectcalico.org/podIPs: 10.1.62.147/32
Status:           Running
IP:               10.1.62.147
IPs:
  IP:           10.1.62.147
Controlled By:  ReplicaSet/simple-http-deployment-576c865db
Containers:
  simple-http-container:
    Container ID:   containerd://ffe70fe17696d901bb2a460469ae318bccfac95e0fe6f0ca0e157308641615d1
    Image:          localhost:32000/simple_http:v2
    Image ID:       localhost:32000/simple_http@sha256:213ba4174b3afac02b48af19258c03b32a426d31ca27742e05aacea7a7a6edc1
    Port:           8888/TCP
    Host Port:      0/TCP
    State:          Running
      Started:      Mon, 22 May 2023 21:32:18 +0800
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-5z9dp (ro)
Conditions:
  Type              Status
  Initialized       True 
  Ready             True 
  ContainersReady   True 
  PodScheduled      True 
Volumes:
  kube-api-access-5z9dp:
    Type:                    Projected (a volume that contains injected data from multiple sources)
    TokenExpirationSeconds:  3607
    ConfigMapName:           kube-root-ca.crt
    ConfigMapOptional:       <nil>
    DownwardAPI:             true
QoS Class:                   BestEffort
Node-Selectors:              <none>
Tolerations:                 node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                             node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
  Type    Reason     Age   From               Message
  ----    ------     ----  ----               -------
  Normal  Scheduled  38s   default-scheduler  Successfully assigned default/simple-http-deployment-576c865db-k48mn to fangliang-virtual-machine
  Normal  Pulling    38s   kubelet            Pulling image "localhost:32000/simple_http:v2"
  Normal  Pulled     38s   kubelet            Successfully pulled image "localhost:32000/simple_http:v2" in 119.472724ms (119.476524ms including waiting)
  Normal  Created    38s   kubelet            Created container simple-http-container
  Normal  Started    37s   kubelet            Started container simple-http-container


Name:             simple-http-deployment-576c865db-bjwns
Namespace:        default
Priority:         0
Service Account:  default
Node:             fangliang-virtual-machine/172.30.45.36
Start Time:       Mon, 22 May 2023 21:32:18 +0800
Labels:           app=simple_http
                  pod-template-hash=576c865db
Annotations:      cni.projectcalico.org/containerID: 11f76fe799f1b5a3d4899305e9443d2bcedc5f815c28c8c44f8664f93cc150e4
                  cni.projectcalico.org/podIP: 10.1.62.156/32
                  cni.projectcalico.org/podIPs: 10.1.62.156/32
Status:           Running
IP:               10.1.62.156
IPs:
  IP:           10.1.62.156
Controlled By:  ReplicaSet/simple-http-deployment-576c865db
Containers:
  simple-http-container:
    Container ID:   containerd://2459b017ee5fb29ac61f488ffc0eabb0016f5a18bf6b031345480d9d2fb3c84a
    Image:          localhost:32000/simple_http:v2
    Image ID:       localhost:32000/simple_http@sha256:213ba4174b3afac02b48af19258c03b32a426d31ca27742e05aacea7a7a6edc1
    Port:           8888/TCP
    Host Port:      0/TCP
    State:          Running
      Started:      Mon, 22 May 2023 21:32:19 +0800
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-4lp5j (ro)
Conditions:
  Type              Status
  Initialized       True 
  Ready             True 
  ContainersReady   True 
  PodScheduled      True 
Volumes:
  kube-api-access-4lp5j:
    Type:                    Projected (a volume that contains injected data from multiple sources)
    TokenExpirationSeconds:  3607
    ConfigMapName:           kube-root-ca.crt
    ConfigMapOptional:       <nil>
    DownwardAPI:             true
QoS Class:                   BestEffort
Node-Selectors:              <none>
Tolerations:                 node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                             node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
  Type    Reason     Age   From               Message
  ----    ------     ----  ----               -------
  Normal  Scheduled  37s   default-scheduler  Successfully assigned default/simple-http-deployment-576c865db-bjwns to fangliang-virtual-machine
  Normal  Pulled     36s   kubelet            Container image "localhost:32000/simple_http:v2" already present on machine
  Normal  Created    36s   kubelet            Created container simple-http-container
  Normal  Started    36s   kubelet            Started container simple-http-container

老的Pod(simple-http-deployment-5995f574dc-lzs8v和simple-http-deployment-5995f574dc-l7zwv)被删除了,新的Pod( simple-http-deployment-576c865db-k48mn和simple-http-deployment-576c865db-bjwns)被创建出来。

查看ReplicaSet

kubectl describe replicasets.apps 
Name:           simple-http-deployment-576c865db
Namespace:      default
Selector:       app=simple_http,pod-template-hash=576c865db
Labels:         app=simple_http
                pod-template-hash=576c865db
Annotations:    deployment.kubernetes.io/desired-replicas: 2
                deployment.kubernetes.io/max-replicas: 3
                deployment.kubernetes.io/revision: 2
Controlled By:  Deployment/simple-http-deployment
Replicas:       2 current / 2 desired
Pods Status:    2 Running / 0 Waiting / 0 Succeeded / 0 Failed
Pod Template:
  Labels:  app=simple_http
           pod-template-hash=576c865db
  Containers:
   simple-http-container:
    Image:        localhost:32000/simple_http:v2
    Port:         8888/TCP
    Host Port:    0/TCP
    Environment:  <none>
    Mounts:       <none>
  Volumes:        <none>
Events:
  Type    Reason            Age   From                   Message
  ----    ------            ----  ----                   -------
  Normal  SuccessfulCreate  97s   replicaset-controller  Created pod: simple-http-deployment-576c865db-k48mn
  Normal  SuccessfulCreate  95s   replicaset-controller  Created pod: simple-http-deployment-576c865db-bjwns


Name:           simple-http-deployment-5995f574dc
Namespace:      default
Selector:       app=simple_http,pod-template-hash=5995f574dc
Labels:         app=simple_http
                pod-template-hash=5995f574dc
Annotations:    deployment.kubernetes.io/desired-replicas: 2
                deployment.kubernetes.io/max-replicas: 3
                deployment.kubernetes.io/revision: 1
Controlled By:  Deployment/simple-http-deployment
Replicas:       0 current / 0 desired
Pods Status:    0 Running / 0 Waiting / 0 Succeeded / 0 Failed
Pod Template:
  Labels:  app=simple_http
           pod-template-hash=5995f574dc
  Containers:
   simple-http-container:
    Image:        localhost:32000/simple_http:v1
    Port:         8888/TCP
    Host Port:    0/TCP
    Environment:  <none>
    Mounts:       <none>
  Volumes:        <none>
Events:
  Type    Reason            Age   From                   Message
  ----    ------            ----  ----                   -------
  Normal  SuccessfulDelete  95s   replicaset-controller  Deleted pod: simple-http-deployment-5995f574dc-l7zwv
  Normal  SuccessfulDelete  93s   replicaset-controller  Deleted pod: simple-http-deployment-5995f574dc-lzs8v

可以看到老的ReplicaSet在删除老Pod,新的则创建了新的Pod。
再过段时间执行上述命令,可以看到老的ReplicaSet并没有被删除。

Name:           simple-http-deployment-576c865db
Namespace:      default
Selector:       app=simple_http,pod-template-hash=576c865db
Labels:         app=simple_http
                pod-template-hash=576c865db
Annotations:    deployment.kubernetes.io/desired-replicas: 2
                deployment.kubernetes.io/max-replicas: 3
                deployment.kubernetes.io/revision: 2
Controlled By:  Deployment/simple-http-deployment
Replicas:       2 current / 2 desired
Pods Status:    2 Running / 0 Waiting / 0 Succeeded / 0 Failed
Pod Template:
  Labels:  app=simple_http
           pod-template-hash=576c865db
  Containers:
   simple-http-container:
    Image:        localhost:32000/simple_http:v2
    Port:         8888/TCP
    Host Port:    0/TCP
    Environment:  <none>
    Mounts:       <none>
  Volumes:        <none>
Events:           <none>


Name:           simple-http-deployment-5995f574dc
Namespace:      default
Selector:       app=simple_http,pod-template-hash=5995f574dc
Labels:         app=simple_http
                pod-template-hash=5995f574dc
Annotations:    deployment.kubernetes.io/desired-replicas: 2
                deployment.kubernetes.io/max-replicas: 3
                deployment.kubernetes.io/revision: 1
Controlled By:  Deployment/simple-http-deployment
Replicas:       0 current / 0 desired
Pods Status:    0 Running / 0 Waiting / 0 Succeeded / 0 Failed
Pod Template:
  Labels:  app=simple_http
           pod-template-hash=5995f574dc
  Containers:
   simple-http-container:
    Image:        localhost:32000/simple_http:v1
    Port:         8888/TCP
    Host Port:    0/TCP
    Environment:  <none>
    Mounts:       <none>
  Volumes:        <none>
Events:           <none>

查看Deployment更新后信息

kubectl describe deployments.apps 
Name:                   simple-http-deployment
Namespace:              default
CreationTimestamp:      Mon, 22 May 2023 21:27:01 +0800
Labels:                 <none>
Annotations:            deployment.kubernetes.io/revision: 2
Selector:               app=simple_http
Replicas:               2 desired | 2 updated | 2 total | 2 available | 0 unavailable
StrategyType:           RollingUpdate
MinReadySeconds:        0
RollingUpdateStrategy:  25% max unavailable, 25% max surge
Pod Template:
  Labels:  app=simple_http
  Containers:
   simple-http-container:
    Image:        localhost:32000/simple_http:v2
    Port:         8888/TCP
    Host Port:    0/TCP
    Environment:  <none>
    Mounts:       <none>
  Volumes:        <none>
Conditions:
  Type           Status  Reason
  ----           ------  ------
  Available      True    MinimumReplicasAvailable
  Progressing    True    NewReplicaSetAvailable
OldReplicaSets:  <none>
NewReplicaSet:   simple-http-deployment-576c865db (2/2 replicas created)
Events:          <none>

可以看到NewReplicaSet被更新为新的ReplicaSet simple-http-deployment-576c865db 。老的ReplicaSet simple-http-deployment-5995f574dcz在这儿没有体现。

回滚

 kubectl rollout undo deployment simple-http-deployment

deployment.apps/simple-http-deployment rolled back

查看Deployment

kubectl describe deployments.apps
Name:                   simple-http-deployment
Namespace:              default
CreationTimestamp:      Mon, 22 May 2023 21:27:01 +0800
Labels:                 <none>
Annotations:            deployment.kubernetes.io/revision: 3
Selector:               app=simple_http
Replicas:               2 desired | 2 updated | 2 total | 2 available | 0 unavailable
StrategyType:           RollingUpdate
MinReadySeconds:        0
RollingUpdateStrategy:  25% max unavailable, 25% max surge
Pod Template:
  Labels:  app=simple_http
  Containers:
   simple-http-container:
    Image:        localhost:32000/simple_http:v1
    Port:         8888/TCP
    Host Port:    0/TCP
    Environment:  <none>
    Mounts:       <none>
  Volumes:        <none>
Conditions:
  Type           Status  Reason
  ----           ------  ------
  Available      True    MinimumReplicasAvailable
  Progressing    True    NewReplicaSetAvailable
OldReplicaSets:  <none>
NewReplicaSet:   simple-http-deployment-5995f574dc (2/2 replicas created)
Events:
  Type    Reason             Age   From                   Message
  ----    ------             ----  ----                   -------
  Normal  ScalingReplicaSet  4s    deployment-controller  Scaled up replica set simple-http-deployment-5995f574dc to 1 from 0
  Normal  ScalingReplicaSet  3s    deployment-controller  Scaled down replica set simple-http-deployment-576c865db to 1 from 2
  Normal  ScalingReplicaSet  3s    deployment-controller  Scaled up replica set simple-http-deployment-5995f574dc to 2 from 1
  Normal  ScalingReplicaSet  1s    deployment-controller  Scaled down replica set simple-http-deployment-576c865db to 0 from 1

可以看到最开始V1版本对应的ReplicaSet simple-http-deployment-5995f574dc又被启用,镜像也变成了三个版本localhost:32000/simple_http:v1。

查看ReplicaSet

kubectl describe replicasets.apps 
Name:           simple-http-deployment-5995f574dc
Namespace:      default
Selector:       app=simple_http,pod-template-hash=5995f574dc
Labels:         app=simple_http
                pod-template-hash=5995f574dc
Annotations:    deployment.kubernetes.io/desired-replicas: 2
                deployment.kubernetes.io/max-replicas: 3
                deployment.kubernetes.io/revision: 3
                deployment.kubernetes.io/revision-history: 1
Controlled By:  Deployment/simple-http-deployment
Replicas:       2 current / 2 desired
Pods Status:    2 Running / 0 Waiting / 0 Succeeded / 0 Failed
Pod Template:
  Labels:  app=simple_http
           pod-template-hash=5995f574dc
  Containers:
   simple-http-container:
    Image:        localhost:32000/simple_http:v1
    Port:         8888/TCP
    Host Port:    0/TCP
    Environment:  <none>
    Mounts:       <none>
  Volumes:        <none>
Events:
  Type    Reason            Age   From                   Message
  ----    ------            ----  ----                   -------
  Normal  SuccessfulCreate  24s   replicaset-controller  Created pod: simple-http-deployment-5995f574dc-6dmtt
  Normal  SuccessfulCreate  23s   replicaset-controller  Created pod: simple-http-deployment-5995f574dc-547sp


Name:           simple-http-deployment-576c865db
Namespace:      default
Selector:       app=simple_http,pod-template-hash=576c865db
Labels:         app=simple_http
                pod-template-hash=576c865db
Annotations:    deployment.kubernetes.io/desired-replicas: 2
                deployment.kubernetes.io/max-replicas: 3
                deployment.kubernetes.io/revision: 2
Controlled By:  Deployment/simple-http-deployment
Replicas:       0 current / 0 desired
Pods Status:    2 Running / 0 Waiting / 0 Succeeded / 0 Failed
Pod Template:
  Labels:  app=simple_http
           pod-template-hash=576c865db
  Containers:
   simple-http-container:
    Image:        localhost:32000/simple_http:v2
    Port:         8888/TCP
    Host Port:    0/TCP
    Environment:  <none>
    Mounts:       <none>
  Volumes:        <none>
Events:
  Type    Reason            Age   From                   Message
  ----    ------            ----  ----                   -------
  Normal  SuccessfulDelete  23s   replicaset-controller  Deleted pod: simple-http-deployment-576c865db-bjwns
  Normal  SuccessfulDelete  21s   replicaset-controller  Deleted pod: simple-http-deployment-576c865db-k48mn

可以看到V2版本对应的ReplicaSet还存在。
这是否意味着再次回滚又会回滚到V2呢?是的。

再回滚

再将kubectl rollout undo deployment simple-http-deployment执行一遍,可以发现Deployment又启用了V2版本对应的simple-http-deployment-576c865db,弃用了V1版本对应的simple-http-deployment-5995f574dc。

kubectl describe replicasets.apps
Name:           simple-http-deployment-576c865db
Namespace:      default
Selector:       app=simple_http,pod-template-hash=576c865db
Labels:         app=simple_http
                pod-template-hash=576c865db
Annotations:    deployment.kubernetes.io/desired-replicas: 2
                deployment.kubernetes.io/max-replicas: 3
                deployment.kubernetes.io/revision: 4
                deployment.kubernetes.io/revision-history: 2
Controlled By:  Deployment/simple-http-deployment
Replicas:       2 current / 2 desired
Pods Status:    2 Running / 0 Waiting / 0 Succeeded / 0 Failed
Pod Template:
  Labels:  app=simple_http
           pod-template-hash=576c865db
  Containers:
   simple-http-container:
    Image:        localhost:32000/simple_http:v2
    Port:         8888/TCP
    Host Port:    0/TCP
    Environment:  <none>
    Mounts:       <none>
  Volumes:        <none>
Events:
  Type    Reason            Age   From                   Message
  ----    ------            ----  ----                   -------
  Normal  SuccessfulCreate  8s    replicaset-controller  Created pod: simple-http-deployment-576c865db-qm5gp
  Normal  SuccessfulCreate  7s    replicaset-controller  Created pod: simple-http-deployment-576c865db-bzbbw


Name:           simple-http-deployment-5995f574dc
Namespace:      default
Selector:       app=simple_http,pod-template-hash=5995f574dc
Labels:         app=simple_http
                pod-template-hash=5995f574dc
Annotations:    deployment.kubernetes.io/desired-replicas: 2
                deployment.kubernetes.io/max-replicas: 3
                deployment.kubernetes.io/revision: 3
                deployment.kubernetes.io/revision-history: 1
Controlled By:  Deployment/simple-http-deployment
Replicas:       0 current / 0 desired
Pods Status:    2 Running / 0 Waiting / 0 Succeeded / 0 Failed
Pod Template:
  Labels:  app=simple_http
           pod-template-hash=5995f574dc
  Containers:
   simple-http-container:
    Image:        localhost:32000/simple_http:v1
    Port:         8888/TCP
    Host Port:    0/TCP
    Environment:  <none>
    Mounts:       <none>
  Volumes:        <none>
Events:
  Type    Reason            Age   From                   Message
  ----    ------            ----  ----                   -------
  Normal  SuccessfulDelete  7s    replicaset-controller  Deleted pod: simple-http-deployment-5995f574dc-6dmtt
  Normal  SuccessfulDelete  5s    replicaset-controller  Deleted pod: simple-http-deployment-5995f574dc-547sp

通过这次实验,我们就更好理解Deployment是如何使用ReplicaSet来做版本管理的了。
在这里插入图片描述

<think> 我们参考用户提供的引用[1][2][3],特别是引用[3]中关于Deployment操作的Go语言实现,来编写重启Deployment的代码。 重启Deployment的常见方法有两种: 1. 修改Deployment的spec.template.metadata.annotations,添加一个重启标记(如时间戳),从而触发滚动更新。 2. 通过缩放副本数:先缩容到0,然后再恢复到原来的副本数(这种方法会导致服务中断,不推荐在生产环境使用)。 根据引用[3]中的内容,我们可以使用client-go库来操作Deployment。这里我们采用第一种方法(添加annotation)来实现重启。 步骤: 1. 获取当前Deployment对象。 2. 修改Deployment的Pod模板的annotations,添加一个重启标记(例如:kubectl.kubernetes.io/restartedAt,值为当前时间)。 3. 使用Update方法更新Deployment。 注意:在引用[3]中,我们看到了Deployment的结构体定义,以及如何通过client-go进行更新操作。 代码示例: </think> ### 使用 Go 语言通过 Kubernetes API 重启 DeploymentKubernetes 中重启 Deployment 的核心原理是**修改 Deployment 配置触发滚动更新**。以下是基于 client-go 库的实现方法,结合引用[1][2][3]的 Go 语言操作指南: #### 推荐方法:添加重启注解(声明式) 这是 `kubectl rollout restart` 的底层实现原理,通过修改 Pod 模板注解触发滚动更新: ```go package main import ( "context" "fmt" "time" appsv1 "k8s.io/api/apps/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" "k8s.io/client-go/tools/clientcmd" ) func main() { // 1. 加载 kubeconfig config, err := clientcmd.BuildConfigFromFlags("", "/path/to/kubeconfig") if err != nil { panic(err.Error()) } // 2. 创建 clientset clientset, err := kubernetes.NewForConfig(config) if err != nil { panic(err.Error()) } // 3. 构造 Patch 数据(引用[2]的 API 操作) patch := `{ "spec": { "template": { "metadata": { "annotations": { "kubectl.kubernetes.io/restartedAt": "%s" } } } } }` restartTime := time.Now().UTC().Format(time.RFC3339) patchData := fmt.Sprintf(patch, restartTime) // 4. 执行 Patch 操作(引用[3]的 Deployment 操作) deployments := clientset.AppsV1().Deployments("default") _, err = deployments.Patch( context.TODO(), "your-deployment", // 替换为 Deployment 名称 types.StrategicMergePatchType, []byte(patchData), metav1.PatchOptions{}, ) if err != nil { panic(err.Error()) } fmt.Println("Deployment 重启指令已发送") } ``` **实现原理**: 1. 添加 `kubectl.kubernetes.io/restartedAt` 时间戳注解 2. Kubernetes 检测到 Pod 模板变更(引用[1]的声明式管理) 3. 自动触发滚动更新(引用[3]的 Deployment 状态管理) #### 备选方法:副本数缩放(命令式) ```go // 缩放副本数重启(不推荐生产环境使用) func restartByScaling(clientset *kubernetes.Clientset) { deployments := clientset.AppsV1().Deployments("default") // 获取当前副本数(引用[3]的 DeploymentSpec) deploy, _ := deployments.Get(context.TODO(), "your-deployment", metav1.GetOptions{}) originalReplicas := *deploy.Spec.Replicas // 缩容到0 zero := int32(0) deploy.Spec.Replicas = &zero deployments.Update(context.TODO(), deploy, metav1.UpdateOptions{}) // 等待10秒 time.Sleep(10 * time.Second) // 恢复原始副本数 deploy.Spec.Replicas = &originalReplicas deployments.Update(context.TODO(), deploy, metav1.UpdateOptions{}) } ``` #### 关键配置说明 1. **RBAC 权限**(引用[1]的安全管理) ```yaml apiVersion: rbac.authorization.k8s.io/v1 kind: Role rules: - apiGroups: ["apps"] resources: ["deployments"] verbs: ["get", "patch", "update"] # 必要权限 ``` 2. **client-go 导入**(引用[2]的库引用) ```go import ( appsv1 "k8s.io/api/apps/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" "k8s.io/client-go/tools/clientcmd" ) ``` 3. **错误处理建议** ```go if errors.IsNotFound(err) { fmt.Println("Deployment 不存在") } else if statusError, isStatus := err.(*errors.StatusError); isStatus { fmt.Printf("API 错误: %v\n", statusError.ErrStatus.Message) } else { panic(err.Error()) } ``` #### 最佳实践 1. **状态验证**(引用[3]的 DeploymentStatus) ```go // 检查滚动更新状态 for { deploy, _ := deployments.Get(context.TODO(), "your-deployment", metav1.GetOptions{}) if deploy.Status.UpdatedReplicas == *deploy.Spec.Replicas { fmt.Println("重启完成") break } time.Sleep(2 * time.Second) } ``` 2. **连接集群方式** | 环境 | 配置方法 | |------------|----------------------------| | 本地开发 | `clientcmd.BuildConfigFromFlags("", kubeconfig)` | | Pod内运行 | `rest.InClusterConfig()` | 此实现完全遵循 Kubernetes 的声明式管理原则[^1],通过 Go 语言原生客户端提供高效可靠的操作方案[^2][^3]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

breaksoftware

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值