Kubernetes 滚动更新Deployment负载

负载样例

apiVersion: apps/v1
kind: Deployment
metadata:
  name: busybox
spec: 
  replicas: 1
  selector: 
    matchLabels: 
      app: busybox 
  template: 
    metadata: 
      labels: 
        app: busybox
    spec: 
      containers: 
      - name: busybox
        image: busybox
        args: 
        - /bin/sh
        - -c
        - sleep 10; touch   /tmp/healthy; sleep 30000
        env: 
        - name: MY_NODE_NAME
          valueFrom: 
            fieldRef: 
              fieldPath: spec.nodeName
        - name: MY_POD_NAME
          valueFrom: 
            fieldRef: 
              fieldPath: metadata.name
        readinessProbe: 
          exec: 
            command: 
            - cat 
            - /tmp/healthy
          initialDelaySeconds: 10
          periodSeconds: 5

说明:给当前负载使用downward API把pod的字段作为pod环境变量的值

$ kubectl exec -it busybox-7fd76f8b8b-p2rkw -- printenv  grep MY_
MY_NODE_NAME=node1
MY_POD_NAME=busybox-7fd76f8b8b-p2rkw

使用kubectl patch 命令拼接一个参数给负载,就可以达到重启负载的作用

kubectl patch deploy busybox --patch '{"spec":{"template":{"spec":{"containers":[{"name":"busybox","env":[{"name":"MY_POD_IP","valueFrom":{"fieldRef":{"fieldPath":"status.podIP"}}}]}]}}}}'

相关说明

  • 如果在配置文件中指定了容器名称,则应将 spec.template.spec.containers 字段中的 name 字段设置为容器名称。否则,将为 deployment 中的所有容器添加该环境变量
  • 如果您只想更新 deployment busybox 中的一个 pod,请在命令末尾添加标识符 -l key=value,其中 keyvalue 是您想要标识 pod 的标签键值对

结果如下

# 结果
$ kubectl exec -it busybox-5499d84d7d-xs8rm  -- printenv  grep MY_
MY_POD_NAME=busybox-5499d84d7d-xs8rm
MY_POD_IP=100.108.11.203
MY_NODE_NAME=node2

# deployment 的事件变化
$ kubectl get events -w
0s          Normal   ScalingReplicaSet   deployment/busybox              Scaled up replica set busybox-5499d84d7d to 1
0s          Normal   SuccessfulCreate    replicaset/busybox-5499d84d7d   Created pod: busybox-5499d84d7d-xs8rm
0s          Normal   Scheduled           pod/busybox-5499d84d7d-xs8rm    Successfully assigned default/busybox-5499d84d7d-xs8rm to node2
0s          Normal   Pulling             pod/busybox-5499d84d7d-xs8rm    Pulling image "busybox"
0s          Normal   Pulled              pod/busybox-5499d84d7d-xs8rm    Successfully pulled image "busybox" in 17.650388188s
0s          Normal   Created             pod/busybox-5499d84d7d-xs8rm    Created container busybox
0s          Normal   Started             pod/busybox-5499d84d7d-xs8rm    Started container busybox
0s          Normal   ScalingReplicaSet   deployment/busybox              Scaled down replica set busybox-7fd76f8b8b to 0 from 1
0s          Normal   SuccessfulDelete    replicaset/busybox-7fd76f8b8b   Deleted pod: busybox-7fd76f8b8b-p2rkw
0s          Normal   Killing             pod/busybox-7fd76f8b8b-p2rkw    Stopping container busybox

Kubernetes 滚动更新Deployment负载
http://www.qiqios.cn/2023/04/02/kubernetes-滚动更新deployment负载/
作者
一亩三分地
发布于
2023年4月2日
许可协议