Skip to content
LF Cert Trainer

Lesson 101 · Section 8: Storage

Lesson 101: Storage Class: volumes created on demand

How a StorageClass and its provisioner create a PersistentVolume for each claim, what every field of a StorageClass controls, how the default class and the empty class name behave, and why a claim with WaitForFirstConsumer stays Pending until a Pod uses it. · 19 min read · 3 min video

1/9Storage Class
0:00 / 3:15

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

Why storage classes exist

In the last three lessons every PersistentVolume was made by hand. That is static provisioning, and it has a cost that grows with the cluster:

  • Before a user can claim storage, an administrator must create a disk at the storage provider and then write a PV that describes exactly that disk.
  • The administrator has to guess sizes in advance. A claim for 6Gi either waits because only 5Gi volumes exist, or it takes a 100Gi volume and wastes most of it.
  • When a claim is deleted, someone cleans up the released volume and the disk.

A StorageClass removes the administrator from the loop. It describes a kind of storage and names a program, the provisioner, that can create volumes of that kind. From then on a user's claim is all it takes: the provisioner creates a disk of exactly the requested size, creates the PV for it, and the claim is bound. This is dynamic provisioning.

Dynamic provisioning: the claim comes firstnamesnamescreatescreatesboundPVC db-claimclass: fast, 10GiStorageClass fastprovisioner, parametersProvisionera CSI driverPV pvc-7c1e...made for this claimNew disk10Gi SSD
Dynamic provisioning: the claim comes first. The claim names a StorageClass. The class names a provisioner. The provisioner creates a real disk of the requested size and a PersistentVolume that is already bound to the claim.

Parts:

  • PVC db-claim (class: fast, 10Gi)
  • StorageClass fast (provisioner, parameters)
  • Provisioner (a CSI driver)
  • PV pvc-7c1e... (made for this claim)
  • New disk (10Gi SSD)

Connections:

  • PVC db-claim to StorageClass fast: names
  • StorageClass fast to Provisioner: names
  • Provisioner to New disk: creates
  • Provisioner to PV pvc-7c1e...: creates
  • PV pvc-7c1e... to PVC db-claim: bound

The word "class" is meant literally. An administrator can offer several, for example standard on cheap disks, fast on SSDs and replicated on storage that is copied across zones. Users choose by name and never see the details. The names mean nothing to Kubernetes; they are whatever the administrator picked.

What a StorageClass looks like

apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  name: fast
provisioner: ebs.csi.aws.com
parameters:
  type: gp3
reclaimPolicy: Delete
volumeBindingMode: WaitForFirstConsumer
allowVolumeExpansion: true

Notice what is missing: there is no spec. The fields sit at the top level. A StorageClass is cluster-scoped (no namespace), its short name is sc, and its API group is storage.k8s.io.

FieldMeaningDefault
provisionerWho creates the volumes: the name of a CSI driver, or kubernetes.io/no-provisioner for noneRequired
parametersSettings passed to the provisioner as they are: disk type, file system, replication. Each provisioner defines its own keysNone
reclaimPolicyCopied to every PV the class creates: Delete or RetainDelete
volumeBindingModeWhen to provision and bind: Immediate or WaitForFirstConsumerImmediate
allowVolumeExpansionWhether claims of this class may be enlarged laterfalse
mountOptionsMount options put on every PV of the class, for example noatimeNone
allowedTopologiesLimits provisioning to certain zones or nodesAnywhere

Only provisioner is required. A StorageClass cannot be edited once it exists, apart from its labels and annotations and allowVolumeExpansion. To change the provisioner, the parameters, the reclaim policy or the binding mode, delete the class and create it again. Existing volumes are not affected, because they were stamped with the settings when they were created.

The provisioner

The provisioner is a controller that watches for claims of its classes. In today's clusters it is part of a CSI driver, which you met in the Container Storage Interface lesson. The driver's controller Pod runs a helper container called external-provisioner. It sees the new claim, asks the driver to create a volume, and writes the PV object.

WhereTypical provisionerNotes
AWSebs.csi.aws.comParameters such as type: gp3
Google Cloudpd.csi.storage.gke.iotype: pd-balanced, pd-ssd
Azuredisk.csi.azure.comskuName: StandardSSD_LRS
kind, k3s, many practice clustersrancher.io/local-pathA directory on the node per claim
NFSnfs.csi.k8s.ioOne subdirectory of an export per claim
Anykubernetes.io/no-provisionerNo dynamic provisioning: the class only groups hand-made volumes

A cluster built with kubeadm has no StorageClass and no provisioner until someone installs one. On such a cluster kubectl get sc prints No resources found, and a claim that expects dynamic provisioning waits forever. Older manifests name in-tree provisioners such as kubernetes.io/aws-ebs or kubernetes.io/gce-pd. That code has been removed from Kubernetes in favour of the CSI drivers above.

How a claim becomes a volume

  1. A user creates a claim with storageClassName: fast and a request for 10Gi.
  2. The PV controller sees that the claim names a class and leaves it for that class's provisioner (after checking that no existing PV of the class already fits).
  3. The provisioner reads the class's parameters and creates a 10Gi disk at the storage back end.
  4. It creates a PV named pvc- followed by the claim's UID, with the class name, the class's reclaim policy, and a claimRef that points at the claim.
  5. The PV controller binds the two. The claim is Bound, and its capacity is exactly what was asked for.

Deleting the claim runs this in reverse: with the default policy Delete, the provisioner removes the disk and the PV.

The default class and the empty string

One class can be marked as the cluster's default with an annotation:

metadata:
  name: standard
  annotations:
    storageclass.kubernetes.io/is-default-class: "true"

kubectl get sc shows it as standard (default). The default matters for claims that do not mention a class. An admission controller in the API server, DefaultStorageClass, fills the default class's name into such a claim when it is created.

Which class a claim getsthe class it namesthe default is filled inno provisioningPVCstorageClassName: fastPVCno storageClassNamePVCstorageClassName: ""fastnew volumestandard (default)new volumeHand-made PVno class
Which class a claim gets. A claim that names a class gets that class. A claim with no storageClassName gets the default class, if the cluster has one. A claim with an empty string asks for no class at all and binds only to a hand-made volume.

Parts:

  • PVC (storageClassName: fast)
  • PVC (no storageClassName)
  • PVC (storageClassName: "")
  • fast (new volume)
  • standard (default) (new volume)
  • Hand-made PV (no class)

Connections:

  • PVC to fast: the class it names
  • PVC to standard (default): the default is filled in
  • PVC to Hand-made PV: no provisioning
The claim hasWith a default classWithout a default class
storageClassName: fastClass fastClass fast
No storageClassNameThe default class is filled in; a volume is provisionedBinds only to a hand-made PV with no class
storageClassName: ""No class. Binds only to a hand-made PV with no classThe same

The empty string is the way to say "I want static provisioning, do not create anything for me". You used it in the Persistent Volume Claims lesson for exactly that reason.

Under the hood · Claims created before the default class existed

A claim with no storageClassName created on a cluster with no default class used to stay classless for ever. In current Kubernetes the PV controller assigns the default class to such claims retroactively: as soon as a default class appears, every pending claim whose storageClassName is unset gets it and is provisioned. Claims that say storageClassName: "" are left alone, which is one more reason to write the empty string when you mean it.

Binding mode: when the volume is created

volumeBindingMode answers a question that static provisioning never had to ask: where should the new volume be created?

Immediate or WaitForFirstConsumerat oncestuckwaitsthenPVCImmediateVolume in zone acreated at oncePodonly fits zone bPVCWaitForFirstConsumerPodscheduled to zone bVolume in zone bcreated after
Immediate or WaitForFirstConsumer. With Immediate the volume is created as soon as the claim exists, before anyone knows where the Pod will run. With WaitForFirstConsumer the claim waits for a Pod, the scheduler picks a node, and the volume is created where that node can reach it.

Parts:

  • PVC (Immediate)
  • Volume in zone a (created at once)
  • Pod (only fits zone b)
  • PVC (WaitForFirstConsumer)
  • Pod (scheduled to zone b)
  • Volume in zone b (created after)

Connections:

  • PVC to Volume in zone a: at once
  • Volume in zone a to Pod: stuck
  • PVC to Pod: waits
  • Pod to Volume in zone b: then
  • Immediate (the default). The volume is provisioned and bound as soon as the claim is created. The provisioner knows nothing about the Pod that will use it. A cloud disk exists in one zone, and a local volume on one node. If the Pod can only run elsewhere, because of a node selector, taints or a lack of free CPU, it can never be scheduled next to its volume.
  • WaitForFirstConsumer. Nothing happens until a Pod that uses the claim is created. The scheduler chooses a node taking all of the Pod's constraints into account, and only then is the volume provisioned, in a place that node can reach. For hand-made volumes the same mode delays binding, so the claim is matched with a PV that suits the Pod's node.

The visible effect is a claim that stays Pending with this event:

Normal  WaitForFirstConsumer  persistentvolume-controller  waiting for first consumer to be created before binding

That is not an error and there is nothing to fix. Create the Pod.

Under the hood · A class with no provisioner: local volumes

A local PersistentVolume is a disk or directory on one particular node, with a node affinity that says which one. There is no dynamic provisioner for it in Kubernetes itself, but it still needs WaitForFirstConsumer, so that the scheduler can choose between the local volumes on different nodes. The class exists only to carry that setting:

apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  name: local-storage
provisioner: kubernetes.io/no-provisioner
volumeBindingMode: WaitForFirstConsumer

An administrator still creates each PV by hand, with storageClassName: local-storage. A claim that names the class stays Pending until a Pod uses it, then binds to one of those PVs. If no PV of the class exists, the claim and the Pod both wait, and no provisioner will come to help.

Under the hood · Changing a volume's performance later: VolumeAttributesClass

A StorageClass's parameters are fixed at the moment a volume is created. Recent Kubernetes versions add a second, similar object, the VolumeAttributesClass, for settings that a driver can change on a live volume, such as provisioned IOPS and throughput. A claim names one in spec.volumeAttributesClassName, and changing that field asks the CSI driver to modify the existing disk. This is why kubectl get pvc and kubectl get pv have a VOLUMEATTRIBUTESCLASS column, which shows <unset> on most clusters.

Using it

Example · Look at the classes, then get a volume from one

kubectl get sc
NAME                   PROVISIONER             RECLAIMPOLICY   VOLUMEBINDINGMODE      ALLOWVOLUMEEXPANSION   AGE
local-path (default)   rancher.io/local-path   Delete          WaitForFirstConsumer   false                  12d

One class, marked default, which waits for a consumer. Create a claim that names it and a Pod that uses the claim:

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: db-claim
spec:
  storageClassName: local-path
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 2Gi
---
apiVersion: v1
kind: Pod
metadata:
  name: db
spec:
  containers:
    - name: redis
      image: redis:7
      volumeMounts:
        - name: data
          mountPath: /data
  volumes:
    - name: data
      persistentVolumeClaim:
        claimName: db-claim
kubectl apply -f db.yaml
kubectl get pvc,pv
NAME                             STATUS   VOLUME                                     CAPACITY   ACCESS MODES   STORAGECLASS   VOLUMEATTRIBUTESCLASS   AGE
persistentvolumeclaim/db-claim   Bound    pvc-7c1e52b4-0d3a-4f6e-9a57-2b1c8e4d90aa   2Gi        RWO            local-path     <unset>                 15s

NAME                                                        CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS   CLAIM              STORAGECLASS   VOLUMEATTRIBUTESCLASS   REASON   AGE
persistentvolume/pvc-7c1e52b4-0d3a-4f6e-9a57-2b1c8e4d90aa   2Gi        RWO            Delete           Bound    default/db-claim   local-path     <unset>                          11s

Nobody wrote that PV. Its name is pvc- plus the claim's UID, its capacity is exactly the 2Gi requested, and its reclaim policy is the class's Delete.

Example · Create a StorageClass and make it the default

The task: "Create a StorageClass fast with the provisioner rancher.io/local-path, the reclaim policy Retain and binding that waits for a Pod. Make it the default class."

apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  name: fast
  annotations:
    storageclass.kubernetes.io/is-default-class: "true"
provisioner: rancher.io/local-path
reclaimPolicy: Retain
volumeBindingMode: WaitForFirstConsumer
kubectl apply -f fast.yaml
kubectl get sc
NAME                   PROVISIONER             RECLAIMPOLICY   VOLUMEBINDINGMODE      ALLOWVOLUMEEXPANSION   AGE
fast (default)         rancher.io/local-path   Retain          WaitForFirstConsumer   false                  4s
local-path (default)   rancher.io/local-path   Delete          WaitForFirstConsumer   false                  12d

Two defaults. Take the mark off the old one:

kubectl patch sc local-path -p '{"metadata":{"annotations":{"storageclass.kubernetes.io/is-default-class":"false"}}}'
kubectl get sc
NAME             PROVISIONER             RECLAIMPOLICY   VOLUMEBINDINGMODE      ALLOWVOLUMEEXPANSION   AGE
fast (default)   rancher.io/local-path   Retain          WaitForFirstConsumer   false                  40s
local-path       rancher.io/local-path   Delete          WaitForFirstConsumer   false                  12d

The same patch with "true" marks an existing class as default, so you never need to recreate a class for this.

Example · A claim that is Pending, and should be

kubectl get pvc cache-claim
kubectl describe pvc cache-claim | tail -n 2
NAME          STATUS    VOLUME   CAPACITY   ACCESS MODES   STORAGECLASS   VOLUMEATTRIBUTESCLASS   AGE
cache-claim   Pending                                      fast           <unset>                 2m

  Normal  WaitForFirstConsumer  8s (x9 over 2m)  persistentvolume-controller  waiting for first consumer to be created before binding

Confirm the class's mode, and compare with the two events that do mean trouble:

kubectl get sc fast -o jsonpath='{.volumeBindingMode}{"\n"}'
Event on the claimMeaningWhat to do
waiting for first consumer to be created before bindingHealthy. The class waits for a PodCreate the Pod
storageclass.storage.k8s.io "fsat" not foundThe claim names a class that does not existRecreate the claim with the right name, or create the class
Waiting for a volume to be created either by the external provisioner ... that never endsThe provisioner is not running or cannot create the volumeCheck the driver's Pods and their logs, usually in kube-system
no persistent volumes available for this claim and no storage class is setNo class and no fitting hand-made PVName a class, or create a PV

Example · Keep the data of a dynamically provisioned volume

A volume from a class with reclaimPolicy: Delete disappears with its claim. To protect an existing volume, change the policy on the PV; the class cannot be edited and would only affect new volumes anyway.

PV=$(kubectl get pvc db-claim -o jsonpath='{.spec.volumeName}')
kubectl patch pv $PV -p '{"spec":{"persistentVolumeReclaimPolicy":"Retain"}}'
kubectl get pv $PV -o custom-columns=NAME:.metadata.name,POLICY:.spec.persistentVolumeReclaimPolicy,STATUS:.status.phase
NAME                                       POLICY   STATUS
pvc-7c1e52b4-0d3a-4f6e-9a57-2b1c8e4d90aa   Retain   Bound

Now deleting db-claim leaves the PV as Released with the data intact, exactly like a hand-made volume.

Example · Grow a claim

The claim is full and its class allows expansion:

kubectl get sc fast -o jsonpath='{.allowVolumeExpansion}{"\n"}'     # true
kubectl patch pvc db-claim -p '{"spec":{"resources":{"requests":{"storage":"5Gi"}}}}'
kubectl get pvc db-claim -o jsonpath='{.status.capacity.storage}{"\n"}'
5Gi

The driver enlarges the disk, then the file system, usually while the Pod keeps running. status.capacity changes when both are done; until then kubectl describe pvc shows the progress in its conditions and events. If the class does not allow it, the patch is refused:

persistentvolumeclaims "db-claim" is forbidden: only dynamically provisioned pvc can be resized and the storageclass that provisions the pvc must support resize

allowVolumeExpansion is the one setting you may change on an existing class: kubectl patch sc fast -p '{"allowVolumeExpansion":true}'. The driver must support resizing too. Claims can grow, never shrink.

Tricks

Common mistakes

  • Writing a spec in a StorageClass. provisioner, parameters, reclaimPolicy and volumeBindingMode are top-level fields. kubectl reports unknown field "spec".
  • Treating a Pending claim as broken when the class uses WaitForFirstConsumer. Read the event. If it says "waiting for first consumer", create the Pod.
  • Expecting dynamic provisioning on a kubeadm cluster. There is no class and no provisioner until one is installed. Use hand-made PVs, or a class with kubernetes.io/no-provisioner when the task asks for one.
  • Forgetting that Delete is the default reclaim policy. Deleting a claim of such a class destroys the data. Set reclaimPolicy: Retain in the class, or patch the PV.
  • Leaving two default classes. Claims without a class go to the newest one. Set the annotation to "false" on the old default.
  • Writing the default annotation as a boolean. Annotation values are strings: "true" with quotes. Without them the API server rejects the object.
  • Misspelling the class name in a claim. The claim is accepted and stays Pending with not found. A claim's class cannot be edited; delete and recreate it.
  • Trying to shrink a claim, or to grow one whose class has allowVolumeExpansion: false. Both are refused.

Recap

  • A StorageClass names a provisioner and the parameters to give it. A claim that names the class gets a new volume of exactly the requested size: dynamic provisioning.
  • The fields are top-level: provisioner (required), parameters, reclaimPolicy (default Delete), volumeBindingMode (default Immediate), allowVolumeExpansion (default false).
  • A class is cluster-scoped and immutable except for allowVolumeExpansion and its metadata. To change it, delete and recreate it.
  • The annotation storageclass.kubernetes.io/is-default-class: "true" marks the default class. Claims without a storageClassName get it; claims with "" get no class.
  • WaitForFirstConsumer delays provisioning or binding until a Pod is scheduled, so the claim is Pending until then.
  • kubernetes.io/no-provisioner makes a class for hand-made volumes, used with local volumes.
  • To keep the data of a dynamic volume, set Retain in the class before creating claims, or patch the 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 StorageClass with the right reclaim policy and binding mode, make it the cluster's only default, and let a waiting app get its volume from it.

    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.