Skip to content
Opsfolk
Kubernetes

Kubernetes Persistent Storage: PVs, PVCs and CSI Explained

How Kubernetes persistent storage works: PersistentVolumes, PVCs, StorageClasses, dynamic provisioning, CSI drivers, access modes, snapshots and debugging.

admin28 min read

Persistent Storage: PVs, PVCs and CSI explained. A Pod on worker-2 reaches its EBS disk through three gates, the claim, the volume and the CSI driver.
On this page

In the last part, a request found its way from a name to a Pod. But a Pod is easy to replace because it keeps nothing: when its container restarts, everything it wrote to its own filesystem is gone, and when a rollout replaces it, the new Pod starts empty on another node. That is fine for a web server. It is not fine for Postgres.

Kubernetes answers that problem with a small set of objects and one plugin interface, and this part of Kubernetes Internals: How a Cluster Really Works follows them from a YAML file to a mounted disk. A PersistentVolumeClaim is a request for storage, made by an application. A PersistentVolume is a piece of real storage, made by an administrator or on demand. A StorageClass says how to make one. And the Container Storage Interface (CSI) is how Kubernetes asks a storage system, any storage system, to create, attach and mount it. At the end, we turn it around: given a claim stuck in Pending or a Pod stuck in ContainerCreating, how to find which step failed.

New to the series? Start with Kubernetes API Server Explained: The Life of a Request, then How the Kubernetes Scheduler Works, Kubelet and Container Runtimes and Kubernetes Services, DNS and Ingress Explained.

What Is a PersistentVolume in Kubernetes?

Definition: A PersistentVolume (PV) is a cluster-wide API object that represents one piece of storage, such as a cloud disk or an NFS export, with its size, access modes and reclaim policy. A PersistentVolumeClaim (PVC) is a namespaced request for storage. Kubernetes binds each claim to one volume that satisfies it, and a Pod uses the storage by naming the claim.

Three facts frame the rest of this article:

  • A PV belongs to the cluster; a PVC belongs to a namespace. Volumes are infrastructure, like nodes. Claims are part of an application, like its Deployments. The split lets the people who run the storage and the people who use it work apart.
  • A Pod names a claim, never a disk. The Pod's spec says claimName: data-postgres-0. It does not know whether that is an EBS volume, a Ceph image or an NFS share, and the same manifest runs on any cluster that can satisfy the claim.
  • Binding is one to one, and it sticks. Once a claim is bound to a volume, no other claim can take that volume, and the claim keeps it until the claim is deleted. Pods come and go; the binding stays.

Here is the claim the rest of this article uses: storage for a Postgres Pod in the namespace shop.

yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: data-postgres-0
  namespace: shop
spec:
  storageClassName: fast-ssd
  accessModes: [ReadWriteOnce]
  resources:
    requests:
      storage: 20Gi

And the Pod that uses it, trimmed to the parts that matter:

yaml
apiVersion: v1
kind: Pod
metadata:
  name: postgres-0
  namespace: shop
spec:
  containers:
  - name: postgres
    image: postgres:18
    volumeMounts:
    - name: data
      mountPath: /var/lib/postgresql
  volumes:
  - name: data
    persistentVolumeClaim:
      claimName: data-postgres-0

Pod postgres-0 names the claim data-postgres-0, which names the class fast-ssd and is bound to a PersistentVolume; the volume names an EBS disk that the CSI driver made.

Volumes at a Glance: Ephemeral and Persistent

Not every volume is a PersistentVolume. A Pod's volumes list takes many kinds, and they split by one question: does the data outlive the Pod?

Volume Lives as long as Typical use
emptyDir The Pod, on its node (it survives container restarts, not the Pod's deletion) Scratch space, a cache, files shared between containers
configMap, secret, downwardAPI, projected The Pod; the kubelet writes the files from API objects Configuration, credentials, service account tokens
Generic ephemeral (ephemeral.volumeClaimTemplate) The Pod; a PVC is created with it and deleted with it Large scratch space from a real storage class
persistentVolumeClaim The claim, which outlives any Pod Databases, queues, anything you cannot lose
hostPath The node Node agents that need the host's files; not application data

The last two lines are where people get hurt. A hostPath volume looks persistent in a one-node test cluster, and loses its data the first time the Pod is scheduled to another node. A persistentVolumeClaim is the one that follows the Pod around.

A generic ephemeral volume is the bridge between the two. It is written inline in the Pod, with a claim template, and the control plane creates a PVC named <pod>-<volume> owned by the Pod. The storage is real, provisioned by a StorageClass like any other, but it is deleted when the Pod is.

How Dynamic Provisioning Works, Step by Step

Nobody creates disks by hand any more. On a cluster with a default StorageClass, applying the claim above is enough, and about ten seconds later Postgres has a formatted 20 GiB disk at /var/lib/postgresql. Here is what happens in between.

How a PersistentVolumeClaim becomes a mounted disk, step by step:

  1. Claim: you apply the PVC. The API server stores it with the phase Pending. The PV controller, in the kube-controller-manager, finds no existing PV that fits, sees that the class fast-ssd waits for its first consumer, and leaves the event WaitForFirstConsumer.
  2. Schedule: the Pod is created. The scheduler's VolumeBinding plugin keeps only the nodes where the class could make a volume, and among those it picks worker-2, in zone b. It writes that choice on the claim, as the annotation volume.kubernetes.io/selected-node: worker-2, and waits.
  3. Provision: the CSI driver's external-provisioner, a sidecar container next to the driver, watches claims. It sees one for its driver, ebs.csi.aws.com, with a selected node, and calls the driver's CreateVolume, asking for zone b. The driver creates a 20 GiB gp3 volume there, through the cloud's API.
  4. Bind: the external-provisioner creates a PV for the new disk, already pointing at the claim. The PV controller completes the binding: the claim's phase becomes Bound, and so does the PV's. The scheduler, which was waiting for it, binds the Pod to worker-2.
  5. Attach: the attach-detach controller, also in the kube-controller-manager, sees a Pod on worker-2 that needs the volume, and creates a VolumeAttachment object. The driver's external-attacher sees it and calls ControllerPublishVolume, which attaches the disk to the machine.
  6. Mount: the kubelet on worker-2 waits for the attachment, then calls the driver's node plugin twice: NodeStageVolume formats the disk if it is new and mounts it once for the node, and NodePublishVolume bind-mounts it into the Pod's own directory.
  7. Start: the kubelet asks the container runtime to start the container, with that directory mounted at /var/lib/postgresql. The Pod becomes Running.

With a class whose binding mode is Immediate, steps 3 and 4 come first, as soon as the claim exists, and the scheduler in step 2 is then held to the zone the volume landed in. The section on StorageClasses shows why that matters.

A claim waits for its Pod; the scheduler picks worker-2 in zone b; the provisioner creates the disk there; the PV is bound; the disk is attached; the kubelet mounts it and starts the container.

Notice who is involved. The API server only stores objects. Two controllers in the kube-controller-manager, the PV controller and the attach-detach controller, decide what should happen, and the scheduler decides where. Two sidecars of the CSI driver, the external-provisioner and the external-attacher, make it happen in the storage system. And the kubelet does the last mile on the node. When something breaks, it is one of those, and each one leaves events on the claim or the Pod.

PersistentVolumeClaims and Binding

The PV controller binds a claim to a volume when the volume satisfies all of the claim's demands:

  • Size: the volume's capacity is at least the claim's request. A 20Gi claim can bind a 100Gi volume, and it gets all 100Gi.
  • Access modes: the volume offers every mode the claim asks for.
  • Class: the volume's storageClassName is the claim's. A claim with storageClassName: "" binds only volumes with no class.
  • Selector: if the claim has a selector, the volume's labels match it.
  • Volume mode: both are Filesystem (the default), or both are Block, a raw device with no filesystem.

The binding is written on both sides: the PV's spec.claimRef names the claim, and the claim's spec.volumeName names the PV.

bash
kubectl get pvc -n shop
NAME              STATUS   VOLUME                                     CAPACITY   ACCESS MODES   STORAGECLASS   VOLUMEATTRIBUTESCLASS   AGE
data-postgres-0   Bound    pvc-5d1c2a7e-8f3b-4c61-9a0e-2b7d4e6f1a93   20Gi       RWO            fast-ssd       <unset>                 2m

kubectl get pv shows the same binding from the other side, with the volume's reclaim policy and the claim it holds.

A dynamically provisioned PV is named after the claim's UID, pvc-<uid>, which is how you find a claim's volume in the cloud console: the driver usually tags the disk with it.

Static Provisioning

Before StorageClasses, an administrator created PVs by hand and claims bound to whichever fitted. That still works, and it is the way to give Kubernetes a disk that already exists, with data on it:

yaml
apiVersion: v1
kind: PersistentVolume
metadata:
  name: legacy-orders-db
spec:
  capacity:
    storage: 50Gi
  accessModes: [ReadWriteOnce]
  persistentVolumeReclaimPolicy: Retain
  storageClassName: ""
  claimRef:                      # reserve it for one claim
    namespace: shop
    name: data-orders
  csi:
    driver: ebs.csi.aws.com
    volumeHandle: vol-0a1b2c3d4e5f67890
    fsType: ext4

claimRef reserves the volume for one claim, so nothing else binds it first. volumeHandle is the driver's own ID for the disk. A claim named data-orders in shop, with storageClassName: "", then binds this PV and no other.

Protection Finalizers

A claim that a Pod uses cannot disappear under it. Every PVC carries the finalizer kubernetes.io/pvc-protection, and every PV kubernetes.io/pv-protection. Delete a claim while a Pod still mounts it, and the claim goes to Terminating and stays there until the last Pod using it is gone. Delete a bound PV, and it waits for its claim the same way. kubectl describe pvc lists the Pods in its Used By field, which is the first thing to read when a claim refuses to go.

StorageClasses: How Volumes Are Made

A StorageClass is a template for volumes. Claims name it, and its provisioner reads its parameters:

yaml
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  name: fast-ssd
  annotations:
    storageclass.kubernetes.io/is-default-class: "true"
provisioner: ebs.csi.aws.com
parameters:
  type: gp3
  encrypted: "true"
reclaimPolicy: Delete
allowVolumeExpansion: true
volumeBindingMode: WaitForFirstConsumer
  • provisioner is the CSI driver's name. The parameters are the driver's own: type: gp3 means nothing to Kubernetes, only to the EBS driver.
  • reclaimPolicy is copied into every PV the class makes: Delete, the default, or Retain. It cannot be changed on the class later, only on each PV.
  • allowVolumeExpansion: true lets claims of this class grow.
  • The default class is the one with the annotation storageclass.kubernetes.io/is-default-class: "true". A claim that names no class gets it. A claim that says storageClassName: "" asks for no class at all, and is never given one. If a default class is created after a claim that named none, the control plane gives the claim that class, so the claim no longer waits for a PV that nobody will make.

Volume Binding Modes: Immediate and WaitForFirstConsumer

volumeBindingMode decides when a volume is made, and it is the line that most often explains a Pod stuck in Pending:

Mode When the volume is provisioned and bound Risk
Immediate (the default) As soon as the claim is created, before any Pod uses it The volume's zone is chosen without knowing where the Pod can run
WaitForFirstConsumer When the scheduler places the first Pod that uses the claim, in that node's topology The claim looks Pending until a Pod uses it, which is expected

A cloud disk lives in one zone, and only machines in that zone can attach it. With Immediate, the driver picks a zone first, and the scheduler is then held to it: if the only node with free CPU is in another zone, the Pod cannot run anywhere. With WaitForFirstConsumer, the scheduler picks the node first, using the claim's StorageClass and the driver's topology to check that a volume could be made there, writes its choice on the claim as the annotation volume.kubernetes.io/selected-node, and the provisioner creates the disk in that node's zone.

The canvas below plays twelve seconds of the same claim and Pod on three nodes, one per zone, of which only one has CPU to spare. Pick the binding mode and the zone with room, and watch where the volume is made.

Twelve seconds, with illustrative times, of one claim and the Pod that uses it, on three nodes in three zones, of which only one has CPU to spare. Lanes show the claim, the volume and the Pod. With Immediate, the volume is made in zone a before any Pod asks: if node-a has the room, the Pod runs at 6 s; if the room is in zone b or c, the Pod stays Pending, since no node has both the CPU and the disk's zone. With WaitForFirstConsumer, the scheduler picks the node with room first, the volume is made in its zone, and the Pod runs at 8 s wherever the room is. The controls set the mode and the zone.

When the volume is made, and where

With Immediate, the volume is made in zone a before the Pod exists. If node-a has the room, the Pod runs at 6 s, two seconds sooner than with the other mode, because the disk was ready before it asked. Move the room to zone b or c, and the Pod never runs: node-a has the disk but no CPU, and the node with CPU cannot attach a disk in zone a. With WaitForFirstConsumer, the claim waits, the scheduler picks the node with room, and the volume follows it there: the Pod runs at 8 s wherever the room is. For zonal storage, that is the mode to use, and most cloud providers' default classes already do.

Local volumes, disks inside the node itself, have no provisioner (provisioner: kubernetes.io/no-provisioner) and only make sense with WaitForFirstConsumer: the PV's nodeAffinity names one node, and the scheduler must know about it before it places the Pod.

Storage Capacity Tracking

A zone can also run out of space, or a node of local disk. A CSI driver that tracks capacity publishes CSIStorageCapacity objects, one per topology segment and class, and, with WaitForFirstConsumer, the scheduler skips nodes whose segment cannot hold the claim's size. Without it, the scheduler may pick a node, the provisioning fails there, and the scheduler has to try again.

Access Modes: ReadWriteOnce Is Per Node

A claim's accessModes say how the volume may be mounted. They are a promise the storage must keep, not a lock Kubernetes enforces inside a node:

Mode Short Mounted read-write by Typical storage
ReadWriteOnce RWO One node at a time, and any number of Pods on it Block storage: EBS, Persistent Disk, Azure Disk, Ceph RBD
ReadOnlyMany ROX Many nodes, read-only Shared datasets, a restored snapshot
ReadWriteMany RWX Many nodes at once File storage: NFS, EFS, Azure Files, CephFS
ReadWriteOncePod RWOP One Pod in the whole cluster CSI volumes only; stable since Kubernetes 1.29

Two traps follow from the first line:

  • RWO does not mean one Pod. Two Pods on the same node can both mount an RWO volume read-write, and a database that is not built for it will corrupt its files. If exactly one writer matters, use ReadWriteOncePod, which the scheduler and the kubelet enforce for the whole cluster.
  • RWO blocks a Pod that moves. A Deployment's rolling update starts the new Pod before it stops the old one. If the scheduler puts the new Pod on another node, the volume is still attached to the old node, and the new Pod waits with the event Multi-Attach error for volume "pvc-…" Volume is already exclusively attached to one node and can't be attached to another. For a single-replica workload on RWO storage, use strategy: Recreate, or a StatefulSet, which never runs two Pods with the same identity.

What a volume can do depends on the storage, not on the claim. Asking for ReadWriteMany from a block-storage class does not make the disk shareable: the provisioning fails, and the claim stays Pending.

The PersistentVolume Lifecycle and Reclaim Policies

A PV goes through a short list of phases:

Phase Meaning
Available Free, and not bound to any claim
Bound Bound to a claim
Released Its claim was deleted, but the volume has not been reclaimed
Failed Automatic reclamation failed

What happens when the claim is deleted is the PV's persistentVolumeReclaimPolicy:

Policy When the claim is deleted Use it for
Delete (the default for dynamic volumes) The PV and the disk in the storage system are deleted Data you can recreate, or that is backed up elsewhere
Retain The PV becomes Released, and the disk and its data are kept Data you cannot lose to a mistyped kubectl delete
Recycle Deprecated: the volume was wiped with rm -rf and offered again Nothing new; use dynamic provisioning instead

A Released volume is not offered to new claims, because its claimRef still names the old one and its data still belongs to it. To reuse it, an administrator decides what to do with the data, then removes the reference, and the PV becomes Available:

bash
kubectl patch pv pvc-5d1c2a7e-8f3b-4c61-9a0e-2b7d4e6f1a93 --type json \
  -p '[{"op": "remove", "path": "/spec/claimRef"}]'

The order of deletion used to matter more than it does. With Delete, removing the PV before its claim could leave the disk behind in the cloud, billed and forgotten. Since Kubernetes 1.33, CSI volumes carry the finalizer external-provisioner.volume.kubernetes.io/finalizer, and the disk is deleted whichever object goes first.

Change a volume's policy at any time, on the PV itself, which is how you protect a database before you touch its claim:

bash
kubectl patch pv pvc-5d1c2a7e-8f3b-4c61-9a0e-2b7d4e6f1a93 \
  -p '{"spec":{"persistentVolumeReclaimPolicy":"Retain"}}'

The canvas below holds the four objects of our example: the Pod, its claim, the PV and the disk. Delete them in any order, under either policy, and see which ones go, which wait, and what is left.

The Pod postgres-0, its claim data-postgres-0, the PersistentVolume bound to it and the disk behind it, each with its state. Delete them in any order. A claim deleted while the Pod uses it waits as Terminating, held by pvc-protection, until the Pod goes; a bound PV deleted first waits the same way for its claim. When the claim goes, Delete removes the PV and the disk with its data; Retain leaves the PV Released and the disk with its data, and deleting that PV still keeps the disk, which then no object names. The controls pick the reclaim policy and what to delete.

What deleting a claim does

Delete the claim first, and it waits as Terminating until you delete the Pod, which is the protection finalizer at work. Under Delete, the PV and the disk then go with it. Under Retain, the PV is left Released and the disk keeps its data, even after you delete the PV, which leaves a disk that no Kubernetes object names: yours to find in the cloud console, and yours to pay for.

CSI: How a Storage Driver Plugs In

The Container Storage Interface is a gRPC API, the same for Kubernetes, Nomad and other orchestrators, between the orchestrator and a storage driver. Kubernetes never talks to a cloud's storage API itself any more: every step from the last section that touched the storage system was a CSI call. A driver implements three services:

Service Calls Runs in
Identity GetPluginInfo, GetPluginCapabilities, Probe Both of the driver's parts
Controller CreateVolume, DeleteVolume, ControllerPublishVolume (attach), ControllerUnpublishVolume, ControllerExpandVolume, CreateSnapshot, ControllerModifyVolume The controller plugin: a Deployment, usually two replicas with one leader
Node NodeStageVolume, NodePublishVolume, their Unstage and Unpublish pairs, NodeExpandVolume, NodeGetInfo The node plugin: a DaemonSet, one privileged Pod per node

The driver itself knows nothing about Kubernetes objects. Sidecar containers, maintained by the Kubernetes storage SIG and shipped next to every driver, translate between the two:

  • external-provisioner watches claims and calls CreateVolume and DeleteVolume.
  • external-attacher watches VolumeAttachments and calls ControllerPublishVolume and ControllerUnpublishVolume.
  • external-resizer watches claims whose request grew, and calls ControllerExpandVolume.
  • external-snapshotter watches VolumeSnapshotContents and calls CreateSnapshot.
  • node-driver-registrar, on every node, registers the node plugin's socket with the kubelet, under /var/lib/kubelet/plugins_registry/.
  • livenessprobe turns the driver's Probe into an HTTP health check.

Each sidecar talks to its driver over a Unix socket in a shared emptyDir, and the kubelet talks to the node plugin over a socket on the host, under /var/lib/kubelet/plugins/<driver>/. Nothing goes over the network between Kubernetes and the driver, except the driver's own calls to its storage system.

A CSI driver's controller Deployment has four sidecars that watch the API server and call the driver over a socket; its node DaemonSet is called by the kubelet; the driver calls the cloud's API.

Two objects describe a driver to the cluster:

  • CSIDriver, one per driver, says how Kubernetes should treat it: whether it needs attaching at all (attachRequired: false skips VolumeAttachments, as NFS-like drivers do), whether it wants the Pod's details on mount, and how it handles fsGroup.
  • CSINode, one per node, lists the drivers registered there, the node's ID in each, its topology keys, and how many volumes it can attach. The scheduler's NodeVolumeLimits plugin reads that number, which is why a node with every slot used refuses a Pod that needs one more volume, even with CPU to spare.
bash
kubectl get csidrivers
kubectl get csinode worker-2 -o yaml

Staging and Publishing on the Node

The kubelet's two calls are two mounts. NodeStageVolume mounts the device once per node, at a global path under /var/lib/kubelet/plugins/kubernetes.io/csi/, and formats it first if it has no filesystem. NodePublishVolume bind-mounts that into the Pod's directory, /var/lib/kubelet/pods/<pod-uid>/volumes/kubernetes.io~csi/<pv-name>/mount, and the container runtime mounts the Pod's directory into the container. Two Pods on one node that share an RWO volume share the staged mount and get one bind mount each.

Tearing down runs the same calls backwards: unpublish when the Pod goes, unstage when no Pod on the node uses the volume, detach when the attach-detach controller deletes the VolumeAttachment, and delete when the reclaim policy says so.

The End of In-Tree Plugins

Kubernetes used to carry storage drivers in its own code: awsElasticBlockStore, gcePersistentDisk, azureDisk, cinder and others, built into the kubelet and the controller manager. They tied every storage fix to a Kubernetes release. CSI migration, stable since Kubernetes 1.25, sends every call for those volume types to the matching CSI driver instead, and the in-tree code for the cloud providers has since been removed. Old PVs that still say awsElasticBlockStore keep working, but only if the cluster runs the EBS CSI driver: the migration translates the object, it does not provide the driver.

Expanding, Snapshotting and Changing Volumes

Volume Expansion

To grow a volume, raise the claim's request. Its StorageClass must have allowVolumeExpansion: true:

bash
kubectl patch pvc data-postgres-0 -n shop \
  -p '{"spec":{"resources":{"requests":{"storage":"40Gi"}}}}'

The external-resizer calls ControllerExpandVolume, which grows the disk in the storage system, then the kubelet calls NodeExpandVolume, which grows the filesystem. Most drivers do both while the Pod runs. One that cannot grow a filesystem online leaves the claim with the condition FileSystemResizePending until its Pod restarts. Volumes only grow: Kubernetes does not shrink a claim below its current size. If an expansion fails because the storage cannot give that much, you can lower the request again, as long as it stays above the original size, and retry with a size that works.

Snapshots and Clones

Snapshots are not part of the core API. They are three CRDs and a cluster-wide snapshot controller, which your distribution or cloud provider installs:

  • VolumeSnapshotClass, like a StorageClass for snapshots: a driver and its parameters.
  • VolumeSnapshot, namespaced: a request to snapshot one claim.
  • VolumeSnapshotContent, cluster-wide: the snapshot that exists in the storage system, as a PV is for a claim.
yaml
apiVersion: snapshot.storage.k8s.io/v1
kind: VolumeSnapshot
metadata:
  name: postgres-before-upgrade
  namespace: shop
spec:
  volumeSnapshotClassName: ebs-snapshots
  source:
    persistentVolumeClaimName: data-postgres-0

A new claim restores it by naming it as its dataSource:

yaml
spec:
  storageClassName: fast-ssd
  dataSource:
    apiGroup: snapshot.storage.k8s.io
    kind: VolumeSnapshot
    name: postgres-before-upgrade
  accessModes: [ReadWriteOnce]
  resources:
    requests:
      storage: 20Gi

A dataSource of kind: PersistentVolumeClaim instead makes a clone of another claim in the same namespace and class, without a snapshot in between. A snapshot of a running database is crash-consistent, like pulling the power: Postgres will recover from it, but quiesce the application, or use its own backup tool, if you need more than that.

VolumeAttributesClass: Changing Performance in Place

A StorageClass's parameters are fixed when the volume is made. To give a running volume more IOPS, you used to migrate its data. A VolumeAttributesClass, stable since Kubernetes 1.34, holds the attributes that a driver can change on a live volume:

yaml
apiVersion: storage.k8s.io/v1
kind: VolumeAttributesClass
metadata:
  name: gp3-fast
driverName: ebs.csi.aws.com
parameters:
  iops: "6000"
  throughput: "500"

Set volumeAttributesClassName: gp3-fast on the claim, and the external-resizer calls the driver's ControllerModifyVolume. The class's parameters cannot change; to change a volume again, point its claim at another class. It only works with drivers that implement the call.

StatefulSets and volumeClaimTemplates

A Deployment's Pods share a template, so they would share one claim. A StatefulSet gives each replica a claim of its own, from a volumeClaimTemplates entry:

yaml
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: postgres
  namespace: shop
spec:
  serviceName: postgres
  replicas: 3
  selector:
    matchLabels: {app: postgres}
  template:
    metadata:
      labels: {app: postgres}
    spec:
      containers:
      - name: postgres
        image: postgres:18
        volumeMounts:
        - name: data
          mountPath: /var/lib/postgresql
  volumeClaimTemplates:
  - metadata:
      name: data
    spec:
      storageClassName: fast-ssd
      accessModes: [ReadWriteOnce]
      resources:
        requests:
          storage: 20Gi
  persistentVolumeClaimRetentionPolicy:
    whenDeleted: Retain
    whenScaled: Retain

Each claim is named <template>-<statefulset>-<ordinal>: data-postgres-0, data-postgres-1, data-postgres-2. That is where this article's claim name came from. When postgres-1 is rescheduled, it gets data-postgres-1 back, wherever it lands that can reach the volume.

The claims outlive the Pods on purpose. By default, deleting the StatefulSet or scaling it down leaves every claim and its data in place, and scaling back up reattaches them. persistentVolumeClaimRetentionPolicy, stable since Kubernetes 1.32, changes that: whenDeleted: Delete removes the claims with the StatefulSet, and whenScaled: Delete removes the claims of the replicas a scale-down removes. Both default to Retain, which is the safe choice for a database.

Permissions: fsGroup and Slow Mounts

A new filesystem belongs to root. A container that runs as user 999 cannot write to it, and Postgres exits with permission denied. The Pod's securityContext.fsGroup fixes that: the kubelet changes the volume's group to the given ID and makes it group-writable before the container starts.

yaml
spec:
  securityContext:
    runAsUser: 999
    fsGroup: 999
    fsGroupChangePolicy: OnRootMismatch

By default (Always), the kubelet walks the whole volume on every mount and changes every file. On a volume with millions of files, that can take many minutes, and the Pod sits in ContainerCreating with nothing in its events to say why. fsGroupChangePolicy: OnRootMismatch skips the walk when the volume's root already has the right owner and mode, which, after the first mount, it does. Whether the kubelet applies fsGroup at all is the driver's choice, in its CSIDriver's fsGroupPolicy.

Why a PVC Stays Pending, and a Pod in ContainerCreating

When storage fails, the object that waits tells you where. A claim stuck in Pending means provisioning or binding failed. A Pod stuck in Pending with a bound claim means scheduling failed. A Pod stuck in ContainerCreating means attaching or mounting failed. kubectl describe on each shows the events that name the cause:

Symptom Likely cause Where to look
PVC Pending, event WaitForFirstConsumer Nothing is wrong: no Pod uses the claim yet Create the Pod; the claim binds when it is scheduled
PVC Pending, no persistent volumes available for this claim and no storage class is set No default class, and the claim names none kubectl get storageclass; set storageClassName or a default
PVC Pending, ExternalProvisioning events and nothing else The driver's provisioner is not running, or the class names a driver that is not installed kubectl get csidrivers; the controller plugin's Pods and its external-provisioner logs
PVC Pending, ProvisioningFailed The storage system refused: quota, a bad parameter, an access mode it cannot offer The event's message, then the driver's logs
Pod Pending, volume node affinity conflict The volume's zone has no node the Pod fits on The PV's nodeAffinity; the binding mode of its class
Pod ContainerCreating, Multi-Attach error An RWO volume is still attached to another node The old Pod, and kubectl get volumeattachments
Pod ContainerCreating, FailedAttachVolume The attach call failed: node limit, a permission, the disk in another zone The VolumeAttachment's status, the external-attacher's logs
Pod ContainerCreating, FailedMount Staging or publishing failed: no node plugin on the node, a filesystem error The node plugin's Pod on that node, and the kubelet's logs
Pod ContainerCreating for minutes, no error fsGroup walking a large volume fsGroupChangePolicy: OnRootMismatch
PVC Terminating forever A Pod still uses it kubectl describe pvc, its Used By

If the PVC is not Bound, check provisioning; if the Pod is not scheduled, the volume's zone; if the disk is not attached, attaching; if it is attached but not mounted, the node plugin or fsGroup.

When a Node Dies with a Volume Attached

An RWO volume can only move when its old node lets go. If that node is down, nothing on it can unmount the volume, and the attach-detach controller will not detach a volume that a Pod may still be writing to. The Pod on the dead node stays Terminating, and its replacement waits with a Multi-Attach error. After six minutes of a Pod deletion that has not succeeded, Kubernetes force-detaches the volume. If you know the node is really off, the non-graceful node shutdown taint, stable since Kubernetes 1.28, moves things along at once:

bash
kubectl taint nodes worker-2 node.kubernetes.io/out-of-service=nodeshutdown:NoExecute

The Pods on the node are deleted, their volumes detached immediately, and the replacements start elsewhere. Only add it to a node that is truly shut down: a node that is still running and writing would now share its disk with the new Pod.

Debugging Storage, Step by Step

1. Is the claim bound?

bash
kubectl get pvc -n shop
kubectl describe pvc data-postgres-0 -n shop

Bound with a volume name means provisioning and binding worked: move to step 3. Pending means read the events at the bottom of describe, which name the waiting party.

2. Can the class be served?

bash
kubectl get storageclass
kubectl get csidrivers
kubectl -n kube-system get pods -l app=ebs-csi-controller
kubectl -n kube-system logs deploy/ebs-csi-controller -c csi-provisioner --tail=50

The class's provisioner must match a CSIDriver that exists, and its controller Pods must be running. The labels and names are the EBS driver's; every driver's chart names its own, with a container per sidecar.

3. Did the volume attach to the Pod's node?

bash
kubectl get pod postgres-0 -n shop -o wide
kubectl get volumeattachments | grep pvc-5d1c2a7e

A VolumeAttachment for the right node with ATTACHED true means the controller's half is done. One for another node is the Multi-Attach case. None at all, with the Pod scheduled, points at the attach-detach controller or a driver that does not need attaching.

4. Did the kubelet mount it?

bash
kubectl describe pod postgres-0 -n shop
kubectl -n kube-system get pods -o wide -l app=ebs-csi-node | grep worker-2

FailedMount events come from the kubelet. The node plugin must be running on the Pod's node, and its logs, and the kubelet's (journalctl -u kubelet on the node), say which call failed.

5. Inside the container, is it what you expect?

bash
kubectl exec -n shop postgres-0 -- df -h /var/lib/postgresql
kubectl exec -n shop postgres-0 -- ls -ld /var/lib/postgresql

The size should be the claim's, and the owner what fsGroup asked for. A size of the node's root disk means the volume is not mounted where the container looks: compare mountPath with the path the application writes to.

Key Takeaways

  • A PersistentVolumeClaim is an application's request for storage; a PersistentVolume is the storage; binding is one to one and lasts until the claim is deleted. Pods name claims, never disks.
  • With a StorageClass, volumes are made on demand: the PV controller and the attach-detach controller decide, the CSI driver's sidecars act, and the kubelet mounts.
  • Use WaitForFirstConsumer for zonal storage. With Immediate, the volume's zone is chosen before the Pod's node, and the Pod can end up with nowhere to run.
  • ReadWriteOnce is one node, not one Pod. Use ReadWriteOncePod for a single writer, and Recreate or a StatefulSet for a single replica that moves.
  • Delete removes the disk with the claim; Retain keeps it as a Released PV. Set Retain on a PV before you touch the claim of data you cannot lose.
  • CSI is a gRPC API with Controller and Node services; sidecars translate Kubernetes objects into calls. In-tree cloud plugins are gone, and CSI migration needs the CSI driver installed.
  • Volumes grow online with allowVolumeExpansion, never shrink, and change performance in place with a VolumeAttributesClass. Snapshots are CRDs with a controller of their own.
  • To debug, read who is waiting: a Pending claim is provisioning, a Pending Pod is scheduling, ContainerCreating is attaching or mounting.

FAQ

What is the difference between a PV and a PVC in Kubernetes?

A PersistentVolume is a piece of storage in the cluster, such as a cloud disk, with a size, access modes and a reclaim policy; it belongs to no namespace. A PersistentVolumeClaim is a namespaced request for storage, made by an application. Kubernetes binds each claim to one volume that satisfies it, and Pods mount the volume by naming the claim.

What is a StorageClass in Kubernetes?

A StorageClass describes how to make volumes: which CSI driver provisions them, with what parameters, what happens to them when their claim is deleted, whether they can grow, and when they are made. A claim names a class, or gets the default one, and the class's provisioner creates a matching PersistentVolume for it.

What is CSI in Kubernetes?

The Container Storage Interface is a standard gRPC API between Kubernetes and storage drivers. A CSI driver runs in the cluster as a controller Deployment and a node DaemonSet, and Kubernetes calls it to create, attach, mount, resize, snapshot and delete volumes. It replaced the storage drivers that used to be built into Kubernetes itself.

Why is my PersistentVolumeClaim stuck in Pending?

Run kubectl describe pvc and read the events. WaitForFirstConsumer means the claim waits for a Pod to use it, which is normal. "No storage class is set" means there is no default class and the claim names none. Repeated ExternalProvisioning events mean the CSI driver's provisioner is not running, and ProvisioningFailed carries the storage system's own error.

Can two Pods use the same ReadWriteOnce volume?

Yes, if they run on the same node: ReadWriteOnce limits the volume to one node, not one Pod. Pods on different nodes cannot, and the second waits with a Multi-Attach error. To allow exactly one Pod in the whole cluster, use ReadWriteOncePod; to share a volume across nodes, use storage that supports ReadWriteMany, such as NFS or a cloud file service.

What happens to data when a PVC is deleted?

It depends on the PersistentVolume's reclaim policy. With Delete, the default for dynamically provisioned volumes, the PV and the underlying disk are deleted, and the data is gone. With Retain, the PV becomes Released and the disk keeps its data until an administrator deletes or reuses it. A claim that a Pod still uses is not deleted until that Pod is gone.

How do I resize a PersistentVolume in Kubernetes?

Edit the claim, not the volume: raise spec.resources.requests.storage. Its StorageClass must set allowVolumeExpansion: true. The CSI driver grows the disk, then the kubelet grows the filesystem, usually while the Pod keeps running. Volumes can only grow; Kubernetes does not shrink a claim below its current size.

What's Next

You have followed a claim from a YAML file to a mounted disk: the PV controller bound it, the CSI driver's sidecars made and attached the disk, and the kubelet mounted it into the Pod. Every step was a controller watching an object and acting until the cluster matched it, and when one of them fails, the Pod says which, if you know where to read. In the next part of Kubernetes Internals: How a Cluster Really Works, Kubernetes Troubleshooting: Fix CrashLoopBackOff, OOMKilled and More, we turn the series into a playbook: what each Pod status means, which command shows its cause, and how to fix it.


Comments

No comments yet.