subPath is used to select a specific Path within the volume from which the container's volume should be mounted. This Defaults to "" (volume's root).
Check this mentioned here. So what that means is that you can still mount a volume on the path mentioned in your mountPath but instead of mounting it from the volume root, you can specify a separate subpath within the volume to be mounted under the volumeMount directory in your container.
To clarify on what this means, i created a simple volume on my minikube node.
docker@minikube:/mnt/data$ ls -lrth
total 8.0K
drwxr-xr-x 2 root root 4.0K Dec 30 16:23 path1
drwxr-xr-x 2 root root 4.0K Dec 30 16:23 path2
docker@minikube:/mnt/data$
docker@minikube:/mnt/data$ pwd
/mnt/data
As you can see that in this case, i have a directory and i have created two sub directories inside this volume. Under each of these path1 or path2 folder i have placed a different index file.
docker@minikube:/mnt/data$ pwd
/mnt/data
docker@minikube:/mnt/data$ cat path1/index.html
This is index file from path1
docker@minikube:/mnt/data$
docker@minikube:/mnt/data$ cat path2/index.html
This is index file from path2
docker@minikube:/mnt/data$
Now I created a sample PV using this volume on my minikube node using the sample manifest as below
apiVersion: v1
kind: PersistentVolume
metadata:
name: task-pv-volume
labels:
type: local
spec:
storageClassName: manual
capacity:
storage: 1Gi
accessModes:
- ReadWriteOnce
hostPath:
path: "/mnt/data"
After this, i created the sample PVC using the below manifest
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: task-pv-claim
spec:
storageClassName: manual
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 800Mi
Now if i created a nginx pod and used this PVC under my volume, depending on the subPath config that i use in my pod spec, i will have the volume mounted from that specific subfolder.
i.e. If i used the below manifest for my nginx pod
apiVersion: v1
kind: Pod
metadata:
name: test
spec:
containers:
- name: test
image: nginx
volumeMounts:
# a mount for site-data
- name: config
mountPath: /usr/share/nginx/html
subPath: path1
volumes:
- name: config
persistentVolumeClaim:
claimName: task-pv-claim
and i do a curl on the POD IP, i get the index.html served from path1.
Gauravs-MBP:K8s alieninvader$ kubectl exec -it mycurlpod -- /bin/sh
/ $ curl 172.17.0.3
This is index file from path1
And if i changed my pod manifest and used the subpath as path2, so that the new manifest becomes this
apiVersion: v1
kind: Pod
metadata:
name: test
spec:
containers:
- name: test
image: nginx
volumeMounts:
# a mount for site-data
- name: config
mountPath: /usr/share/nginx/html
subPath: path2
volumes:
- name: config
persistentVolumeClaim:
claimName: task-pv-claim
Then as expected the curl to nginx pod would produce the below output serving the file from path2.
Gauravs-MBP:K8s alieninvader$ kubectl exec -it mycurlpod -- /bin/sh
/ $ curl 172.17.0.3
This is index file from path2
/ $