Kubernetes: Connecting Multiple Pods to the same PVC with different mount path
Ever wondered, if there was a way so that multiple pods in a deployment could have different mount paths within the same PVC? Well it’s achievable! In this article, we are going to talk about that.
The advantage — we will be able to reduce the number of PVCs, as no matter how many pods, we can create different mount location within the same PVC! This will be useful specially in case of cloud premises wherein there are limited resources and cost associated with the usage.
We are going to use volumeMounts.subPath property that specifies a sub-path inside the referenced volume.
Let us create a PersistentVolumeClaim which will be used by our pods -
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: mpod-pvc
spec:
accessModes:
- ReadWriteMany
resources:
requests:
storage: 1Gi
- Run the following command to create the PVC named mpod-pvc
kubectl apply -f mpod-pvc.yaml
- Now we will create two sample pods mpod1 & mpod2 that are going to use the PVC mpod-pvc that we have created earlier.
apiVersion: v1
kind: Pod
metadata:
name: mpod1
spec:
containers:
- name: nginx
image: nginx
volumeMounts:
- name: mpod
mountPath: /hey
subPath: pod1
volumes:
- name: mpod
persistentVolumeClaim:
claimName: mpod-pvc
apiVersion: v1
kind: Pod
metadata:
name: mpod2
spec:
containers:
- name: nginx
image: nginx
volumeMounts:
- name: mpod
mountPath: /hii
subPath: pod2
volumes:
- name: mpod
persistentVolumeClaim:
claimName: mpod-pvc
- run the following command to create the pods mpod1 & mpod2. Notice that we have added subPath property that will specify the directory inside the PVC.
kubectl apply -f mpod1.yaml
kubectl apply -f mpod2.yaml
kubectl get po

- Once the pods are up and running, we can view the PVC to get the persistentVolume(PV) name. Run the following command —
kubectl get pvc mpod-pvc

This would display the name of the PV. We will then need to describe this PV to get the actual mount path using the following command:
kubectl describe pv <pv-name>
We can find the mount path in path attribute of source. Let’s go inside the path —

Notice there are two directories inside our PV, pod1 & pod2. These are the same directories that we specified in the subPath attribute. Now we will enter inside pod mpod2 using the command :
kubectl exec -it mpod2 -- bash

Let’s go inside the /hii directory inside mpod2. It will be empty. Now we will create a sample python file xyz.py from here to check if it gets reflected inside our PV.
touch xyz.py

Now if we go inside the PV in the /pod2 directory, we can see our text file xyz.py that we created inside the mpod2.
Congratulations! We were able to create separate mount paths for our pods within the same PVC. With this, we will now be able to make optimum utilization of our resources in the cloud premises.