Skip to content
LF Cert Trainer

Lesson 97 · Section 8: Storage

Lesson 97: Persistent Volumes: storage as a cluster resource

A PersistentVolume describes one piece of real storage as an object of the cluster, separate from any Pod. Its fields, the four access modes, the reclaim policies, the phases from Available to Released, and how to create and repair one by hand. · 17 min read · 4 min video

1/10Persistent Volumes
0:00 / 3:41

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

What this lesson is about

The lesson Volumes ended with a Pod that mounts an NFS share directly. It works, but the Pod's author has to know the server and the path, and every workload repeats them. Kubernetes separates the two concerns with a pair of objects:

  • A PersistentVolume (PV) describes a piece of storage. The cluster administrator, or a storage driver, creates it.
  • A PersistentVolumeClaim (PVC) is a request for storage. The application's owner creates it, and the Pod refers to the claim.

This lesson is about the first half: what a PersistentVolume is, what its fields mean and how it behaves over its life. The next lessons cover claims, using a claim in a Pod, and storage classes, which create PersistentVolumes automatically.

Why it exists

With volumes configured in each Pod:

  • Developers must know storage details: server addresses, export paths, disk IDs.
  • A storage migration means editing and rolling out every workload.
  • Nobody can list which storage exists, how big it is and who uses it.
  • There is no place to say what should happen to the data when the application is removed.

The PersistentVolume answers all four. The storage details are written once, by the person who knows them. Workloads refer to a claim by name. kubectl get pv is the inventory, and the reclaim policy is the rule for the data's end of life.

Two objects, two rolescreatespoints tocreatesbound, one to oneusesAdministratorknows the storagePersistentVolumecluster-wide, 10Gi, RWXReal storageNFS export, disk, LUNDeveloperknows the applicationPersistentVolumeClaimin a namespace, needs 5GiPodvolumes: claimName
Two objects, two roles. The administrator describes real storage once as a PersistentVolume. A developer asks for storage with a claim and never sees the server address. Kubernetes binds the two.

Parts:

  • Administrator (knows the storage)
  • PersistentVolume (cluster-wide, 10Gi, RWX)
  • Real storage (NFS export, disk, LUN)
  • Developer (knows the application)
  • PersistentVolumeClaim (in a namespace, needs 5Gi)
  • Pod (volumes: claimName)

Connections:

  • Administrator to PersistentVolume: creates
  • PersistentVolume to Real storage: points to
  • Developer to PersistentVolumeClaim: creates
  • PersistentVolumeClaim and PersistentVolume: bound, one to one
  • Pod to PersistentVolumeClaim: uses

What it is

apiVersion: v1
kind: PersistentVolume
metadata:
  name: pv-reports
spec:
  capacity:
    storage: 10Gi
  accessModes:
    - ReadWriteMany
  persistentVolumeReclaimPolicy: Retain
  storageClassName: manual
  nfs:
    server: 10.0.0.10
    path: /exports/reports
FieldMeaning
metadata.nameThe volume's name. No namespace: a PV is cluster-scoped
capacity.storageThe size the volume offers. A claim can bind only if it asks for this much or less
accessModesHow the volume may be mounted. A list: the volume supports each mode in it
persistentVolumeReclaimPolicyRetain or Delete: what happens after its claim is deleted. Default for a hand-made PV: Retain
storageClassNameThe class of the volume. Only claims that ask for the same class can bind it. Empty or absent: no class
volumeModeFilesystem (default): mounted as a directory. Block: handed to the Pod as a raw device
mountOptionsOptions for the mount command on the node, for example ["nfsvers=4.1", "hard"]
nodeAffinityWhich nodes can reach the volume. Required for local volumes
claimRefThe claim this volume is reserved for or bound to. Filled in by Kubernetes on binding
One volume sourceWhere the storage is: nfs, csi, hostPath, local, iscsi, fc

The volume source uses the same fields as a volume in a Pod. The nfs block above is identical to the one in the previous lesson. It has only moved from the Pod to an object of its own.

Access modes

An access mode says how many nodes, or Pods, may use the volume at the same time.

The four access modesallowsallowsallowsallowsReadWriteOnceRWOReadOnlyManyROXReadWriteManyRWXReadWriteOncePodRWOPOne noderead-write, any Pods on itMany nodesread-onlyMany nodesread-writeOne Podin the whole cluster
The four access modes. An access mode says how many nodes, or Pods, may mount the volume at the same time. Three of the four count nodes, not Pods.

Parts:

  • ReadWriteOnce (RWO)
  • ReadOnlyMany (ROX)
  • ReadWriteMany (RWX)
  • ReadWriteOncePod (RWOP)
  • One node (read-write, any Pods on it)
  • Many nodes (read-only)
  • Many nodes (read-write)
  • One Pod (in the whole cluster)

Connections:

  • ReadWriteOnce to One node: allows
  • ReadOnlyMany to Many nodes: allows
  • ReadWriteMany to Many nodes: allows
  • ReadWriteOncePod to One Pod: allows
ModeShortMeaning
ReadWriteOnceRWOMounted read-write by one node. Several Pods on that node can share it
ReadOnlyManyROXMounted read-only by many nodes
ReadWriteManyRWXMounted read-write by many nodes
ReadWriteOncePodRWOPMounted read-write by one Pod in the whole cluster. CSI volumes only

Which modes are possible depends on the storage. A block device such as a cloud disk can be attached to one machine, so it offers RWO. A shared file system offers all of them.

StorageRWOROXRWX
hostPathYesNoNo
nfsYesYesYes
iscsi, fcYesYesNo
csiDepends on the driverDepends on the driverDepends on the driver

Reclaim policies

The reclaim policy says what Kubernetes does with the volume after its claim is deleted.

PolicyWhat happens when the claim is deletedDefault for
RetainThe PV becomes Released. The object and the data stay. An administrator must clean up by handPVs you create yourself
DeleteKubernetes deletes the PV object and the storage behind it, for example the cloud diskPVs created through a StorageClass
RecycleDeprecated. It ran rm -rf on the volume and made it Available again. Only nfs and hostPath ever supported itNothing

Retain is the safe choice for data that matters, and it means work: a retained volume is not reusable until someone decides what to do with the old data.

Phases

The life of a PersistentVolumeclaimedPVC gonepolicy Retainpolicy Deleteon errorAvailablefree, no claimBoundbelongs to one claimReleasedclaim deleted, data keptRetainwaits for an administratorDeletePV and storage removedFailedautomatic reclaim failed
The life of a PersistentVolume. A volume is Available until a claim binds it. When the claim is deleted the volume is Released, and the reclaim policy decides what happens to it and to the data.

Parts:

  • Available (free, no claim)
  • Bound (belongs to one claim)
  • Released (claim deleted, data kept)
  • Retain (waits for an administrator)
  • Delete (PV and storage removed)
  • Failed (automatic reclaim failed)

Connections:

  • Available to Bound: claimed
  • Bound to Released: PVC gone
  • Released to Retain: policy Retain
  • Released to Delete: policy Delete
  • Delete to Failed: on error
PhaseMeaning
AvailableFree. No claim is bound to it
BoundBound to exactly one claim. The CLAIM column shows namespace/name
ReleasedThe claim was deleted, but the volume has not been reclaimed. It still holds the old data
FailedAutomatic reclamation failed, for example the driver could not delete the disk
kubectl get pv
NAME         CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS      CLAIM             STORAGECLASS   VOLUMEATTRIBUTESCLASS   REASON   AGE
pv-reports   10Gi       RWX            Retain           Available                     manual         <unset>                          5s
pv-db        20Gi       RWO            Retain           Bound       shop/mysql-data   manual         <unset>                          41d
pv-old       5Gi        RWO            Retain           Released    default/scratch   manual         <unset>                          90d

How it works

Static and dynamic provisioning

PersistentVolumes come into being in two ways.

  • Static provisioning. An administrator creates the storage (an NFS export, a disk) and then writes a PV manifest for it, as in this lesson. Claims pick from the pool of existing volumes.
  • Dynamic provisioning. Nobody creates PVs in advance. A claim names a StorageClass, and the class's provisioner, a CSI driver, creates the storage and the PV at that moment. Such volumes are named pvc- plus the claim's UID.

Both produce the same kind of object. Everything in this lesson applies to a dynamically provisioned volume too: it has a capacity, access modes, a reclaim policy and a phase. Dynamic provisioning is the topic of the lesson Storage Class.

Binding in one paragraph

A control loop in kube-controller-manager watches claims and volumes. For each new claim it looks for an Available PV with the same storageClassName, with all access modes the claim asks for, and with at least the requested capacity. It picks the smallest that fits, writes the claim into the PV's spec.claimRef and the PV's name into the claim. From then on the two are bound one to one: a 10Gi volume bound to a 5Gi claim is fully used, and the other 5Gi are not available to anybody else. The next lesson covers binding from the claim's side.

Protection against deleting a volume in use

Every PV carries the finalizer kubernetes.io/pv-protection. If you delete a PV that is bound to a claim, the command returns, but the object only gets a deletion timestamp and stays in Terminating until the claim is gone. The data of a running application cannot be pulled away by one mistaken kubectl delete pv.

Under the hood · hostPath and local PersistentVolumes

Two volume sources use a disk of a node, and they behave differently.

A hostPath PV is what the documentation uses for single-node exercises:

apiVersion: v1
kind: PersistentVolume
metadata:
  name: pv-log
spec:
  capacity:
    storage: 100Mi
  accessModes: ["ReadWriteOnce"]
  hostPath:
    path: /pv/log

Kubernetes does not know which node holds the data. On a cluster with several nodes, a Pod may be scheduled to a node whose /pv/log is empty. Use it only where there is one node, which includes many exam tasks.

A local PV names a disk or directory of one specific node, and says so with a required nodeAffinity:

apiVersion: v1
kind: PersistentVolume
metadata:
  name: pv-ssd-node-1
spec:
  capacity:
    storage: 100Gi
  accessModes: ["ReadWriteOnce"]
  persistentVolumeReclaimPolicy: Retain
  storageClassName: local-storage
  local:
    path: /mnt/disks/ssd1
  nodeAffinity:
    required:
      nodeSelectorTerms:
        - matchExpressions:
            - key: kubernetes.io/hostname
              operator: In
              values: ["node-1"]

The scheduler reads that affinity and places any Pod that uses the volume on node-1. The data is still lost if the node is lost, but the Pod can never land on the wrong node. Local volumes are used with a StorageClass whose volumeBindingMode is WaitForFirstConsumer, so that binding waits until a Pod is being scheduled.

Under the hood · What can be changed on an existing PV

Most of the spec is fixed at creation: the volume source cannot be changed, so you cannot point a PV at another server. You can change persistentVolumeReclaimPolicy, mountOptions, claimRef and labels. The capacity of a bound volume is changed through its claim, if the StorageClass allows expansion, not by editing the PV.

To move a PV to different storage, create a new PV, copy the data, and bind the workload's claim to the new volume.

Using it

Example · Create a PersistentVolume from a task description

Task: "Create a PersistentVolume pv-log with 100Mi, access mode ReadWriteOnce, host path /pv/log and reclaim policy Retain."

There is no imperative command. Copy the example from the documentation page Persistent Volumes and change it:

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

Check four things against the task: capacity, access mode, reclaim policy, and Available. The task named no storage class, so the manifest has none.

Example · Change the reclaim policy before deleting a claim

A dynamically provisioned volume holds data you want to keep, and its policy is Delete:

kubectl get pv
NAME                                       CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS   CLAIM             STORAGECLASS   AGE
pvc-8d1c04e2-5b7f-4a55-9c1e-2f6f0c7d1a11   20Gi       RWO            Delete           Bound    shop/mysql-data   fast           41d
kubectl patch pv pvc-8d1c04e2-5b7f-4a55-9c1e-2f6f0c7d1a11 \
  -p '{"spec":{"persistentVolumeReclaimPolicy":"Retain"}}'
kubectl get pv -o custom-columns=NAME:.metadata.name,POLICY:.spec.persistentVolumeReclaimPolicy
NAME                                       POLICY
pvc-8d1c04e2-5b7f-4a55-9c1e-2f6f0c7d1a11   Retain

Now deleting the claim leaves the volume Released with its data, instead of deleting the disk.

Example · Make a Released volume usable again

kubectl get pv pv-reports
NAME         CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS     CLAIM             STORAGECLASS   AGE
pv-reports   10Gi       RWX            Retain           Released   default/reports   manual         2d

A new claim will not bind this volume: spec.claimRef still points to the deleted claim, by its UID. Decide what to do with the data first. Then either delete the PV and create it again, or remove the reference:

kubectl patch pv pv-reports --type json -p '[{"op":"remove","path":"/spec/claimRef"}]'
kubectl get pv pv-reports -o jsonpath='{.status.phase}{"\n"}'
Available

The old data is still on the storage. Whoever claims the volume next will see it, so clean it up if it should not be shared.

Example · Reserve a volume for one claim

To make sure that a particular claim gets a particular volume, set claimRef yourself when you create the PV:

spec:
  claimRef:
    namespace: shop
    name: mysql-data

No other claim can bind this volume, even one that would match its size and modes. The volume shows Available until the claim shop/mysql-data exists. The claim must still match the volume's class, modes and size.

Tricks

Common mistakes

  • Giving a PV a namespace, or looking for it with -n. PVs are cluster-scoped.
  • Reading ReadWriteOnce as "one Pod". It is one node. Use ReadWriteOncePod for a single Pod.
  • Expecting a Released volume to be claimed again. It keeps its old claimRef until an administrator clears it or recreates the PV.
  • Leaving Delete on a volume with precious data. Deleting the claim then deletes the storage. Patch the policy to Retain first.
  • A storage class name that does not match. A PV with storageClassName: manual binds only claims that ask for manual. A PV with no class binds only claims with storageClassName: "". In a cluster with a default StorageClass, a claim with no class asks for the default class and ignores your class-less PV.
  • Using a hostPath PV on a cluster with several nodes. The data is on one node, and Kubernetes does not know which.
  • Thinking the capacity is enforced. For NFS and hostPath it is only a number used for matching.
  • Writing reclaimPolicy in a PV. The field is persistentVolumeReclaimPolicy. The API rejects the manifest with an unknown field error.

Recap

  • A PersistentVolume is a cluster-scoped object that describes one piece of real storage, created by an administrator (static) or by a StorageClass provisioner (dynamic).
  • capacity and accessModes say what it offers. RWO is one node, ROX and RWX are many nodes, RWOP is one Pod.
  • persistentVolumeReclaimPolicy: Retain keeps the volume and data for manual cleanup, Delete removes both.
  • Phases: Available, Bound (one claim, one to one), Released (claim gone, not reusable yet), Failed.
  • There is no kubectl create pv: write YAML, check with kubectl get pv, adjust with kubectl patch pv.

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.

  • Create a PersistentVolume with the right size, access mode and class, protect a volume that is in use from deletion, and make a Released volume claimable again.

    Build · 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.