如何在不编辑运行中Deployment的情况下附加额外存储卷
无需编辑Deployment即可附加新存储卷的解决方案
针对你提到的运行中Deployment,不用手动编辑yaml或使用kubectl edit,直接用kubectl patch命令就能增量添加新的存储卷和挂载配置,具体步骤如下:
1. 提前准备新的PVC(如果需要)
如果新存储卷需要对应的PersistentVolumeClaim,先创建它(替换下方的存储类和容量参数):
kubectl create pvc my-new-pv-claim -n httpd-test --storage-class=your-storage-class --resources=requests.storage=1Gi --access-modes=ReadWriteOnce
2. 用kubectl patch添加卷和挂载
方法一:JSON Patch(精确指定修改操作)
执行这条命令,给Deployment的Pod模板追加新的卷定义和容器挂载:
kubectl patch deployment httpd-deployment -n httpd-test --type='json' -p='[ {"op": "add", "path": "/spec/template/spec/volumes/-", "value": {"name": "my-new-pv-storage", "persistentVolumeClaim": {"claimName": "my-new-pv-claim"}}}, {"op": "add", "path": "/spec/template/spec/containers/0/volumeMounts/-", "value": {"mountPath": "/data/new-test", "name": "my-new-pv-storage"}} ]'
这里的-符号表示在数组末尾追加元素,不会影响已有的卷配置。
方法二:Merge Patch(更直观的yaml格式)
如果觉得JSON语法麻烦,用Merge Patch更易读:
kubectl patch deployment httpd-deployment -n httpd-test --type='merge' -p=' spec: template: spec: volumes: - name: my-new-pv-storage persistentVolumeClaim: claimName: my-new-pv-claim containers: - name: httpd-container volumeMounts: - mountPath: "/data/new-test" name: my-new-pv-storage '
3. 验证配置是否生效
检查Deployment的更新:
kubectl get deployment httpd-deployment -n httpd-test -o yaml | grep -A5 -B5 "my-new-pv-storage"
或者进入Pod确认新卷已挂载:
kubectl exec -n httpd-test $(kubectl get pods -n httpd-test -l app=httpd_app -o name | head -n1) -- df -h /data/new-test
补充说明
你之前尝试的sed修改本地yaml再apply,本质还是编辑了Deployment配置;而kubectl patch是通过K8s API做增量更新,只会修改你指定的字段,不会触碰其他配置,完全符合“不编辑运行中Deployment”的要求。动态配置只是负责创建PV,和更新Deployment挂载是两回事,需要配合patch命令完成最终的挂载操作。
内容的提问来源于stack exchange,提问作者Sivaksr27
相关产品推荐
相关产品推荐

