在Pod中共享卷以供多方使用是很有用的。VolumeMounts.subPath属性可用于指定所引用的卷内的子路径,而不是其根路径。
subpath的两种使用场景
- 1个Pod中可以有多个容器,将不同容器的路径挂载在存储卷volume的子路径,这种场景需要使用到subpath。
- volume支持将configMap/secret挂载到容器的路径,但是会覆盖容器路径下原有的文件。如何支持选定configmap/secret的key-value挂载到容器中,且不会覆盖掉原目录下的文件,这个时候可以用subpath。
一个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 # 容器1的挂载目录 name: subpath-volume # 这里指定volumes的volume名称 subPath: redispvc # 存储卷pvc-subpath要挂载的子目录 - name: nginx-container image: nginx volumeMounts: - mountPath: /var/lib # 容器2的挂载目录 name: subpath-volume # 这里指定volumes的volume名称 subPath: nginxpvc # 存储卷pvc-subpath要挂载的子目录 volumes: - name: subpath-volume persistentVolumeClaim: claimName: pvc-subpath
|
测试:
首先进到redis-container中在/var/lib下创建一个a.txt的文件,退出之后进入nginx-container的/var/lib目录,
如果未指定subPath,文件会直接存储在卷的根目录下,所以在nginx-container下可以看见redis-container刚刚新建的a.txt文件
如果指定了subPath, 同样进入两个容器的挂载目录下创建新文件,在nginx-container下是无法看见redis-container新建的文件的, subPath起到了隔离的作用
指定config/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 # 容器挂载的目录路径为容器的/etc,文件名为config.ini subPath: config.ini # 将${key}名称作为文件名,"hello"作为文件内容 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
|