CodeBlanks Logo Icon CodeBlanks

Mounting a PVC to a Pod

Learn to mount a PVC as a volume in a Pod.

Mounting a PVC in a pod

A pod defines a PVC as a volume under volumes with persistentVolumeClaim.claimName and mounts it in the container with volumeMounts. When the pod is deleted and recreated, it attaches to the same PVC, and therefore the same data:

    spec:
      volumes:
        - name: veri
          persistentVolumeClaim:
            claimName: api-veri
      containers:
        - name: api
          image: api:1.0
          volumeMounts:
            - name: veri
              mountPath: /var/lib/api

Verifying persistence

Persistence is tested by writing data and deleting the pod. Before a PVC is deleted, the pods using it must be deleted; otherwise the PVC stays Terminating (protection):

kubectl exec deploy/api -- sh -c 'echo merhaba > /var/lib/api/not.txt'
kubectl delete pod -l app=api
kubectl exec deploy/api -- cat /var/lib/api/not.txt
# merhaba

Practice Mount the PVC

Write a pod template's spec section (starting with spec:): a veri volume using the api-veri PVC under volumes; container named api, image api:1.0; mount veri at /var/lib/api.

Starter code

terminal
# buraya yaz

Sample solution

terminal
spec:
  volumes:
    - name: veri
      persistentVolumeClaim:
        claimName: api-veri
  containers:
    - name: api
      image: api:1.0
      volumeMounts:
        - name: veri
          mountPath: /var/lib/api

Expected output

deployment.apps/api configured
$ kubectl exec deploy/api -- df -h /var/lib/api
Filesystem   Size  Used Avail Use% Mounted on
/dev/sdb     4.9G   24K  4.9G   1% /var/lib/api

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 When you delete the pod and recreate it with the same PVC, what happens to the files in /var/lib/api?

  • They move to another pod
  • They stay in place Correct answer
  • They are deleted
  • They are restored from the image

Explanation: The data is on the PV; the pod only mounts it.

2 Specify which PVC the volume is.

Question
      volumes:
        - name: veri
          persistentVolumeClaim:
            ____: api-veri
Answer
      volumes:
        - name: veri
          persistentVolumeClaim:
            claimName: api-veri

Explanation: claimName is the PVC's name.

3 Match.

Term Meaning
persistentVolumeClaim Volume source
claimName PVC name
mountPath Path in the container
Terminating PVC Waiting because it's in use

All lessons in Advanced