一.subpath简单说明
在Pod中共享卷以供多方使用是很有用的。VolumeMounts.subPath属性可用于指定所引用的卷内的子路径,而不是其根路径。
二.subpath使用场景
- 1个Pod中可以有多个容器,这里将不同容器的路径挂载在存储卷volume的子路径,这种场景需要使用到subpath。
- volume支持将configMap/secret挂载到容器的路径,但是会覆盖容器路径下原有的文件。如何支持选定configmap/secret的key-value挂载到容器中,且不会覆盖掉原目录下的文件,这个时候可以用subpath。
2.1 存储卷挂载
# 这里我们提前创建好一个PVC-CLAIM名称为pvc-subpath
[root@k8s001 subpath]# cat pvc.yaml
---
kind: PersistentVolume
apiVersion: v1
metadata:
name: pv-subpath
labels:
release: stable
spec:
capacity:
storage: 10Gi
accessModes:
- ReadWriteOnce
persistentVolumeReclaimPolicy: Recycle
hostPath:
path: /mnt/yuhaohao # 这个是宿主机真实存在的目录
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: pvc-subpath
namespace: default
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 10Gi
[root@k8s001 subpath]# kubectl apply -f pvc.yaml
[root@k8s001 ~]# cat subpath.yaml
[root@k8s001 subpath]# cat subpath.yaml
apiVersion: v1
kind: Pod
metadata:
name: pod-subpath-yuhaohao
spec:
containers:
- name: redis-container
image: redis
volumeMounts:
- mountPath: /var/lib/redis # 容器1的挂载目录
name: subpath-volume # 这里指定pvc的volume名称
subPath: redispvc # 存储卷pvc-subpath要挂载的/mnt/yuhaohao的子目录
- name: nginx-container
image: nginx
volumeMounts:
- mountPath: /var/www/nginx # 容器2的挂载目录
name: subpath-volume # 这里指定pvc的volume名称
subPath: nginxpvc # 存储卷pvc-subpath要挂载的/mnt/yuhaohao的子目录
volumes:
- name: subpath-volume
persistentVolumeClaim:
claimName: pvc-subpath # PVC的名字
[root@k8s-master zhanglei]# kubectl create -f subpath.yaml
[root@k8s001 subpath]# kubectl get pod
NAME READY STATUS RESTARTS AGE
pod-subpath-yuhaohao 2/2 Running 0 106s
[root@k8s001 yuhaohao]# pwd
/mnt/yuhaohao
[root@k8s001 yuhaohao]# ls
nginxpvc redispvc
2.2 configmap挂载
2.2.1 创建configmap
[root@k8s001 subpath]# cat configmap.yaml
---
apiVersion: v1
kind: ConfigMap
metadata:
name: configmap-subpath
namespace: default
data:
example.property.1: hello # key-value键值对
example.property.2: world
example.property.file: |-
property.1=value-1
property.2=value-2
property.3=value-3
[root@k8s001 subpath]# kubectl apply -f configmap.yaml
configmap/configmap-subpath created
[root@k8s001 subpath]# kubectl get cm
NAME DATA AGE
configmap-subpath 3 35s
[root@k8s001 subpath]# cat pod-configmap.yaml
apiVersion: v1
kind: Pod
metadata:
name: configmap-subpath-test
labels:
purpose: configmap-subpath-test
spec:
containers:
- name: configmap-subpath-test
image: nginx
volumeMounts:
- name: config-volume
mountPath: /etc/nginx/example.property.1 # 容器挂载的目录路径为容器的/etc/nginx,文件名为example.property.1
subPath: example.property.1 # 将key名称作为文件名,hello作为文件内容
volumes:
- name: config-volume
configMap:
name: configmap-subpath # 指定使用哪个CM
[root@k8s001 subpath]# kubectl apply -f pod-configmap.yaml
pod/configmap-subpath-test created
[root@k8s001 subpath]# kubectl get pod
NAME READY STATUS RESTARTS AGE
configmap-subpath-test 1/1 Running 0 7s
[root@k8s001 subpath]# kubectl exec configmap-subpath-test cat /etc/nginx/example.property.1
hello