Skip to content
LF Cert Trainer

Lesson 98 · Section 8: Storage

Lesson 98: Persistent Volume Claims: asking for storage

What a PersistentVolumeClaim is and why it is a separate object from the PersistentVolume, the rules the control plane uses to bind a claim to a volume, why a claim stays Pending, and what happens to the volume and its data when the claim is deleted. · 18 min read · 4 min video

1/10Persistent Volume Claims
0:00 / 3:45

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

Why claims exist

In the last lesson an administrator created PersistentVolumes (PVs). Each one describes a piece of real storage: an NFS export, a cloud disk, a directory on a node. A PV is full of details that only the person who runs the storage knows, such as server addresses, volume IDs and paths.

The people who deploy applications should not need those details. They know something else: "my database needs 10 gibibytes that one node can write to". A PersistentVolumeClaim (PVC) is exactly that sentence written as an object. The user creates the claim, Kubernetes finds a volume that satisfies it, and the two are bound.

Two objects, two people, one bindingcreatescreatesuseswatchesboundUserneeds 500MiPVC data-claimnamespace: defaultPV controllercontroller-managerAdministratorknows the storagePV pv-datacluster-wide, 1GiNFS exportthe real storage
Two objects, two people, one binding. An administrator describes real storage as a PersistentVolume. A user asks for storage with a PersistentVolumeClaim in a namespace. A controller in kube-controller-manager binds the two.

Parts:

  • User (needs 500Mi)
  • PVC data-claim (namespace: default)
  • PV controller (controller-manager)
  • Administrator (knows the storage)
  • PV pv-data (cluster-wide, 1Gi)
  • NFS export (the real storage)

Connections:

  • User to PVC data-claim: creates
  • Administrator to PV pv-data: creates
  • PV pv-data to NFS export: uses
  • PV controller to PVC data-claim: watches
  • PVC data-claim and PV pv-data: bound

The same pattern exists for compute. A Node offers CPU and memory, and a Pod requests some of it. A PV offers storage, and a PVC requests some of it. In both cases the request is written without knowing which machine or which disk will serve it.

PersistentVolumePersistentVolumeClaim
What it isThe storage itselfA request for storage
ScopeCluster-wide, no namespaceLives in a namespace
Usually written byA cluster administrator, or a provisionerThe person who deploys the application
HoldsCapacity, access modes, where the storage is, reclaim policyWanted size, access modes, optionally a class or a selector
Short namepvpvc

Because a claim is namespaced, a Pod can only use claims from its own namespace. The volume behind the claim has no namespace, but once it is bound to a claim it belongs to that claim alone.

What a claim looks like

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: data-claim
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 500Mi

Two fields are required: accessModes and resources.requests.storage. The rest is optional and narrows down which volume you will accept:

FieldMeaningIf you leave it out
accessModesHow the volume must be mountable: ReadWriteOnce, ReadOnlyMany, ReadWriteMany, ReadWriteOncePodRequired
resources.requests.storageThe least capacity you acceptRequired
storageClassNameOnly volumes of this class. "" means "only volumes with no class"The cluster's default StorageClass is filled in, if there is one
volumeModeFilesystem (a mounted directory) or Block (a raw device)Filesystem
selectorOnly volumes whose labels match (matchLabels, matchExpressions)Any labels
volumeNameBind to exactly this PVThe controller chooses

The access modes were covered in the Persistent Volumes lesson. As a reminder, they describe how many nodes may mount the volume, not how many Pods:

ModeShortMeaning
ReadWriteOnceRWORead-write by one node. Several Pods on that node can share it
ReadOnlyManyROXRead-only by many nodes
ReadWriteManyRWXRead-write by many nodes
ReadWriteOncePodRWOPRead-write by one single Pod in the whole cluster

How binding works

Binding is done by the PersistentVolume controller, one of the control loops inside kube-controller-manager. It watches claims and volumes. For each unbound claim it searches the volumes whose status is Available and keeps only those that pass every check:

  1. Capacity. The volume's capacity.storage is equal to or larger than the claim's request.
  2. Access modes. The volume lists every mode the claim asks for. A volume with [ReadWriteOnce, ReadOnlyMany] satisfies a claim for [ReadWriteOnce].
  3. Storage class. storageClassName is the same on both. A claim with no class only binds to a volume with no class.
  4. Volume mode. Both are Filesystem, or both are Block.
  5. Selector. If the claim has a selector, the volume's labels match it.

Of the volumes that remain, the controller picks the smallest one, to waste as little as possible. It then writes the claim into the volume's spec.claimRef, writes the volume's name into the claim's spec.volumeName, and both become Bound.

Which volume a claim getstoo smallbound: gets the whole 1Giwrong access modePVC data-claim500Mi, RWOpv-small100Mi, RWOpv-data1Gi, RWOpv-shared5Gi, ROX
Which volume a claim gets. The claim asks for 500Mi with ReadWriteOnce. A volume must be Available, large enough, offer the access mode and have the same storage class. The smallest volume that fits wins, and the claim gets all of it.

Parts:

  • PVC data-claim (500Mi, RWO)
  • pv-small (100Mi, RWO)
  • pv-data (1Gi, RWO)
  • pv-shared (5Gi, ROX)

Connections:

  • PVC data-claim to pv-small: too small
  • PVC data-claim to pv-data: bound: gets the whole 1Gi
  • PVC data-claim to pv-shared: wrong access mode

Three consequences of these rules catch people out:

  • Binding is one to one. A volume serves one claim. Two claims can never share a PV, and a claim never spans two PVs.
  • The claim gets the whole volume. In the diagram the claim asked for 500Mi and is bound to a 1Gi volume. The claim's status.capacity says 1Gi, the Pod can use all of it, and the other 500Mi is not available to anyone else.
  • No match is not a failure. The claim stays Pending for as long as it takes. The moment a fitting volume appears, the controller binds it. Nothing has to be recreated.

Phases you will see

ObjectPhaseMeaning
PVCPendingNo volume yet: nothing fits, or the class waits for a Pod, or a provisioner is still working
PVCBoundBound to the volume named in the VOLUME column
PVCLostThe volume it was bound to no longer exists
PVAvailableFree, not bound to any claim
PVBoundBound to the claim in the CLAIM column, shown as namespace/name
PVReleasedIts claim was deleted, but the volume has not been reclaimed yet
PVFailedAutomatic reclamation failed

Storage classes change the picture

Everything above is static provisioning: an administrator made the volumes in advance. Most real clusters have a StorageClass, and then a claim does not wait for a matching PV at all. A provisioner creates a new volume of exactly the requested size for it. That is the subject of the Storage Class lesson. For this lesson you need one rule from it:

What happens when a claim is deleted

Deleting a claim says "I am done with this storage". Two mechanisms decide what follows.

Deleting a claimblocksfreesRetainDeletePodstill mounts itPVC deletedTerminating, then gonePV pv-datareclaim policy?RetainReleased, data keptDeletePV and disk removed
Deleting a claim. A claim that a Pod still uses is not removed until the Pod is gone. After that, the volume's reclaim policy decides: Retain keeps the volume and the data, Delete removes both.

Parts:

  • Pod (still mounts it)
  • PVC deleted (Terminating, then gone)
  • PV pv-data (reclaim policy?)
  • Retain (Released, data kept)
  • Delete (PV and disk removed)

Connections:

  • Pod to PVC deleted: blocks
  • PVC deleted to PV pv-data: frees
  • PV pv-data to Retain: Retain
  • PV pv-data to Delete: Delete

Protection while in use. Every claim carries the finalizer kubernetes.io/pvc-protection. If you delete a claim that a Pod still uses, the API server only marks it for deletion. The claim shows Terminating and keeps working. It is really removed when the last Pod that uses it is gone. Volumes have the same guard, kubernetes.io/pv-protection, for as long as they are bound to a claim.

The reclaim policy. Once the claim is gone, the volume's persistentVolumeReclaimPolicy applies:

PolicyWhat happens to the PVWhat happens to the dataDefault for
RetainStays, in phase ReleasedKept. An administrator cleans up by handPVs you create by hand
DeleteThe PV object is removedThe storage behind it (cloud disk, provisioned directory) is deleted tooPVs created by a StorageClass
RecycleWas wiped with rm -rf and made Available againErasedNothing. Deprecated, do not use

A Released volume is not offered to new claims. It still has the old claimRef, and it still holds the previous owner's data, which the next user should not see. To use it again an administrator either deletes and recreates the PV, or removes the claimRef once the data has been dealt with.

Under the hood · Pre-binding: reserving a volume for a claim

The controller normally chooses the volume. You can make the choice yourself from either side:

  • In the claim, set spec.volumeName: pv-data. The claim binds only to that volume. The class, size and access mode checks still apply, so set storageClassName: "" if the volume has no class.
  • In the volume, set spec.claimRef with the namespace and name of a claim. The volume refuses every other claim, even before the claim exists.

Setting only volumeName does not reserve the volume: another claim can still take it first, and yours is then stuck in Pending. For a real reservation, set claimRef on the PV as well.

apiVersion: v1
kind: PersistentVolume
metadata:
  name: pv-data
spec:
  storageClassName: ""
  claimRef:
    namespace: default
    name: data-claim
  # capacity, accessModes and the volume source as usual
Under the hood · Growing a claim

A bound claim can be made larger, never smaller. Edit spec.resources.requests.storage to a bigger value. This only works when the claim's StorageClass has allowVolumeExpansion: true and the storage driver supports resizing; otherwise the API server rejects the change. The driver grows the disk first and the file system second, and the claim's status.capacity shows the new size when both are done. Most drivers resize while the Pod keeps running. Hand-made hostPath and NFS volumes without a class cannot be expanded this way.

Using it

Example · Create a volume and a claim, and watch them bind

Start with one volume, made by an administrator:

apiVersion: v1
kind: PersistentVolume
metadata:
  name: pv-data
spec:
  capacity:
    storage: 1Gi
  accessModes:
    - ReadWriteOnce
  persistentVolumeReclaimPolicy: Retain
  hostPath:
    path: /srv/pv-data
kubectl apply -f pv-data.yaml
kubectl get pv
NAME      CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS      CLAIM   STORAGECLASS   VOLUMEATTRIBUTESCLASS   REASON   AGE
pv-data   1Gi        RWO            Retain           Available                          <unset>                          5s

Now the claim, written by a user who only knows the application needs 500Mi:

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: data-claim
spec:
  storageClassName: ""
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 500Mi
kubectl apply -f data-claim.yaml
kubectl get pvc,pv
NAME                               STATUS   VOLUME    CAPACITY   ACCESS MODES   STORAGECLASS   VOLUMEATTRIBUTESCLASS   AGE
persistentvolumeclaim/data-claim   Bound    pv-data   1Gi        RWO                           <unset>                 4s

NAME                       CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS   CLAIM                STORAGECLASS   VOLUMEATTRIBUTESCLASS   REASON   AGE
persistentvolume/pv-data   1Gi        RWO            Retain           Bound    default/data-claim                  <unset>                          40s

Read the two lines against each other. The claim's VOLUME is pv-data, and its CAPACITY is the volume's 1Gi, not the 500Mi it asked for. The volume's CLAIM is default/data-claim. The binding is recorded on both sides.

Example · Find out why a claim is Pending

The task: "The claim logs-claim in the namespace web is not bound. Fix it." Look at the claim's events first:

kubectl describe pvc logs-claim -n web | tail -n 4
Events:
  Type    Reason         Age               From                         Message
  ----    ------         ----              ----                         -------
  Normal  FailedBinding  9s (x3 over 35s)  persistentvolume-controller  no persistent volumes available for this claim and no storage class is set

The message says nothing fits. Put the fields that matter side by side:

kubectl get pvc logs-claim -n web -o custom-columns=SIZE:.spec.resources.requests.storage,MODES:.spec.accessModes,CLASS:.spec.storageClassName,MODE:.spec.volumeMode
kubectl get pv -o custom-columns=NAME:.metadata.name,SIZE:.spec.capacity.storage,MODES:.spec.accessModes,CLASS:.spec.storageClassName,MODE:.spec.volumeMode,PHASE:.status.phase
SIZE    MODES             CLASS    MODE
200Mi   [ReadWriteMany]   <none>   Filesystem

NAME      SIZE    MODES             CLASS    MODE         PHASE
pv-logs   100Mi   [ReadWriteMany]   <none>   Filesystem   Available

The class, the modes and the volume mode agree. The size does not: the claim wants 200Mi and the only volume offers 100Mi. Which side to change depends on the task. A claim's request cannot be lowered and most of its spec cannot be edited at all, so changing the claim means deleting it and creating it again:

kubectl get pvc logs-claim -n web -o yaml > logs-claim.yaml
# edit: storage: 100Mi, and remove the status and the metadata fields the server added
kubectl delete pvc logs-claim -n web
kubectl apply -f logs-claim.yaml
kubectl get pvc logs-claim -n web
NAME         STATUS   VOLUME    CAPACITY   ACCESS MODES   STORAGECLASS   VOLUMEATTRIBUTESCLASS   AGE
logs-claim   Bound    pv-logs   100Mi      RWX                           <unset>                 3s

If the task says the claim is right and the volume is wrong, raise the volume instead. Capacity on a PV can be edited in place: kubectl patch pv pv-logs -p '{"spec":{"capacity":{"storage":"200Mi"}}}'.

Example · Bind a claim to one specific volume with labels

There are several 1Gi volumes and the claim must get the one on fast disks. Label the volume and select it:

kubectl label pv pv-fast tier=fast
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: fast-claim
spec:
  storageClassName: ""
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 1Gi
  selector:
    matchLabels:
      tier: fast
kubectl apply -f fast-claim.yaml
kubectl get pvc fast-claim -o jsonpath='{.spec.volumeName}{"\n"}'
pv-fast

A selector is a filter on top of the other rules, not a replacement for them. The volume must still be large enough and offer the access mode. A claim with a selector is also never served by dynamic provisioning, because a provisioner cannot know in advance which labels to put on a new volume.

Example · Delete a claim and reuse the retained volume

kubectl delete pvc data-claim
kubectl get pv pv-data
NAME      CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS     CLAIM                STORAGECLASS   VOLUMEATTRIBUTESCLASS   REASON   AGE
pv-data   1Gi        RWO            Retain           Released   default/data-claim                  <unset>                          12m

The policy is Retain, so the volume and the files in /srv/pv-data are still there. The volume is Released: a new claim, even one with the same name, stays Pending. Check the old data, then clear the reference to the old claim:

kubectl patch pv pv-data --type json -p '[{"op":"remove","path":"/spec/claimRef"}]'
kubectl get pv pv-data
NAME      CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS      CLAIM   STORAGECLASS   VOLUMEATTRIBUTESCLASS   REASON   AGE
pv-data   1Gi        RWO            Retain           Available                          <unset>                          13m

The volume is Available and the next fitting claim binds to it, with the old files still inside. On a real cluster, wipe or move the data first.

Example · A claim that will not go away

kubectl delete pvc data-claim

The command prints persistentvolumeclaim "data-claim" deleted and then hangs. In a second terminal:

kubectl get pvc data-claim
kubectl describe pvc data-claim | grep -E 'Status|Finalizers|Used By'
NAME         STATUS        VOLUME    CAPACITY   ACCESS MODES   STORAGECLASS   VOLUMEATTRIBUTESCLASS   AGE
data-claim   Terminating   pv-data   1Gi        RWO                           <unset>                 20m

Status:        Terminating (lasts 15s)
Finalizers:    [kubernetes.io/pvc-protection]
Used By:       webapp

Used By names the Pod that still mounts the claim. Nothing is broken: the protection finalizer is doing its job. Delete the Pod (or scale down its Deployment) and the claim disappears by itself. Do not remove the finalizer by hand to speed things up; that takes the storage away from a running application.

Tricks

Common mistakes

  • Putting the claim in a different namespace from the Pod. A Pod can only reference claims in its own namespace. The Pod stays Pending with persistentvolumeclaim "data-claim" not found.
  • Leaving out storageClassName on a cluster with a default class. The claim gets the default class, skips your hand-made PV and receives a new, empty volume from the provisioner. Write storageClassName: "".
  • Expecting two claims to share one volume. Binding is one to one. Two Pods share storage by using the same claim, not by using two claims on one PV.
  • Asking for an access mode the volume does not list. A claim for ReadWriteMany never binds to a volume that only offers ReadWriteOnce, whatever its size.
  • Assuming the claim's size is what you get. You get the whole volume. A 500Mi claim can lock up a 100Gi PV if that is the smallest one that fits.
  • Expecting a Released volume to be reused. It needs an administrator: clear claimRef or recreate the PV.
  • Deleting a claim whose volume has the policy Delete. The disk and the data go with it. Check with kubectl get pv before you delete a claim you did not create.

Recap

  • A PersistentVolume is storage in the cluster and has no namespace. A PersistentVolumeClaim is a request for storage and lives in a namespace.
  • The PV controller binds one claim to one volume when capacity, access modes, storage class, volume mode and any selector fit. It picks the smallest volume that fits, and the claim gets all of it.
  • A claim with no match stays Pending until one appears. kubectl describe pvc gives the reason.
  • storageClassName: "" means "a volume with no class". Leaving the field out means "the default class, if any".
  • A claim in use is protected: it stays Terminating until its Pods are gone.
  • After the claim is deleted, the reclaim policy decides: Retain keeps the volume as Released with its data, Delete removes the volume and the storage behind it.

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.

  • Find out why a claim stays Pending next to a volume made for it, and get the shop's media server running on the data that volume already holds.

    Fix · Level 2 · standard · target 15 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.