Skip to content
LF Cert Trainer

Lesson 99 · Section 8: Storage

Lesson 99: Using PVCs in Pods: from a claim to a mounted directory

How a Pod names a PersistentVolumeClaim and mounts it in a container, what the scheduler, the attach controller and the kubelet do before the container starts, how replicas of a Deployment share a claim, and how to read the errors when such a Pod will not start. · 17 min read · 3 min video

1/9Using PVCs in Pods
0:00 / 3:22

Narrated by the local narrator voice. Keys: Space plays and pauses, J and L step, C captions, F full screen.

From a claim to a directory

A bound PersistentVolumeClaim is a promise of storage, nothing more. No file can be read or written until a Pod uses the claim. This lesson is about that last step: how you write it, what the cluster does with it, and how to tell what went wrong when the Pod does not start.

A Pod never names a PersistentVolume. It names a claim, and the claim leads to the volume. That indirection is the point of the whole design: the Pod manifest contains no server address, no disk ID and no path on a node, so the same manifest works on a laptop cluster with a hostPath volume and on a cloud cluster with a network disk.

The chain from a container to the storagemountsnamesboundusesContainer/usr/share/nginx/htmlPod volumename: web-dataPVC data-claimsame namespaceStoragedisk, NFS, directoryPV pv-datacluster-wide
The chain from a container to the storage. The container mounts a Pod volume by name. The Pod volume names a claim. The claim is bound to a PersistentVolume, and the volume points to the real storage. Every link must be right for the files to appear.

Parts:

  • Container (/usr/share/nginx/html)
  • Pod volume (name: web-data)
  • PVC data-claim (same namespace)
  • Storage (disk, NFS, directory)
  • PV pv-data (cluster-wide)

Connections:

  • Container to Pod volume: mounts
  • Pod volume to PVC data-claim: names
  • PVC data-claim to PV pv-data: bound
  • PV pv-data to Storage: uses

The Pod manifest

apiVersion: v1
kind: Pod
metadata:
  name: webapp
spec:
  containers:
    - name: nginx
      image: nginx
      volumeMounts:
        - name: web-data                       # 2. which Pod volume
          mountPath: /usr/share/nginx/html     #    and where it appears in this container
  volumes:
    - name: web-data                           # 1. a Pod volume with a name of your choice
      persistentVolumeClaim:
        claimName: data-claim                  #    backed by this claim

There are two blocks, and they live at different levels:

BlockLevelWhat it says
spec.volumesThe Pod"This Pod has a volume called web-data, and its content comes from the claim data-claim"
spec.containers[].volumeMountsEach container"Mount the Pod volume web-data at this path in my file system"

The name is the only link between the two. It is a name inside this Pod and has nothing to do with the name of the claim or of the PV. If the names differ, the API server rejects the Pod: spec.containers[0].volumeMounts[0].name: Not found: "web-data".

This is the same structure you used for emptyDir, hostPath, ConfigMap and Secret volumes. Only the source under volumes changes. Compare:

volumes:
  - name: scratch
    emptyDir: {}                # lives and dies with the Pod
  - name: web-data
    persistentVolumeClaim:      # outlives the Pod
      claimName: data-claim

The persistentVolumeClaim source has just two fields:

FieldMeaning
claimNameThe claim's name. Required. There is no namespace field: it is always the Pod's namespace
readOnlytrue mounts the volume read-only in every container of this Pod. Default false

What the cluster does before the container starts

Between kubectl apply and a running container, three components each do one job. Knowing which one is responsible tells you where a stuck Pod is stuck.

What happens before the container startsnode setattachedstartsif it cannotif it failsSchedulerchecks the claimAttach controllerdisk to nodeKubeletmounts itPendingclaim not boundContainerCreatingattach or mount failsRunningfiles are there
What happens before the container starts. The scheduler only places the Pod when its claims can be satisfied. The attach controller connects the disk to the node, and the kubelet mounts it. A problem at each stage leaves the Pod in a different state.

Parts:

  • Scheduler (checks the claim)
  • Attach controller (disk to node)
  • Kubelet (mounts it)
  • Pending (claim not bound)
  • ContainerCreating (attach or mount fails)
  • Running (files are there)

Connections:

  • Scheduler to Attach controller: node set
  • Attach controller to Kubelet: attached
  • Kubelet to Running: starts
  • Scheduler to Pending: if it cannot
  • Attach controller to ContainerCreating: if it fails
  1. The scheduler refuses to place a Pod whose claim does not exist or cannot be satisfied. For a bound claim it also reads the volume's node affinity: a local volume or a zonal cloud disk can only be used on certain nodes, and the scheduler restricts the Pod to those. Until this works the Pod is Pending.
  2. The attach/detach controller in kube-controller-manager connects the storage to the chosen node, for volume types that need it (cloud disks and most CSI block volumes). It records the result in a VolumeAttachment object. NFS and hostPath volumes skip this step.
  3. The kubelet on the node mounts the volume into a directory of its own, under /var/lib/kubelet/pods/<pod-uid>/volumes/, formatting an empty disk first if needed. When the container is created, the container runtime bind-mounts that directory to the mountPath. If step 2 or 3 fails, the Pod sits in ContainerCreating.

Only then does the container start. From inside, the mount is an ordinary directory.

Two things follow from this sequence:

  • The mount hides what was in the image. If the image has files at the mountPath, the container no longer sees them. A new, empty volume mounted at /usr/share/nginx/html gives you an nginx that answers 403 Forbidden, because its default index.html is hidden under the mount.
  • The data is outside the container. Delete the Pod, and the claim, the PV and the files stay. A new Pod that names the same claim sees the same files. The claim is released only when someone deletes the claim itself.

Deployments, ReplicaSets and other controllers

A Deployment, ReplicaSet, DaemonSet or Job contains a Pod template. The two blocks go in the same places, one level deeper, under spec.template.spec:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
spec:
  replicas: 2
  selector:
    matchLabels:
      app: web
  template:
    metadata:
      labels:
        app: web
    spec:
      containers:
        - name: nginx
          image: nginx
          volumeMounts:
            - name: web-data
              mountPath: /usr/share/nginx/html
      volumes:
        - name: web-data
          persistentVolumeClaim:
            claimName: data-claim

Every replica is stamped from the same template, so every replica names the same claim. They all share one volume. Whether that works depends on the access mode and on where the Pods land.

A Deployment's replicas share one claimnode01node02mountsmountsMulti-Attach errorboundPod web-1RunningPod web-2RunningPod web-3ContainerCreatingPVC data-claimReadWriteOncePVattached to node01
A Deployment's replicas share one claim. Every replica comes from the same template, so every replica names the same claim. With ReadWriteOnce on an attachable disk, Pods on the first node work and a Pod on a second node cannot attach the volume.

Parts:

  • Pod web-1 (Running), in node01
  • Pod web-2 (Running), in node01
  • Pod web-3 (ContainerCreating), in node02
  • PVC data-claim (ReadWriteOnce)
  • PV (attached to node01)

Connections:

  • Pod web-1 to PVC data-claim: mounts
  • Pod web-2 to PVC data-claim: mounts
  • Pod web-3 to PVC data-claim: Multi-Attach error
  • PVC data-claim to PV: bound
Access mode of the volumeReplicas on one nodeReplicas on several nodes
ReadWriteOnceWork, and share the filesThe Pods on the second node hang in ContainerCreating with a Multi-Attach error (for attachable disks)
ReadWriteManyWorkWork. This is what shared content needs: NFS, CephFS and similar
ReadOnlyManyWork, read-onlyWork, read-only
ReadWriteOncePodOnly one Pod runs. The others stay PendingOnly one Pod runs

ReadWriteOnce also bites during a rolling update, even with one replica. The Deployment starts the new Pod before it stops the old one. If the new Pod lands on a different node, it waits for a disk that the old Pod still holds, and the rollout stalls. For a single-replica application on an RWO disk, set spec.strategy.type: Recreate, so the old Pod is gone before the new one starts.

Under the hood · One claim per replica: StatefulSets

When each replica needs its own storage, as a database cluster does, a Deployment is the wrong tool. A StatefulSet has volumeClaimTemplates: a claim template next to the Pod template. For every replica the controller creates a separate claim, named after the template and the Pod, such as data-db-0, data-db-1, data-db-2.

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: db
spec:
  serviceName: db
  replicas: 3
  selector:
    matchLabels:
      app: db
  template:
    metadata:
      labels:
        app: db
    spec:
      containers:
        - name: postgres
          image: postgres:17
          volumeMounts:
            - name: data
              mountPath: /var/lib/postgresql/data
  volumeClaimTemplates:
    - metadata:
        name: data
      spec:
        accessModes: ["ReadWriteOnce"]
        resources:
          requests:
            storage: 5Gi

There is no volumes block: the template's name, data, is what the container mounts. When the Pod db-1 is recreated it gets the claim data-db-1 again. Scaling down or deleting the StatefulSet leaves the claims in place by default, so the data survives. StatefulSets are not a focus of the CKA exam, but you should recognise the mechanism.

Under the hood · A claim written inside the Pod: generic ephemeral volumes

A Pod can also carry its own claim template, with the ephemeral volume source:

volumes:
  - name: scratch
    ephemeral:
      volumeClaimTemplate:
        spec:
          accessModes: ["ReadWriteOnce"]
          storageClassName: fast
          resources:
            requests:
              storage: 1Gi

Kubernetes creates a claim named after the Pod and the volume (webapp-scratch), owned by the Pod, and deletes it together with the Pod. The storage behaves like emptyDir in lifetime, but it comes from a StorageClass, so it can be a large or fast disk with a fixed size. It is the opposite of what this lesson is about: storage that is deliberately not persistent.

Using it

Example · Mount a claim in a Pod and prove the data survives

The claim from the last lesson is bound:

kubectl get pvc data-claim
NAME         STATUS   VOLUME    CAPACITY   ACCESS MODES   STORAGECLASS   VOLUMEATTRIBUTESCLASS   AGE
data-claim   Bound    pv-data   1Gi        RWO                           <unset>                 3m

Generate the Pod and add the two blocks:

kubectl run webapp --image=nginx --dry-run=client -o yaml > webapp.yaml
apiVersion: v1
kind: Pod
metadata:
  name: webapp
spec:
  containers:
    - name: webapp
      image: nginx
      volumeMounts:
        - name: web-data
          mountPath: /usr/share/nginx/html
  volumes:
    - name: web-data
      persistentVolumeClaim:
        claimName: data-claim
kubectl apply -f webapp.yaml
kubectl exec webapp -- sh -c 'echo "hello from the volume" > /usr/share/nginx/html/index.html'
kubectl delete pod webapp
kubectl apply -f webapp.yaml
kubectl exec webapp -- cat /usr/share/nginx/html/index.html
hello from the volume

The second Pod is a new container from a clean image, and the file is there. Confirm where it is mounted from:

kubectl describe pod webapp | grep -A 4 '^Volumes:'
Volumes:
  web-data:
    Type:       PersistentVolumeClaim (a reference to a PersistentVolumeClaim in the same namespace)
    ClaimName:  data-claim
    ReadOnly:   false

Example · A Pod stuck in Pending because of its claim

kubectl get pod reports
kubectl describe pod reports | tail -n 3
NAME      READY   STATUS    RESTARTS   AGE
reports   0/1     Pending   0          40s

  Type     Reason            Age   From               Message
  ----     ------            ----  ----               -------
  Warning  FailedScheduling  40s   default-scheduler  0/2 nodes are available: persistentvolumeclaim "report-data" not found. preemption: 0/2 nodes are available: 2 Preemption is not helpful for scheduling.

The scheduler names the claim. Check it in the Pod's namespace:

kubectl get pvc
NAME           STATUS   VOLUME      CAPACITY   ACCESS MODES   STORAGECLASS   VOLUMEATTRIBUTESCLASS   AGE
reports-data   Bound    pv-reports  2Gi        RWO                           <unset>                 10m

The claim is reports-data, the Pod asks for report-data. A Pod's volumes cannot be edited in place, so fix the file and replace the Pod:

kubectl get pod reports -o yaml > reports.yaml
# edit claimName: reports-data
kubectl replace --force -f reports.yaml

The other message you will meet in this place is pod has unbound immediate PersistentVolumeClaims. The claim exists but is itself Pending. The problem is then one level down: go to kubectl describe pvc and fix the binding, as in the previous lesson. The Pod is scheduled by itself once the claim is bound.

Example · A Pod stuck in ContainerCreating

kubectl get pods -l app=web -o wide
NAME                   READY   STATUS              RESTARTS   AGE   IP           NODE
web-6d4b9c7f5d-8kx2p   1/1     Running             0          9m    10.244.1.7   node01
web-6d4b9c7f5d-tq4mz   0/1     ContainerCreating   0          3m    <none>       node02

The Pod has a node, so scheduling worked. The problem is attaching or mounting:

kubectl describe pod web-6d4b9c7f5d-tq4mz | tail -n 3
  Warning  FailedAttachVolume  3m   attachdetach-controller  Multi-Attach error for volume "pvc-3f1c2a9e" Volume is already used by pod(s) web-6d4b9c7f5d-8kx2p

The volume is ReadWriteOnce and already attached to node01. The fixes, depending on what the task allows:

  • Keep one replica and avoid the overlap during updates: kubectl patch deployment web -p '{"spec":{"strategy":{"type":"Recreate","rollingUpdate":null}}}'.
  • Keep all replicas on one node, with a nodeSelector or Pod affinity.
  • Use storage that supports ReadWriteMany and a claim that asks for it.

Other events in this state point at the node instead: MountVolume.SetUp failed with a reason such as a missing NFS server, a wrong export path, or a hostPath with type: Directory whose directory does not exist on that node.

Example · Share one claim between two Pods, one of them read-only

A writer produces files and a web server publishes them. Both use the same claim; the web server may not change anything:

apiVersion: v1
kind: Pod
metadata:
  name: publisher
spec:
  containers:
    - name: nginx
      image: nginx
      volumeMounts:
        - name: site
          mountPath: /usr/share/nginx/html
          readOnly: true
  volumes:
    - name: site
      persistentVolumeClaim:
        claimName: data-claim
kubectl apply -f publisher.yaml
kubectl exec publisher -- touch /usr/share/nginx/html/test
touch: cannot touch '/usr/share/nginx/html/test': Read-only file system

readOnly on the mount affects this container only. The writer Pod mounts the same claim without it and keeps writing. With a ReadWriteOnce volume both Pods must run on the same node; add nodeName or Pod affinity if the cluster has several.

Tricks

Common mistakes

  • Naming the PV instead of the claim. claimName takes the name of the PersistentVolumeClaim. The Pod stays Pending with persistentvolumeclaim "pv-data" not found.
  • Different names in volumes and volumeMounts. The API server rejects the Pod. The two name values must be identical.
  • Indenting volumes under the container. volumes is a field of the Pod spec, at the same level as containers. Under a container, kubectl reports an unknown field.
  • A claim in another namespace. There is no way to reference one. Create the claim in the Pod's namespace.
  • Mounting over a directory the application needs. The mount hides the image's files at that path. Mount at a dedicated data directory, or use subPath, which the next lesson covers.
  • Scaling a Deployment that uses a ReadWriteOnce claim across nodes. The extra Pods hang in ContainerCreating. Use RWX storage, or a StatefulSet with a claim per Pod.
  • Stopping when the Pod is Running. Running only proves the mount succeeded. Write a file and read it back, ideally from a recreated Pod.

Recap

  • A Pod uses a claim through spec.volumes[].persistentVolumeClaim.claimName, and a container mounts it with volumeMounts using the same volume name and a mountPath.
  • The claim must be in the Pod's namespace. The Pod never mentions the PV.
  • The scheduler waits for the claim (Pending), the attach/detach controller attaches the disk and the kubelet mounts it (ContainerCreating when either fails). kubectl describe pod names the claim and the reason.
  • Data written to the mount survives the Pod. It goes away only with the claim, according to the reclaim policy.
  • In a Deployment or ReplicaSet the blocks go under spec.template.spec, and all replicas share the one claim, so the access mode decides whether they can run on several nodes.
  • Use Recreate for a single replica on a ReadWriteOnce disk, and a StatefulSet when each replica needs its own volume.

Official docs

Quiz: check what you learned

5 questions on this lesson · about 3 min · instant feedback. Missed questions come back in your review queue.

Sign in to take the quiz and keep your score.

Practise: try it on a real cluster

2 hands-on labs for this lesson. You get goals, not steps: any solution that reaches them passes.

  • Give a Deployment a claim of its own, mount it where the app writes, and prove that the data outlives the pod.

    Build · Level 2 · standard · target 20 min

  • Section capstone. Put existing data on the node behind a volume and a claim, move a running app onto it, give a second app its own corner of the same volume, and get a third one its storage on demand.

    Build · Level 3 · challenge · target 30 min

Discussion

Learners ask and answer questions here. Sign in to read and join the discussion.