Sub topic 8
Mounting a claim in a Pod
This chapter assumes you can apply YAML with kubectl and that you have already created the demo-pv PersistentVolume and the demo-pvc PersistentVolumeClaim from the previous chapters. Here you connect that claim to a running container.
Two parts: a volume and a mount
A Pod never refers to a PersistentVolume directly. It refers to a claim, in two steps:
- Under
spec.volumes, declare a volume with a name and apersistentVolumeClaim.claimName. - Under each container's
volumeMounts, mount that volume name at a path.
The volume name links the two parts. The claim must be in the same namespace as the Pod.
apiVersion: v1
kind: Pod
metadata:
name: demo-pod
spec:
containers:
- name: app
image: busybox:1.36
command: ["sh", "-c", "date >> /data/log.txt; sleep 3600"]
volumeMounts:
- name: data
mountPath: /data
volumes:
- name: data
persistentVolumeClaim:
claimName: demo-pvcThe container appends the current date to /data/log.txt each time it starts. Because /data is backed by the claim, the file outlives the Pod.
Prove the data survives
Apply the Pod, then delete and recreate it:
kubectl apply -f pod.yaml
kubectl exec demo-pod -- cat /data/log.txt
kubectl delete pod demo-pod
kubectl apply -f pod.yaml
kubectl exec demo-pod -- cat /data/log.txtThe second cat shows two timestamps. The first run's line is still there, and the new Pod added another.
What happens at scheduling time
The scheduler will not place a Pod until every claim it references is bound, or can be bound. If the claim does not exist, or stays Pending, the Pod stays Pending too. Its events then show a message such as persistentvolumeclaim "demo-pvc" not found or pod has unbound immediate PersistentVolumeClaims.
Once the claim is bound, the scheduler also has to respect the volume. A ReadWriteOnce volume can be mounted read-write by one node at a time. Several Pods on that same node may share it, but a Pod on another node cannot attach it until the first node releases it.
Common mistakes
- Wrong namespace. A claim in
defaultcannot be used by a Pod inteam-a. - Mismatched names. The
nameinvolumeMountsmust match a name involumes. TheclaimNamemust match the claim'smetadata.name. - Using
hostPathbeyond a test cluster. The data lives on one node. If the Pod moves to another node, it sees an empty directory. - Forgetting
readOnly. To stop a container from writing, setreadOnly: trueon thevolumeMountsentry. To make the claim itself read-only for the Pod, set it onpersistentVolumeClaim.
Exercise
A Pod references claimName: demo-pvc but stays Pending, and its events say the claim was not found. Name two likely causes and one command to check.
Show answer
The claim may not have been created, or it may be in a different namespace from the Pod. Run kubectl get pvc -n <pod-namespace> to see whether demo-pvc exists there.