在 Pod 中共享卷以供多方使用是很有用的。VolumeMounts.subPath 属性可用于指定所引用的卷内的子路径,而不是其根路径。
subPath 的两种使用场景:
- 一个 Pod 中有多个容器时,将不同容器的路径挂载到存储卷的子路径,需要使用 subPath。
- Volume 支持将 ConfigMap/Secret 挂载到容器路径,但会覆盖原有文件。使用 subPath 可以只挂载指定的 key,且不覆盖原目录下的其他文件。
一个 Pod 多组容器的情况
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| apiVersion: v1 kind: Pod metadata: name: pod-subpath-yuhaohao spec: containers: - name: redis-container image: redis volumeMounts: - mountPath: /var/lib name: subpath-volume subPath: redispvc - name: nginx-container image: nginx volumeMounts: - mountPath: /var/lib name: subpath-volume subPath: nginxpvc volumes: - name: subpath-volume persistentVolumeClaim: claimName: pvc-subpath
|
测试: 进入 redis-container 在 /var/lib 下创建 a.txt,退出后进入 nginx-container 的 /var/lib 目录。若未指定 subPath,文件直接存于卷根目录,nginx-container 可见该文件;若指定了 subPath,两个容器的挂载路径相互隔离,nginx-container 无法看见 redis-container 创建的文件。
指定 ConfigMap/Secret 中的某个 key 作为挂载
1 2 3 4 5 6 7
| apiVersion: v1 kind: ConfigMap metadata: name: config-test data: config.ini: "hello" config.conf: "nihao"
|
单独挂载一个 key 为文件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| apiVersion: v1 kind: Pod metadata: name: testpod spec: containers: - name: testc image: busybox command: ["/bin/sleep","10000"] volumeMounts: - name: config-test mountPath: /etc/config.ini subPath: config.ini volumes: - name: config-test configMap: name: config-test
|
挂载多个 key 为文件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| apiVersion: v1 kind: Pod metadata: name: testpod2 spec: containers: - name: testc image: busybox command: ["/bin/sleep","10000"] volumeMounts: - name: config-test mountPath: /etc/config.ini subPath: config.ini - name: config-test mountPath: /etc/config.conf subPath: config.conf volumes: - name: config-test configMap: name: config-test
|
多个 container 挂载不同的 key:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| apiVersion: v1 kind: Pod metadata: name: testpod1 spec: containers: - name: testc imagePullPolicy: Never image: busybox command: ["/bin/sleep","10000"] volumeMounts: - name: config-test mountPath: /etc/config/config.ini subPath: config.ini - name: testc1 imagePullPolicy: Never image: busybox command: ["/bin/sleep","10000"] volumeMounts: - name: config-test mountPath: /etc/config/config.conf subPath: config.conf volumes: - name: config-test configMap: name: config-test items: - key: config.ini path: config.ini - key: config.conf path: config.conf
|