Narration:When a container restarts, the writable layer in its image is discarded. So where does the data go? The answer is volumes, and the lifecycle of a volume decides the data's fate.
Kubernetes Hour 4: Storage and Stateful Apps
- Explain how the lifecycles differ between Pod-internal volumes (emptyDir/configMap/secret/projected/image) and persistent volumes (PV/PVC), and predict where data goes during "container restart / Pod deletion / node failure".
- Draw the full sequence of a PVC from creation to being written by a container: PV controller → scheduler → external-provisioner → CreateVolume → attach → NodeStage/NodePublish.
- Understand the CSI architecture (controller/node plugin + sidecar) and how Azure Disk and Azure Files CSI differ. Choose the right StorageClass, access modes, reclaim policy and topology for your workload.
- Online expansion, VolumeSnapshot, cloning, and restoring from snapshots. Understand VolumeGroupSnapshot (GA in v1.36) and volume populators.
- Run PostgreSQL 17 with a StatefulSet and volumeClaimTemplates, handling PGDATA, fsGroup, graceful shutdown and PVC retention policy. Know when to use an Operator (CloudNativePG) or a managed database.
- Complete namespace-level backup and restore with Velero (CSI snapshots or Kopia filesystem backup), and use pre hooks for application-consistent backups.
- Master a storage troubleshooting workflow: PVC Pending, Multi-Attach, FailedMount, Permission denied, full volumes, Released PVs, and stuck deletion.
1-hour timetable
| # | Time | Module | Core content | Animation / interaction | Lab |
|---|---|---|---|---|---|
| 0 | Before class | Warm-up | Check the kind cluster lab, StorageClasses, the default SC annotation and shop's current state. Optionally create the AKS cluster aks-lab. | — | kubectl get sc, optional az aks create |
| 1 | 00–07 | Volume basics | emptyDir (Memory, sizeLimit), configMap/secret/downwardAPI/projected, hostPath risks, image volume (GA in v1.36), generic ephemeral volumes; readOnly, subPath, mountPropagation | Container restart / Pod deletion / node failure data-location simulator | Multi-volume Pod: observe the data in each volume type after restarts and deletions |
| 2 | 07–15 | PV · PVC · StorageClass | Static vs dynamic provisioning, PV controller binding, SC fields, default SC, PVC/PV phases, v1.37 Beta: PVC Unused condition | PVC → WaitForFirstConsumer → scheduling → provision → bind → attach → mount timing animation | Dynamic provisioning with local-path + manual binding to a static PV |
| 3 | 15–22 | CSI architecture and Azure Disk | controller plugin + sidecar, node plugin + registrar, CSIDriver/CSINode/VolumeAttachment; Azure Disk / Files CSI, AKS built-in SCs, Premium SSD v2 | CSI gRPC call-chain animation (each step shows the method name and the K8s object) | Install csi-driver-host-path; observe VolumeAttachment on AKS |
| 4 | 22–29 | Access modes · reclaim policies · topology | RWO/ROX/RWX/RWOP, Retain/Delete, zone topology, allowedTopologies, ZRS, node volume limits | "Backend × access mode × scenario" feasibility checker | RWOP conflict reproduction, Retain reclaim drill |
| 5 | 29–36 | Expansion · snapshots · clones | Online expansion, no shrinking, VolumeSnapshot/Content/Class, dataSource restore, PVC cloning, VolumeGroupSnapshot, populators | Expansion / snapshot / restore / clone object relationship simulator | Snapshot restore with hostpath CSI (kind) or Azure Disk (AKS) |
| 6 | 36–46 | StatefulSet + PostgreSQL in practice | volumeClaimTemplates, data-db-0, PVC retention policy, PGDATA subdirectory, fsGroup, graceful shutdown, Operator vs managed | StatefulSet replica and PVC binding relationship simulator | Write → delete Pod → scale to 0 → scale up → data still there |
| 7 | 46–53 | Backup and restore (Velero) | etcd snapshot vs application-level vs volume snapshot; BSL/VSL, CSI snapshots, Kopia node-agent, hooks, schedules; Azure Backup for AKS | Backup and restore workflow animation | kind + MinIO: back up shop → delete namespace → restore |
| 8 | 53–60 | Storage troubleshooting | Pending, Multi-Attach, FailedMount, permissions, full volumes, Released, finalizers | Detach/attach timeline after node failure + troubleshooting decision tree | Trigger 4 kinds of failure on purpose and fix them |
| — | After class | Cheat sheet · Capstone lab | shop db: StatefulSet + PVC + expansion + snapshot + Velero backup → delete namespace → restore → verify row count | 12-question final quiz | Capstone lab |
Knowledge Coverage Matrix
| Target skill | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Choose the right Pod-internal volume type | ✓ | · | · | · | · | ✓ | · | · | kubectl explain pod.spec.volumes | M1 Multi-volume Pod |
| Dynamic / static provisioning and binding | · | ✓ | ✓ | · | · | ✓ | · | ✓ | kubectl get pvc,pv -o wide | M2 local-path |
| Understand CSI components and objects | · | ✓ | ✓ | · | ✓ | · | · | ✓ | kubectl get csidriver,csinode,volumeattachment | M3 hostpath CSI |
| Access mode and topology design | · | ✓ | ✓ | ✓ | · | ✓ | · | ✓ | kubectl get pv -L topology.kubernetes.io/zone | M4 RWOP |
| Expansion / snapshot / clone | · | · | ✓ | · | ✓ | ✓ | ✓ | · | kubectl patch pvc, kubectl get vs,vsc | M5 Snapshot restore |
| Running a stateful database | · | · | · | ✓ | · | ✓ | ✓ | ✓ | kubectl scale sts, psql | M6 PostgreSQL |
| Backup and disaster recovery | · | · | · | · | ✓ | · | ✓ | · | velero backup/restore create | M7 Velero |
| Storage troubleshooting | ✓ | ✓ | ✓ | ✓ | · | ✓ | · | ✓ | kubectl describe pvc, kubectl get events | M8 Fault injection |
Topics excluded from this hour
| Topic | Why not covered | Where to learn |
|---|---|---|
| Writing your own CSI driver | Belongs to the storage vendor development domain and cannot be covered within 1 hour | Kubernetes CSI Developer Documentation |
| Self-managed distributed storage such as Ceph/Rook, Longhorn, OpenEBS | High operational complexity; this hour focuses on cloud-managed disks | Official project docs; KubeCon storage sessions |
| PostgreSQL primary-replica replication details, Patroni, PITR | Belongs to the database specialty | CloudNativePG docs; Azure Database for PostgreSQL docs |
| Hands-on etcd backup and restore | Control-plane operations; on AKS, handled by the platform | Kubernetes docs "Operating etcd clusters"; hour 6, Module 6 gives an overview |
| RBAC limits on who can create PVs, Pod Security details | Belongs to security hardening | Hour 5 (RBAC / PSS / hardening) |
| Azure Container Storage, Azure NetApp Files, deeper Blob CSI | Time-limited; mentioned only in comparison tables | Microsoft Learn: AKS storage concepts |
| Volumes on Windows nodes | All labs in this hour use Linux nodes | Microsoft Learn: Use Azure Disks with Windows containers |
How to use this course material
Principles · diagrams · animations · commands · labs · production cases · troubleshooting · quiz · voice · video. Read "Principles / Diagrams / Animation" first to build the model, then do the "Lab", and finish with the "Quiz" to check yourself.
A module counts toward progress when you score ≥ 70% on the quiz or click "Mark this module complete". Progress is saved in this browser's localStorage (if storage is disabled, refreshing the page clears it).
The "Voice" tab reads the narration aloud with the browser's built-in Web Speech API (en-US). Systems without an English voice pack will show a prompt; you can give the narration script to any TTS tool.
groupsnapshot.storage.k8s.io/v1); ReadWriteOncePod became GA in v1.29; the StatefulSet PVC retention policy became GA in v1.32; volume populators became GA in v1.33; v1.37 adds a Beta: the PVC Unused condition (feature gate PersistentVolumeClaimUnusedSinceTime). kind's default StorageClass standard is provided by the Rancher local-path-provisioner and does not support expansion or snapshots, so these two topics are demonstrated in kind with csi-driver-host-path, or completed on AKS.Module 0 · Warm-up (complete before class)
- Completed hours 1–3: kind cluster
lab(1 control plane + 2 workers), with namespaceshopcontainingweb(nginx),api(podinfo 6.17.0), anddb(postgres:17 StatefulSet). - Lab machine: Azure VM
Standard_D4s_v5(Ubuntu 24.04, resource grouprg-k8s-lab, regioncanadacentral), or Docker Desktop on your local machine. - Installed: kubectl 1.37, kind v0.33.0, helm 4.x (the MinIO/Velero steps in Module 7 do not depend on Helm), git, jq.
- Optional: Azure CLI signed in with
az login, and a subscription that can create AKS clusters and managed disks.
Step 1: Confirm the cluster and shop's current state
kubectl config use-context kind-lab kubectl get nodes -o wide kubectl -n shop get deploy,sts,svc,pvc kubectl -n shop get pods -o wide
NAME READY UP-TO-DATE AVAILABLE AGE deployment.apps/api 2/2 2 2 2d deployment.apps/web 2/2 2 2 2d NAME READY AGE statefulset.apps/db 1/1 1d NAME TYPE CLUSTER-IP PORT(S) AGE service/api ClusterIP 10.96.31.20 9898/TCP 2d service/db ClusterIP None 5432/TCP 1d service/web ClusterIP 10.96.112.7 80/TCP 2d NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS AGE persistentvolumeclaim/data-db-0 Bound pvc-5d0c2a1e-7b7a-4f3a-9b55-2b1f0e7c9a11 1Gi RWO standard 1d
kubectl create ns shop to continue. The labs in Modules 1–5 do not depend on existing workloads.Step 2: Check StorageClasses and the default SC annotation
kubectl get storageclass kubectl get sc standard -o yaml | grep -E 'is-default-class|provisioner|reclaimPolicy|volumeBindingMode|allowVolumeExpansion' kubectl -n local-path-storage get deploy,cm
NAME PROVISIONER RECLAIMPOLICY VOLUMEBINDINGMODE ALLOWVOLUMEEXPANSION AGE
standard (default) rancher.io/local-path Delete WaitForFirstConsumer false 3d
storageclass.kubernetes.io/is-default-class: "true"
provisioner: rancher.io/local-path
reclaimPolicy: Delete
volumeBindingMode: WaitForFirstConsumer
NAME READY UP-TO-DATE AVAILABLE AGE
deployment.apps/local-path-provisioner 1/1 1 1 3d
NAME DATA AGE
configmap/local-path-config 4 3d
Reading this line:(default) comes from the annotation storageclass.kubernetes.io/is-default-class: "true". A PVC without a storageClassName is automatically filled in with that class by the DefaultStorageClass admission plugin. WaitForFirstConsumer means the PVC stays Pending until a Pod uses it and is scheduled. This is normal, not a fault. ALLOWVOLUMEEXPANSION false means local-path cannot expand volumes.
# The local-path volume's actual directory inside the node container
docker exec lab-worker ls -l /var/local-path-provisioner/ 2>/dev/null || echo "No volumes on this node yet"
kubectl -n local-path-storage get cm local-path-config -o jsonpath='{.data.config\.json}'; echo
Step 3 (optional): Create the AKS cluster aks-lab
The Azure Disk attach, online expansion and incremental snapshots in Modules 3 and 5 are best observed on real cloud disks. The minimal configuration below uses 2 Standard_D2s_v5 nodes, a free-tier control plane, and spreads across 3 availability zones (to observe ZRS and topology).
RG=rg-k8s-lab; LOC=canadacentral; AKS=aks-lab az group create -n $RG -l $LOC # Returns immediately if it already exists az aks get-versions -l $LOC -o table # Confirm 1.37 is available az aks create -g $RG -n $AKS -l $LOC \ --kubernetes-version 1.37 \ --tier free \ --node-count 2 --node-vm-size Standard_D2s_v5 \ --zones 1 2 3 \ --generate-ssh-keys az aks get-credentials -g $RG -n $AKS --context aks-lab kubectl --context aks-lab get sc kubectl --context aks-lab get csidriver
NAME PROVISIONER RECLAIMPOLICY VOLUMEBINDINGMODE ALLOWVOLUMEEXPANSION azurefile-csi file.csi.azure.com Delete Immediate true azurefile-csi-premium file.csi.azure.com Delete Immediate true default (default) disk.csi.azure.com Delete WaitForFirstConsumer true managed-csi disk.csi.azure.com Delete WaitForFirstConsumer true managed-csi-premium disk.csi.azure.com Delete WaitForFirstConsumer true managed-csi-premium-v2 disk.csi.azure.com Delete WaitForFirstConsumer true NAME ATTACHREQUIRED PODINFOONMOUNT STORAGECAPACITY MODES AGE disk.csi.azure.com true false false Persistent 5m file.csi.azure.com false true false Persistent,Ephemeral 5m
default is equivalent to managed-csi (Standard SSD); managed-csi-premium (Premium SSD); managed-csi-premium-v2 (Premium SSD v2, LRS, available from AKS 1.35); azurefile-csi / azurefile-csi-premium; with the Blob driver enabled, there are also azureblob-nfs-premium / azureblob-fuse-premium. Since 1.29, in clusters deployed across multiple availability zones, the built-in Disk SCs use ZRS (except Premium SSD v2). AKS reconciles the built-in SCs, so your changes to them will be overwritten; create a new SC if you need different parameters. Check columns such as ATTACHREQUIRED against the actual output.az aks delete -g rg-k8s-lab -n aks-lab --yes --no-wait. If the whole lab environment is no longer needed, run az group delete -n rg-k8s-lab --yes --no-wait (this also deletes the lab VM). Note that disks for PVs with a Retain reclaim policy, and the Azure snapshots behind VolumeSnapshots, are located in the node resource group MC_rg-k8s-lab_aks-lab_canadacentral, and are deleted along with that node resource group when the cluster is deleted.Step 4: Prepare a working directory for this hour
mkdir -p ~/k8slab/hour4 && cd ~/k8slab/hour4 kubectl config set-context --current --namespace=shop kubectl api-resources --api-group=snapshot.storage.k8s.io # Empty by default on kind; installed in Module 3
Module 1 · Volume basics
- Distinguish volumes that live and die with the Pod (emptyDir, configMap, secret, downwardAPI, projected, image, generic ephemeral volumes) from persistent volumes that exist independently of the Pod (PVC → PV).
- Use emptyDir with
medium: MemoryandsizeLimit, and know that Memory volumes count toward the container's memory limit. - Understand the security risks of hostPath, and why Pod Security Standards (from Baseline up) forbid it.
- Master
readOnly,subPath(and its trap of not updating in place),mountPropagation, andrecursiveReadOnly.
What: What a volume is
A container's root filesystem comes from the image plus a writable layer, and the writable layer is discarded when the container restarts (the kubelet creates a new container). A volume is a Pod-level directory that the kubelet prepares before starting the container, then bind-mounts into the container's mountPath through CRI. On the node, volumes live at /var/lib/kubelet/pods/<pod-uid>/volumes/<plugin>/<name>. A Pod spec has two parts: spec.volumes (where the volume comes from) and containers[].volumeMounts (where it is mounted and whether it is read-only).
Why: Why there are so many volume types
| Category | Volume type | Lifecycle | Typical use |
|---|---|---|---|
| Temporary (Pod-level) | emptyDir (disk, or medium: Memory tmpfs) | Created when the Pod is assigned to a node, deleted when the Pod is removed from the node; not lost when the container crashes and restarts | Cache, sharing files between sidecars, sort scratch space |
ephemeral (generic ephemeral volume) | Automatically creates a PVC for the Pod (named <pod>-<volume-name>, with an ownerReference to the Pod). The PVC is garbage-collected when the Pod is deleted. | Temporary space that needs CSI features (snapshots, capacity tracking, high-performance disks) | |
| Projected (injecting API data) | configMap, secret, downwardAPI, projected (including serviceAccountToken, clusterTrustBundle) | Follows the Pod; content is synced from the API by the kubelet (except subPath mounts) | Config files, certificates, Pod metadata, short-lived tokens |
image (OCI image volume, GA in v1.36) | Follows the Pod; read-only; OCI objects pulled from an image registry | Model files, static assets, plugins, and other data decoupled from the application image | |
| Node-local | hostPath, local PV | Tied to the node; if the Pod moves to another node, it cannot "see" the data | Node agents (logging, CNI, CSI node plugin); local PVs for high-performance local disks |
| Persistent | persistentVolumeClaim | PVC and PV are independent of the Pod; deleting the Pod does not lose data | Databases, message queues, user uploads |
How: Several details you must master
- emptyDir sizeLimit: the kubelet measures usage periodically, and once the limit is exceeded it evicts the Pod (writes do not fail with an error). With
medium: Memory, data lives in tmpfs and is lost on node reboot, and it counts toward the container's memory limit (cgroup), which can cause OOM kills. - configMap/secret updates: the kubelet refreshes files through an atomic symlink (
..data→ timestamped directory). The delay is roughly the kubelet sync period plus the cache TTL. Volumes mounted with subPath are not updated.immutable: trueConfigMaps/Secrets are never updated, but they reduce load on the apiserver. - projected: merges multiple sources into one directory (for example serviceAccountToken + configMap + downwardAPI). Commonly used for tokens with an audience and an expiry time.
- readOnly and recursiveReadOnly:
readOnly: truemakes only the top-level mount read-only. If there are sub-mounts under the volume, userecursiveReadOnly: Enabled(GA in v1.33, requires runtime support) to make the whole subtree read-only. - subPath / subPathExpr: mounts a sub-path of a volume into the container. Suited to putting one file into an existing directory, or using
$(POD_NAME)to create per-Pod directories. - mountPropagation:
None(default, rprivate),HostToContainer(rslave),Bidirectional(rshared, privileged containers only). The CSI node plugin needs Bidirectional so that the volumes it mounts can propagate back to the host for the kubelet to use. - image volume:
volumes[].image.reference+pullPolicy; read-only, noexec; subPath supported since v1.33; requires container runtime support (containerd 2.1+ / CRI-O).
When: How to choose
- If the data can be regenerated when lost → emptyDir (for many small files, prefer disk-backed; use Memory only when you need extreme latency and the capacity is very small).
- Temporary but needs large capacity, high performance or snapshots → generic ephemeral volume.
- Config and secrets → configMap / secret (or projected); large files or binary models → image volume.
- Data must survive Pod deletion and rescheduling → PVC (from Module 2 on).
- hostPath → only for trusted system components; business Pods never use it.
Comparison with the Docker course
| Docker | Kubernetes equivalent | Difference |
|---|---|---|
| Named volume | PVC + PV | K8s creates cloud disks dynamically through a StorageClass, and they can be re-attached across nodes |
| bind mount | hostPath | In K8s it is bound to a node and carries high security risk; PSS Baseline forbids it |
| tmpfs | emptyDir medium: Memory | In K8s it counts toward Pod memory, and it survives container restarts (the Pod still exists) |
Anonymous volume + --rm | emptyDir / generic ephemeral volume | Lifecycle is bound to the Pod, not the container |
Architecture diagram: where the volumes of one Pod sit on the node
Flow diagram: where volume data goes under three events
Interactive simulator: where data goes during container restart / Pod deletion / node failure
Choose a volume type first, then click the events in order. The log below shows the real behavior of the kubelet and controllers, plus commands you can use to verify it. Inspired by the storage simulator in Docker course Module 6, but adapted to K8s's three failure granularities.
Core commands and fields
| Command / field | Purpose | Key parameters / notes |
|---|---|---|
kubectl explain pod.spec.volumes --recursive | less | View all volume types and fields | Works offline; fields depend on the cluster version |
kubectl explain pod.spec.containers.volumeMounts | View mount fields | readOnly, recursiveReadOnly, subPath, subPathExpr, mountPropagation |
kubectl describe pod P | The Volumes section shows volume types and sources; Events show mount errors | Watch for FailedMount and Evicted |
kubectl exec P -c C -- df -h /cache | View volume capacity and filesystem | Memory volumes show tmpfs |
kubectl get pod P -o jsonpath='{.status.containerStatuses[*].restartCount}' | Check whether the container has restarted | Verify that emptyDir survives container restarts |
docker exec lab-worker ls /var/lib/kubelet/pods/UID/volumes | View the volume directory on the node in kind | UID: kubectl get pod P -o jsonpath='{.metadata.uid}' |
Example: one Pod using all six volume types
apiVersion: v1
kind: ConfigMap
metadata: { name: demo-conf, namespace: shop }
data:
app.conf: |
greeting=hello-from-configmap
---
apiVersion: v1
kind: Pod
metadata:
name: vol-demo
namespace: shop
labels: { app: vol-demo, tier: lab }
spec:
containers:
- name: app
image: busybox:1.37
# Creating /tmp/crash (in the container's writable layer) makes the container exit with code 1, which simulates a crash
command: ["sh","-c","while [ ! -f /tmp/crash ]; do date >> /cache/ticks; sleep 5; done; exit 1"]
resources:
limits: { memory: 128Mi }
volumeMounts:
- { name: cache, mountPath: /cache }
- { name: fast, mountPath: /fast }
- { name: conf, mountPath: /etc/app, readOnly: true }
- { name: conf, mountPath: /etc/single.conf, subPath: app.conf } # Not hot-updated
- { name: podinfo, mountPath: /podinfo }
- { name: scratch, mountPath: /scratch }
volumes:
- name: cache
emptyDir: { sizeLimit: 200Mi }
- name: fast
emptyDir: { medium: Memory, sizeLimit: 32Mi } # Counts toward the container memory limit
- name: conf
configMap: { name: demo-conf }
- name: podinfo
downwardAPI:
items:
- path: labels
fieldRef: { fieldPath: metadata.labels }
- path: mem_limit
resourceFieldRef: { containerName: app, resource: limits.memory, divisor: 1Mi }
- name: scratch
ephemeral:
volumeClaimTemplate:
metadata: { labels: { type: scratch } }
spec:
accessModes: ["ReadWriteOnce"]
storageClassName: standard
resources: { requests: { storage: 1Gi } }
kubectl apply -f vol-demo.yaml kubectl -n shop wait --for=condition=Ready pod/vol-demo --timeout=90s kubectl -n shop exec vol-demo -- sh -c 'df -h /cache /fast /scratch | cat; cat /podinfo/mem_limit; cat /etc/app/app.conf' kubectl -n shop get pvc -l type=scratch
Filesystem Size Used Available Use% Mounted on /dev/sda1 58.4G 12.1G 43.3G 22% /cache tmpfs 32.0M 0 32.0M 0% /fast /dev/sda1 58.4G 12.1G 43.3G 22% /scratch 128 greeting=hello-from-configmap NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS AGE vol-demo-scratch Bound pvc-0b6e… 1Gi RWO standard 20s
How to verify:emptyDir's sizeLimit does not show up in df (a disk-backed volume shows the whole node disk). Instead, the kubelet measures usage and evicts. A Memory volume shows the tmpfs size. The PVC generated by a generic ephemeral volume is always named <pod>-<volume-name>. Common mistake:when a downwardAPI resourceFieldRef references a resource with no limit set, it returns the node's allocatable value. Production use:inject the Pod name, namespace and resource limits so that JVM and Go runtimes can auto-tune themselves.
hostPath and Pod Security
# After the shop namespace enforces baseline, hostPath Pods are rejected (covered in detail in hour 5)
kubectl label ns shop pod-security.kubernetes.io/enforce=baseline --overwrite --dry-run=server -o name
kubectl -n shop run hp --image=busybox:1.37 --dry-run=server -o yaml \
--overrides='{"spec":{"volumes":[{"name":"h","hostPath":{"path":"/etc"}}],"containers":[{"name":"hp","image":"busybox:1.37","volumeMounts":[{"name":"h","mountPath":"/host-etc"}]}]}}'
Error from server (Forbidden): pods "hp" is forbidden: violates PodSecurity "baseline:latest": hostPath volumes (volume "h")
image volume (GA in v1.36)
apiVersion: v1
kind: Pod
metadata: { name: imgvol, namespace: shop }
spec:
containers:
- name: shell
image: busybox:1.37
command: ["sleep","3600"]
volumeMounts:
- { name: assets, mountPath: /assets }
volumes:
- name: assets
image:
reference: quay.io/crio/artifact:v2 # Example OCI object from the official docs
pullPolicy: IfNotPresent
If the Pod is stuck in ContainerCreating with events like "image volume not supported", the runtime version does not support it. kind v0.33.0 nodes use containerd 2.x, which generally works. Check the actual events.
Lab 1: See the lifecycles of the three volume types for yourself (about 5 min, kind)
vol-demo.yaml from the "Commands" tab.
cd ~/k8slab/hour4 kubectl apply -f vol-demo.yaml && kubectl -n shop wait --for=condition=Ready pod/vol-demo --timeout=90s kubectl -n shop exec vol-demo -- sh -c 'echo important > /cache/a; echo fast > /fast/b; echo eph > /scratch/c'
kill 1 inside the container usually does nothing, because PID 1 ignores signals that have no registered handler.
kubectl -n shop exec vol-demo -- touch /tmp/crash
sleep 12; kubectl -n shop get pod vol-demo -o jsonpath='{.status.containerStatuses[0].restartCount}{"\n"}'
kubectl -n shop exec vol-demo -- sh -c 'cat /cache/a /fast/b /scratch/c'
1 important fast eph
All three volumes are kept, because they belong to the Pod, not the container. The Memory volume is also kept, because its tmpfs mount point is at the Pod level.
NODE=$(kubectl -n shop get pod vol-demo -o jsonpath='{.spec.nodeName}')
UID_=$(kubectl -n shop get pod vol-demo -o jsonpath='{.metadata.uid}')
docker exec $NODE ls /var/lib/kubelet/pods/$UID_/volumes/
docker exec $NODE cat /var/lib/kubelet/pods/$UID_/volumes/kubernetes.io~empty-dir/cache/a
docker exec $NODE sh -c 'ls /var/local-path-provisioner/ | grep scratch'
kubernetes.io~configmap kubernetes.io~downward-api kubernetes.io~empty-dir kubernetes.io~projected important pvc-0b6e…_shop_vol-demo-scratch
The generic ephemeral volume is provisioned by local-path (which creates a hostPath-type PV), so its data lives under /var/local-path-provisioner on the node, not in the Pod's volumes directory. kubernetes.io~projected is the automatically injected ServiceAccount token. The /tmp/crash file in the old container's writable layer disappeared with that container, so the new container can keep running.
kubectl -n shop delete pod vol-demo --wait kubectl -n shop get pvc vol-demo-scratch 2>&1 | tail -1 # The generic ephemeral volume's PVC is garbage-collected kubectl apply -f vol-demo.yaml && kubectl -n shop wait --for=condition=Ready pod/vol-demo --timeout=90s kubectl -n shop exec vol-demo -- sh -c 'ls /cache /fast /scratch'
Error from server (NotFound): persistentvolumeclaims "vol-demo-scratch" not found /cache: ticks /fast: /scratch:
The emptyDir, Memory and generic ephemeral volumes are all new (only the newly written ticks are present). Persistent data needs a PVC, which is the topic of the next module.
kubectl -n shop exec vol-demo -- sh -c 'dd if=/dev/zero of=/cache/big bs=1M count=260' kubectl -n shop get pod vol-demo -w # After about 10–60 seconds it changes to Error / Evicted (bare Pod) kubectl -n shop describe pod vol-demo | grep -A2 -i evict
Status: Failed Reason: Evicted Message: Usage of EmptyDir volume "cache" exceeds the limit "200Mi".
kubectl -n shop delete pod vol-demo imgvol --ignore-not-found kubectl -n shop delete cm demo-conf
Case 1: Distributing model files for an ML inference service
Problem:An 8 GB model is baked into the application image, so every code change means pushing and pulling the whole image, and node disks fill up with multiple image versions.
Approach:Package the model separately as an OCI artifact and push it to ACR. The Pod mounts it read-only through an image volume, so the application image is only a few hundred MB. To roll out a new model, change only the digest in reference.
volumes:
- name: model
image:
reference: myacr.azurecr.io/models/sentiment@sha256:4b1c… # Pin with a digest
pullPolicy: IfNotPresent
Limits:Read-only; requires node runtime support; the first pull still sits on the startup path (you can combine it with a pre-pulling DaemonSet). Pulling from a private registry uses the Pod's imagePullSecrets or the node kubelet credentials (on AKS, the kubelet identity with ACR attached).
Case 2: Sidecar log collection and emptyDir filling the disk
Problem:A legacy application can only write file logs, and a sidecar (Fluent Bit) reads the emptyDir and forwards them. A downstream failure made logs pile up, the node hit DiskPressure, and other Pods on the same node were evicted.
Approach:Set sizeLimit: 2Gi on the emptyDir, set resources.limits.ephemeral-storage on the container, and rotate logs on the application side. When the limit is exceeded, only this Pod is evicted instead of dragging down the whole node.
resources:
requests: { ephemeral-storage: 1Gi }
limits: { ephemeral-storage: 3Gi }
volumes:
- name: logs
emptyDir: { sizeLimit: 2Gi }
Limits:Eviction is detected after the fact (the kubelet measures periodically), so a short burst of writes can still fill the node disk first. AKS recommends Ephemeral OS disks and leaving enough headroom.
Case 3: Certificate hot rotation runs into subPath
Problem:cert-manager has updated the Secret, but nginx keeps using the old certificate until an expiry alert fires. The cause is mounting with subPath: tls.crt at /etc/nginx/certs/tls.crt.
Approach:Mount the whole directory /etc/nginx/certs instead (no subPath), and reload nginx (a sidecar detects changes to ..data and sends HUP), or use a Reloader-style controller that does a rolling restart when the Secret changes.
Common errors and fixes
MountVolume.SetUp failed for volume "conf" : configmap "demo-conf" not found
Cause:The ConfigMap or Secret referenced by the Pod does not exist (misspelled name, wrong namespace, or a creation-order problem). The Pod stays in ContainerCreating, and the kubelet keeps retrying.
kubectl -n shop describe pod POD | sed -n '/Events/,$p' kubectl -n shop get cm,secret | grep demo
Fix:Creating the missing object recovers automatically. If the configuration is optional, use configMap: {name: x, optional: true}.
The node was low on resource: ephemeral-storage. / Usage of EmptyDir volume "cache" exceeds the limit "200Mi".
Cause:The emptyDir exceeds its sizeLimit, or the container's writable layer plus logs plus emptyDir exceed limits.ephemeral-storage, or the whole node is under DiskPressure.
kubectl get pods -A --field-selector=status.phase=Failed | grep -i evict
kubectl describe node NODE | grep -A5 Conditions
kubectl get --raw "/api/v1/nodes/NODE/proxy/stats/summary" | jq '.pods[] | {pod:.podRef.name, eph:.["ephemeral-storage"].usedBytes}' | head -40
Fix:Confirm whether the data should be on a PVC. Adjust sizeLimit or ephemeral-storage. Clean up evicted Failed Pods: kubectl delete pods -A --field-selector=status.phase=Failed.
container has runAsNonRoot ... / open /data/x: permission denied (emptyDir or hostPath)
Cause:The hostPath directory is owned by root, and the container runs as non-root. emptyDir defaults to 777, so this usually does not happen there, but hostPath and some CSI volumes can hit it.
Fix:For CSI and block volumes, use securityContext.fsGroup (Modules 6 and 8). hostPath does not support fsGroup to change permissions, so the directory must be prepared on the node in advance. This is one reason business workloads should not use hostPath.
OOMKilled, but the application's own memory usage is not high
Cause:Data written to emptyDir.medium: Memory counts toward the memory usage of the container's cgroup.
kubectl -n shop exec POD -- du -sh /fast
kubectl -n shop get pod POD -o jsonpath='{.status.containerStatuses[0].lastState.terminated.reason}'
Fix:Set a small sizeLimit on the Memory volume and raise the memory limit to match. For large data, use a disk-backed emptyDir instead.
1. Write a command that shows the restart count and the last termination reason of the first container in Pod vol-demo.
kubectl -n shop get pod vol-demo -o jsonpath='{.status.containerStatuses[0].restartCount} {.status.containerStatuses[0].lastState.terminated.reason}{"\n"}'2. Without writing YAML, how can you quickly check which fields emptyDir supports?
kubectl explain pod.spec.volumes.emptyDir
The output includes medium and sizeLimit.
A reporting service writes 3 GB of intermediate results to an emptyDir. Every time a node is drained for upgrade, the job starts again from the beginning. How would you improve this?
Drain evicts Pods, and an emptyDir is deleted along with its Pod. Options: ① If the intermediate results must survive across Pods, use a PVC instead (a StatefulSet, or a Job plus PVC), so the same volume is reattached after rescheduling. ② If you only need a large temporary disk, a generic ephemeral volume works, but it is still deleted with the Pod. ③ Implement checkpointing at the application layer and store checkpoints in object storage. ④ Set a PodDisruptionBudget to limit how many Pods are evicted at once. The key is to first decide whether the data can be rebuilt if lost, and how costly the rebuild would be.
Verified teaching videos
Official docs
Video storyboard (for a video generation tool)
This course material cannot generate video or MP3 files directly, so storyboards and narration scripts are provided.
Narration:When a container restarts, the writable layer in its image is discarded. So where does the data go? The answer is volumes, and the lifecycle of a volume decides the data's fate.
Narration:An emptyDir belongs to the Pod, so it survives container crashes and restarts. But when the Pod is deleted or evicted, it disappears too.
Narration:The kubelet refreshes ConfigMaps and Secrets automatically, but files mounted with subPath are not refreshed.
Narration:hostPath exposes the node's filesystem directly, so business workloads should not use it.
Narration:To carry data across Pods and nodes, you need persistent volumes. That is the star of the next module.
Module 2 · PV · PVC · StorageClass
- Distinguish PV (a cluster-scoped resource that represents a real piece of storage) from PVC (a namespace-scoped "request"), and understand the 1:1 binding and
claimRef. - Master static and dynamic provisioning, and read the StorageClass fields
provisioner / parameters / reclaimPolicy / allowVolumeExpansion / volumeBindingMode / allowedTopologies. - Draw the full sequence "PVC → scheduling → provision → bind → attach → mount" under WaitForFirstConsumer, and know which component performs each step.
- Remember the PVC phases (Pending/Bound/Lost) and PV phases (Available/Bound/Released/Failed), and use the v1.37 Beta
Unusedcondition to find idle PVCs.
What: The division of labor among the three objects
| Object | Scope | Who creates it | Analogy | Key fields |
|---|---|---|---|---|
| StorageClass (storage.k8s.io/v1) | Cluster | Platform admin / AKS built-in | "Storage tier" | provisioner, parameters, reclaimPolicy, volumeBindingMode, allowVolumeExpansion, mountOptions, allowedTopologies |
| PersistentVolumeClaim (v1) | Namespace | Application developer / StatefulSet template | "Request form" | accessModes, resources.requests.storage, storageClassName, volumeName, dataSource(Ref), volumeMode |
| PersistentVolume (v1) | Cluster | Admin (static) or provisioner (dynamic) | "A real disk" | capacity, csi.driver / volumeHandle, claimRef, persistentVolumeReclaimPolicy, nodeAffinity |
Why: Why it is split into PVC and PV
It decouples "what you need" (capacity, access mode, performance tier) from "how it is provided" (which cloud, which disk ID). The developer's manifest can be reused on kind, AKS and EKS, with only the StorageClass differing. The platform team uses SCs to control cost, encryption and backup labels centrally.
How: The real binding and provisioning flow
- PVC creation: the
DefaultStorageClassadmission plugin fills in the default SC for a PVC that does not specifystorageClassName. Explicitly writingstorageClassName: ""means dynamic provisioning is forbidden, and the PVC binds only to a static PV. - PV controller (persistentvolume-binder in kube-controller-manager) watches for the new PVC and first looks for a matching Available PV (SC, access modes, capacity ≥ request, selector, volumeMode).
- If none is found and the SC is
Immediate: the controller adds the annotationvolume.kubernetes.io/storage-provisionerto the PVC, handing it to the external provisioner to create the volume right away. - If the SC is
WaitForFirstConsumer, the PVC stays Pending (eventWaitForFirstConsumer) until a Pod references it. After the scheduler's VolumeBinding plugin picks a node for the Pod, it writes the annotationvolume.kubernetes.io/selected-nodeon the PVC. - external-provisioner (a CSI sidecar, or a non-CSI provisioner such as local-path) sees the annotation, calls the storage backend to create the volume, and creates the PV (with
nodeAffinitytopology). The PV controller binds the PV and PVC in both directions (PV.spec.claimRef ↔ PVC.spec.volumeName), and both become Bound. - The scheduler completes the Pod bind. For drivers that need attach, the AD controller creates a VolumeAttachment and external-attacher performs the attach. The kubelet then mounts the volume into the Pod directory (detailed in Module 3).
Phase quick reference
Pending: not yet bound (waiting for WFFC, no matching PV, or provisioning failed)Bound: bound to a PVLost: the bound PV no longer exists (data may be lost)
Available: free, can be boundBound: bound to a PVCReleased: the PVC has been deleted but the resource has not been reclaimed yet (with Retain, it stays here)Failed: automatic reclamation failed
status.lastPhaseTransitionTime has been stable since v1.31.v1.37 Beta: the PVC Unused condition
Maintained by the PVC protection controller, behind the feature gate PersistentVolumeClaimUnusedSinceTime (v1.37 Beta, enabled by default). When no non-terminated Pod references the PVC: type: Unused, status: "True", reason: NoPodsUsingPVC. When a Pod is using it: status: "False", reason: PodUsingPVC. lastTransitionTime shows when the PVC became idle, which you can use to clean up cloud disks that have sat unused for a long time and save cost.
When: Static or dynamic
- Dynamic (default choice): the vast majority of cases; parameters are unified through the SC.
- Static: adopting existing cloud disks (migration, manual restore from a snapshot), NFS exports, local PVs. The PVC uses
volumeNameto pin a specific PV, and setsstorageClassNameto match the PV (or both are "").
Comparison with similar technologies
| Concept | Kubernetes | Docker / Compose | AWS ECS / VM world |
|---|---|---|---|
| Requesting storage | PVC | Named volume in volumes: | EBS volume configuration in the task definition |
| Storage tier | StorageClass | volume driver + driver_opts | EBS volume types gp3/io2 |
| Real storage | PV | /var/lib/docker/volumes/x | One EBS volume / Azure managed disk |
Architecture diagram: control-plane components involved in storage
Flow diagram: WaitForFirstConsumer dynamic provisioning sequence
Step-by-step animation: PVC created → WaitForFirstConsumer → scheduling → provision → bind → attach → mount
Uses managed-csi (Azure Disk) on AKS as the example. The highlighted element is the component currently working; the terminal shows the corresponding API object changes or CSI calls.
Core commands
| Command | Purpose | Key parameters / notes |
|---|---|---|
kubectl get sc | List StorageClasses and the default SC | Default SC marked with the suffix (default) |
kubectl get pvc -A -o wide | View PVC status, bound PV, capacity, VOLUMEMODE | -w to watch status changes |
kubectl get pv --sort-by=.spec.capacity.storage | View PVs with CLAIM, RECLAIM POLICY, STATUS | PVs in Released state must be handled manually |
kubectl describe pvc NAME | Check events: WaitForFirstConsumer, ProvisioningFailed, ExternalProvisioning | First troubleshooting command |
kubectl patch sc NAME -p '{"metadata":{"annotations":{"storageclass.kubernetes.io/is-default-class":"false"}}}' | Remove the default SC | When multiple default SCs exist in the cluster, a new PVC uses the most recently created one (with a warning). Avoid this. |
kubectl get pvc NAME -o jsonpath='{.status.conditions[?(@.type=="Unused")]}' | v1.37 Beta: check whether a PVC is idle, and since when | Requires the feature gate to be enabled (Beta, on by default) |
Dynamic provisioning: minimal PVC + Pod
apiVersion: v1
kind: PersistentVolumeClaim
metadata: { name: demo-data, namespace: shop }
spec:
accessModes: ["ReadWriteOnce"]
# storageClassName omitted → DefaultStorageClass admission fills in standard
resources:
requests: { storage: 1Gi }
---
apiVersion: v1
kind: Pod
metadata: { name: demo-writer, namespace: shop }
spec:
containers:
- name: w
image: busybox:1.37
command: ["sh","-c","echo written-at-$(date +%s) >> /data/log; sleep 3600"]
volumeMounts: [{ name: data, mountPath: /data }]
volumes:
- name: data
persistentVolumeClaim: { claimName: demo-data }
kubectl -n shop apply -f pvc-demo.yaml
kubectl -n shop get pvc demo-data -o jsonpath='{.spec.storageClassName}{"\n"}' # The admission plugin has filled in standard
kubectl -n shop get pvc demo-data -w
NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS AGE demo-data Pending standard 1s demo-data Pending standard 2s demo-data Bound pvc-9a1f2c3d-… 1Gi RWO standard 5s
kubectl -n shop describe pvc demo-data | sed -n '/Events/,$p'
kubectl get pv $(kubectl -n shop get pvc demo-data -o jsonpath='{.spec.volumeName}') -o yaml | grep -A8 -E 'claimRef|nodeAffinity|hostPath'
Events:
Type Reason From Message
Normal WaitForFirstConsumer persistentvolume-controller waiting for first consumer to be created before binding
Normal ExternalProvisioning persistentvolume-controller Waiting for a volume to be created either by the external provisioner 'rancher.io/local-path' or manually by the system administrator…
Normal Provisioning rancher.io/local-path_local-path-provisioner-… External provisioner is provisioning volume for claim "shop/demo-data"
Normal ProvisioningSucceeded rancher.io/local-path_local-path-provisioner-… Successfully provisioned volume pvc-9a1f2c3d-…
claimRef:
name: demo-data
namespace: shop
hostPath:
path: /var/local-path-provisioner/pvc-9a1f2c3d-…_shop_demo-data
nodeAffinity:
required:
nodeSelectorTerms:
- matchExpressions:
- key: kubernetes.io/hostname
operator: In
values: [lab-worker2]
How to verify:The PV's nodeAffinity pins this "disk" to lab-worker2. Any Pod that uses this PVC from now on can only be scheduled to that node (an inherent limitation of local-path). Common mistake:omitting storageClassName in a cluster without a default SC leaves the PVC Pending forever, with no provisioner events. Production use:the platform defines 2–4 SCs (standard, high-performance, retain, shared file) and prohibits business teams from creating their own SCs.
Static provisioning: manually create a PV and bind it precisely
apiVersion: v1
kind: PersistentVolume
metadata: { name: pv-static-demo, labels: { purpose: static-demo } }
spec:
capacity: { storage: 2Gi }
accessModes: ["ReadWriteOnce"]
persistentVolumeReclaimPolicy: Retain
storageClassName: "" # Matches the PVC, and does not trigger dynamic provisioning
local:
path: /mnt/static-demo
nodeAffinity: # A local PV must specify a node
required:
nodeSelectorTerms:
- matchExpressions:
- { key: kubernetes.io/hostname, operator: In, values: ["lab-worker"] }
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata: { name: static-claim, namespace: shop }
spec:
accessModes: ["ReadWriteOnce"]
storageClassName: ""
volumeName: pv-static-demo # Precise match
resources: { requests: { storage: 2Gi } }
docker exec lab-worker mkdir -p /mnt/static-demo kubectl apply -f static-pv.yaml kubectl get pv pv-static-demo; kubectl -n shop get pvc static-claim
NAME CAPACITY ACCESS MODES RECLAIM POLICY STATUS CLAIM STORAGECLASS AGE pv-static-demo 2Gi RWO Retain Bound shop/static-claim 3s NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS AGE static-claim Bound pv-static-demo 2Gi RWO 3s
StorageClass field overview (define a Retain-type SC in kind)
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
name: local-retain
provisioner: rancher.io/local-path
reclaimPolicy: Retain # Default is Delete
volumeBindingMode: WaitForFirstConsumer # Always use for local or multi-zone storage
allowVolumeExpansion: false # local-path does not support expansion
# parameters: {} # Defined by each provisioner, e.g. skuName for Azure Disk
Lab 2: Dynamic + static provisioning and the Unused condition (about 6 min, kind)
cd ~/k8slab/hour4
cat > pvc-only.yaml <<'EOF'
apiVersion: v1
kind: PersistentVolumeClaim
metadata: { name: lonely, namespace: shop }
spec:
accessModes: ["ReadWriteOnce"]
resources: { requests: { storage: 1Gi } }
EOF
kubectl apply -f pvc-only.yaml
sleep 5; kubectl -n shop get pvc lonely; kubectl -n shop describe pvc lonely | tail -3
NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS AGE lonely Pending standard 5s Normal WaitForFirstConsumer 3s (x2 over 5s) persistentvolume-controller waiting for first consumer to be created before binding
pvc-demo.yaml from the "Commands" tab, and watch events at the same time.
kubectl -n shop get events --watch-only --field-selector involvedObject.name=demo-data &
kubectl -n shop apply -f pvc-demo.yaml
kubectl -n shop wait --for=condition=Ready pod/demo-writer --timeout=90s; kill %1
kubectl -n shop get pvc demo-data -o jsonpath='{.metadata.annotations}' | jq .
{
"pv.kubernetes.io/bind-completed": "yes",
"pv.kubernetes.io/bound-by-controller": "yes",
"volume.beta.kubernetes.io/storage-provisioner": "rancher.io/local-path",
"volume.kubernetes.io/selected-node": "lab-worker2",
"volume.kubernetes.io/storage-provisioner": "rancher.io/local-path"
}
Each annotation is a trace of a component handoff: selected-node is written by the scheduler, storage-provisioner is written by the PV controller, and bind-completed is written by the PV controller after binding.
kubectl -n shop delete pod demo-writer kubectl -n shop apply -f pvc-demo.yaml && kubectl -n shop wait --for=condition=Ready pod/demo-writer --timeout=60s kubectl -n shop exec demo-writer -- cat /data/log
written-at-1763190001 written-at-1763190077
kubectl -n shop delete pod demo-writer
sleep 5
kubectl -n shop get pvc demo-data -o jsonpath='{range .status.conditions[*]}{.type}={.status} {.reason} since {.lastTransitionTime}{"\n"}{end}'
Unused=True NoPodsUsingPVC since 2026-11-15T03:12:41Z
If there is no output, the cluster has not enabled this beta feature (PersistentVolumeClaimUnusedSinceTime), or the version is earlier than 1.37. See the official blog post dated 2026-09-21.
static-pv.yaml, then delete the PVC and watch the PV change to Released.
docker exec lab-worker mkdir -p /mnt/static-demo kubectl apply -f static-pv.yaml kubectl -n shop delete pvc static-claim kubectl get pv pv-static-demo
NAME CAPACITY ACCESS MODES RECLAIM POLICY STATUS CLAIM STORAGECLASS AGE pv-static-demo 2Gi RWO Retain Released shop/static-claim 1m
A Released PV still keeps its claimRef, so a new PVC cannot bind to it. Module 8 shows you how to safely make it available again.
kubectl -n shop delete pvc lonely demo-data --ignore-not-found kubectl delete pv pv-static-demo docker exec lab-worker rm -rf /mnt/static-demo
Case 1: PVC created in the wrong zone on a multi-zone AKS cluster
Problem: A team created their own Premium_LRS SC with volumeBindingMode: Immediate. The disk was created in zone 1 when the PVC was created, but the Pod could only be scheduled to zone 2 or 3 because of insufficient CPU. It reported volume node affinity conflict and stayed Pending.
Fix: Use WaitForFirstConsumer for all LRS disks. The scheduler picks a node first, and then the disk is created in that node's zone. Alternatively, use a ZRS SKU (the built-in SC on multi-zone AKS clusters with 1.29+ defaults to ZRS).
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata: { name: premium-lrs-wffc }
provisioner: disk.csi.azure.com
parameters: { skuName: Premium_LRS }
reclaimPolicy: Delete
volumeBindingMode: WaitForFirstConsumer
allowVolumeExpansion: true
Limitation: WFFC cannot be combined with pre-binding through the PVC's volumeName for dynamic provisioning. An LRS disk created in the wrong zone can only be recreated in the target zone from a snapshot.
Case 2: Reclaim idle cloud disks using the Unused condition
Problem: A dev cluster has hundreds of PVCs. Many were left behind after their workloads were deleted (StatefulSets keep their PVCs by default), and they add a significant monthly managed disk cost.
Fix: Run the jq query from the official blog post in a weekly CronJob. It lists PVCs with Unused=True for more than 30 days. The job labels them and notifies the owners first. A person then confirms the deletion.
kubectl get pvc -A -o json | jq -r '
.items[] | select(.status.conditions[]? | select(.type=="Unused" and .status=="True"))
| select((.status.conditions[] | select(.type=="Unused") | .lastTransitionTime) as $t
| (now - ($t | fromdateiso8601)) > (30*86400))
| "\(.metadata.namespace)/\(.metadata.name)"'
Limitation: This is a beta feature. The condition only shows that no Pod references the PVC. It does not mean the data is useless (for example, cold data kept for backups).
Case 3: Centralized StorageClass governance for the platform
The platform team offers only four SCs: standard (default, Delete), standard-retain (production databases, Retain), fast (Premium SSD v2), and shared (Azure Files). Azure Policy or ValidatingAdmissionPolicy blocks business namespaces from using other SCs or creating PVs. A ResourceQuota on <sc>.storageclass.storage.k8s.io/requests.storage caps the total storage each team can use in each tier.
Common errors and fixes
no persistent volumes available for this claim and no storage class is set
Cause: The cluster has no default SC, and the PVC does not set storageClassName. Or the PVC sets storageClassName: "" but no matching static PV exists.
kubectl get sc
kubectl -n shop get pvc NAME -o jsonpath='{.spec.storageClassName}{"\n"}'
Fix: Set the default SC annotation, or set the SC explicitly in the PVC. Note: the PVC's storageClassName cannot be changed after creation (a nil value that was never set can be backfilled). You must delete and recreate the PVC.
failed to provision volume with StorageClass "managed-csi": rpc error: code = ...
Cause: The provisioner's call to the backend failed. Possible reasons: cloud quota is insufficient, the SKU is not available in that region or zone (for example, Premium SSD v2), the managed identity lacks permissions, or a parameter is misspelled.
kubectl -n shop describe pvc NAME | sed -n '/Events/,$p' kubectl -n kube-system logs deploy/csi-azuredisk-controller -c csi-provisioner --tail=50 # on AKS, use the actual container name az vm list-usage -l canadacentral -o table | grep -i disk
Fix: Resolve the quota, SKU, or permission issue named in the error. After you correct the SC, you must recreate the PVC.
waiting for first consumer to be created before binding (lasts a long time)
Cause: This is a normal event for WFFC. It is a problem only when a Pod already uses the PVC and that Pod is also Pending. In that case, check the Pod's scheduling events.
kubectl -n shop get pods -o wide | grep Pending kubectl -n shop describe pod POD | sed -n '/Events/,$p'
Common scheduling failure causes: node(s) had volume node affinity conflict (the disk is on another node or zone), node(s) exceed max volume count, or insufficient resources.
persistentvolumeclaim "x" is being deleted (stuck in Terminating)
Cause: The finalizer kubernetes.io/pvc-protection is set. A Pod still uses the PVC, in any state other than Completed.
kubectl -n shop get pods -o json | jq -r '.items[] | select(.spec.volumes[]?.persistentVolumeClaim.claimName=="x") | .metadata.name'
Fix: Delete the Pod that uses it (or scale down the workload), and the finalizer is removed automatically. Do not remove the finalizer by hand (see Module 8 for details).
1. Use one command to list every PVC in every namespace that is Pending, along with its StorageClass.
kubectl get pvc -A -o custom-columns=NS:.metadata.namespace,NAME:.metadata.name,PHASE:.status.phase,SC:.spec.storageClassName | awk 'NR==1 || $3=="Pending"'
2. Remove the default setting from standard, and set local-retain as the default.
kubectl patch sc standard -p '{"metadata":{"annotations":{"storageclass.kubernetes.io/is-default-class":"false"}}}'
kubectl patch sc local-retain -p '{"metadata":{"annotations":{"storageclass.kubernetes.io/is-default-class":"true"}}}'
kubectl get scA developer reports: "The same Helm chart gets a PVC that binds immediately on kind, but on AKS the PVC stays Pending and the Pod is never created." What could be the cause?
The built-in AKS Disk SC is WaitForFirstConsumer, so the PVC waits until a Pod needs it. But "the Pod is never created" points to an upstream problem. For example, an admission policy rejects the Job or Deployment, the Helm hook order creates the PVC first and waits for a Pod that is created later, or the replica count is 0. To investigate, run kubectl describe pvc (seeing WaitForFirstConsumer is normal), kubectl get events to find out why the controller failed to create the Pod, and helm get hooks. The claim that the PVC bound immediately on kind is also doubtful. The default SC on kind is also WFFC, so a Pod may already have been running at that time.
Verified teaching videos
Official documentation
- Persistent Volumes
- Storage Classes
- Dynamic Volume Provisioning
- v1.37: Tracking When a PVC Was Last Used (2026-09-21)
- AKS storage concepts
Video storyboard script
This lesson cannot directly generate the video or MP3. The storyboard and narration script are provided instead.
Narration: A PVC is the request slip. A StorageClass is the plan. The PV is the actual disk.
Narration: In WaitForFirstConsumer mode, Pending is normal when no Pod is using the PVC.
Narration: Pick the node first, then create the disk. This keeps the disk and the Pod in the same zone.
Narration: Binding is one-to-one. The PV records claimRef, and the PVC records volumeName.
Narration: This beta feature in v1.37 shows when the PVC became idle.
Module 3 · CSI Architecture and Azure Disks
- Name the three gRPC service groups in CSI (Identity, Controller, and Node). Also name the Kubernetes-side sidecars: external-provisioner, external-attacher, external-resizer, external-snapshotter, node-driver-registrar, and livenessprobe.
- Explain the role of the three storage.k8s.io/v1 objects: CSIDriver, CSINode, and VolumeAttachment. Use them to troubleshoot attach problems and node volume limits.
- Tell apart Azure Disk CSI and Azure Files CSI (block vs. file, RWO vs. RWX, and whether attach is required). Understand Premium SSD v2, ZRS, and the built-in AKS SCs.
- On kind, install the snapshot CRDs, snapshot-controller, and csi-driver-host-path to prepare for Module 5.
What: What CSI is
Container Storage Interface is a gRPC specification between a container orchestrator and a storage system. A storage vendor implements a CSI driver, usually as a single image. Kubernetes uses a set of common sidecars to turn changes to API objects into CSI calls. The in-tree cloud disk plugins that used to live in the Kubernetes source code (such as kubernetes.io/azure-disk) have all moved to CSI. AKS stopped supporting volume creation with in-tree drivers starting in 1.26. Existing PVs are forwarded transparently to disk.csi.azure.com or file.csi.azure.com through CSI migration.
Why: Why use the sidecar pattern
The driver only has to implement the CSI gRPC API, and it does not need to understand Kubernetes. The community-maintained sidecars handle the Kubernetes parts: watch APIs, retries, leader election, and events. You can upgrade Kubernetes without waiting for a storage vendor release, and the reverse is also true.
How: Components and calls
| Deployment form | Container | Object watched | CSI methods called |
|---|---|---|---|
| Controller plugin (Deployment, 1–2 replicas, leader election) | external-provisioner | PVC (with the storage-provisioner annotation) | CreateVolume / DeleteVolume, create and delete PVs |
| external-attacher | VolumeAttachment | ControllerPublishVolume / ControllerUnpublishVolume | |
| external-resizer | PVC's spec.resources is increased | ControllerExpandVolume | |
| external-snapshotter (csi-snapshotter) | VolumeSnapshotContent | CreateSnapshot / DeleteSnapshot | |
| CSI driver container | — | Implements the Identity and Controller services, and calls the cloud API | |
| Node plugin (DaemonSet, one per node, privileged) | node-driver-registrar | — | Registers the driver socket with the kubelet through /var/lib/kubelet/plugins_registry. The kubelet calls NodeGetInfo and writes the result to CSINode. |
| CSI driver container | — | Called directly by the kubelet: NodeStageVolume, NodePublishVolume, NodeExpandVolume, NodeGetVolumeStats | |
| livenessprobe | — | Probe |
Two controllers are not in the sidecars: snapshot-controller (watches VolumeSnapshot and creates VolumeSnapshotContent; install it separately or use the one AKS provides) and the AD controller in kube-controller-manager (creates and deletes VolumeAttachments based on Pod scheduling results).
Two mount steps on the node
NodeStageVolume: once per volume per node. It finds the device (Azure Disk by LUN), runsmkfsif needed, and mounts the device to the global directory/var/lib/kubelet/plugins/kubernetes.io/csi/<driver>/<hash>/globalmount.NodePublishVolume: once per Pod. It bind-mounts to/var/lib/kubelet/pods/<uid>/volumes/kubernetes.io~csi/<pv>/mount, and then the CRI mounts it into the container. When several Pods on the same node share one RWO volume, the volume is staged once and published many times.
Three API objects
| Object | Created by | Purpose |
|---|---|---|
| CSIDriver | Driver install manifest | Declares driver capabilities: attachRequired (whether ControllerPublish is needed), podInfoOnMount, fsGroupPolicy (who changes ownership: File / ReadWriteOnceWithFSType / None), volumeLifecycleModes, storageCapacity, requiresRepublish, seLinuxMount |
| CSINode | kubelet (at registration) | Per node, per driver: the nodeID, topology keys (such as topology.disk.csi.azure.com/zone), and allocatable.count (the node's volume attach limit, used by the scheduler's NodeVolumeLimits plugin) |
| VolumeAttachment | AD controller | The intent and result of "attach volume X to node Y" (status.attached, attachError), carried out by external-attacher |
CSI drivers on Azure
| Azure Disk CSI (disk.csi.azure.com) | Azure Files CSI (file.csi.azure.com) | |
|---|---|---|
| Storage type | Block device (managed disk), formatted as ext4 or xfs on the node | SMB 3.x or NFS 4.1 file share |
| Access modes | RWO (/RWOP); multi-node sharing only in the special case of a shared disk | RWX / ROX / RWO |
| attach | Required (ControllerPublish attaches the disk to a LUN on the VM) | Not required (the node mounts the share directly over the network) |
| Performance tiers | Standard HDD/SSD, Premium SSD, Premium SSD v2 (IOPS and throughput can be set independently; cachingMode None only), Ultra Disk | Standard (HDD) / Premium (SSD, FileStorage account) |
| Redundancy | LRS; Premium_ZRS and StandardSSD_ZRS can be attached across zones | LRS / ZRS (storage account level) |
| Snapshots / clones / expansion | Supported (incremental snapshots by default). Online expansion up to 4 TiB; Premium SSD v2 and Ultra have no such limit | Expansion supported; snapshots are shared snapshots |
| Node limit | Limited by the VM SKU's "Max data disks" (for example, D2s_v5 allows 4 and D16s_v5 allows 32; check the documentation) | No disk-count limit (affected by network and mount count) |
| Typical uses | Databases and single-writer stateful services | Shared content, CMS upload directories, and shared disks for legacy apps |
When: Choose a CSI driver or something else
- Single-instance database → Azure Disk (Premium SSD or v2).
- Multiple Pods reading and writing shared data across nodes → Azure Files (NFS performs better and requires Premium). Object data → Blob CSI or the SDK directly.
- Local NVMe for maximum performance, where data loss is acceptable → Azure Container Storage (not covered in this hour).
Architecture diagram: how the CSI driver is deployed in the cluster
Flowchart: CSI methods ↔ Kubernetes objects ↔ Azure operations
Step-by-step animation: CSI call chain (Azure Disk)
Each step shows which component acts because of a change to which object, the gRPC method name it calls, and which Kubernetes object the result is written back to.
Core commands
| Command | Purpose | Notes |
|---|---|---|
kubectl get csidriver | List installed drivers and their capabilities | ATTACHREQUIRED, PODINFOONMOUNT, MODES, FSGROUPPOLICY (-o wide) |
kubectl get csinode NODE -o yaml | Drivers registered by nodes, topology keys, volume limits | spec.drivers[].allocatable.count |
kubectl get volumeattachment | Attach intent and status | ATTACHED column; -o yaml shows attachError |
kubectl -n kube-system get pods -l app=csi-azuredisk-node -o wide | Disk CSI node plugin on AKS | Labels may differ, so check the actual values: kubectl -n kube-system get ds | grep csi |
kubectl -n kube-system logs POD -c azuredisk --tail=100 | Driver logs, including every gRPC call | Search for GRPC call: /csi.v1.Controller/ |
az disk list -g MC_… -o table | See the provisioned disk on the Azure side | The disk name matches the PV name (pvc-…) |
Observe one complete CSI call chain on AKS
kubectl config use-context aks-lab
kubectl create ns shop --dry-run=client -o yaml | kubectl apply -f -
cat <<'EOF' | kubectl apply -f -
apiVersion: v1
kind: PersistentVolumeClaim
metadata: { name: disk-demo, namespace: shop }
spec:
accessModes: ["ReadWriteOnce"]
storageClassName: managed-csi
resources: { requests: { storage: 8Gi } }
---
apiVersion: v1
kind: Pod
metadata: { name: disk-demo, namespace: shop }
spec:
containers:
- name: c
image: busybox:1.37
command: ["sh","-c","df -h /data; sleep 3600"]
volumeMounts: [{ name: d, mountPath: /data }]
volumes:
- name: d
persistentVolumeClaim: { claimName: disk-demo }
EOF
kubectl -n shop wait --for=condition=Ready pod/disk-demo --timeout=180s
PV=$(kubectl -n shop get pvc disk-demo -o jsonpath='{.spec.volumeName}')
kubectl get pv $PV -o jsonpath='{.spec.csi.driver}{"\n"}{.spec.csi.volumeHandle}{"\n"}{.spec.nodeAffinity}{"\n"}'
kubectl get volumeattachment | grep $PV
kubectl -n shop logs disk-demo
disk.csi.azure.com
/subscriptions/xxxx/resourceGroups/mc_rg-k8s-lab_aks-lab_canadacentral/providers/Microsoft.Compute/disks/pvc-3c1e8a2b-…
{"required":{"nodeSelectorTerms":[{"matchExpressions":[{"key":"topology.disk.csi.azure.com/zone","operator":"In","values":["canadacentral-2"]}]}]}}
csi-9f8e… disk.csi.azure.com pvc-3c1e8a2b-… aks-nodepool1-12345678-vmss000001 true 40s
Filesystem Size Used Available Use% Mounted on
/dev/sdc 7.8G 24.0K 7.8G 0% /data
In a multi-zone cluster, the built-in SC uses ZRS, and the PV's nodeAffinity may list all zones or have no zone constraint. Check the actual output. This is how ZRS "can be mounted in any zone" in practice.
# Node volume limits and Azure-side disks
kubectl get csinode -o custom-columns=NODE:.metadata.name,DRIVER:.spec.drivers[*].name,LIMIT:.spec.drivers[*].allocatable.count
MC=$(az aks show -g rg-k8s-lab -n aks-lab --query nodeResourceGroup -o tsv)
az disk list -g $MC --query "[?starts_with(name,'pvc-')].{name:name,sku:sku.name,size:diskSizeGB,state:diskState,zones:zones}" -o table
NODE DRIVER LIMIT aks-nodepool1-12345678-vmss000000 disk.csi.azure.com,file.csi.azure.com 4 aks-nodepool1-12345678-vmss000001 disk.csi.azure.com,file.csi.azure.com 4 Name Sku Size State Zones pvc-3c1e8a2b-… StandardSSD_ZRS 8 Attached
Lab 3: Install the CSI hostpath driver and snapshot components on kind (about 6 minutes)
local-path is not CSI, so it cannot demonstrate attach, expansion, or snapshots. csi-driver-host-path is the official Kubernetes CSI example driver (for testing only, not for production). It fully implements the Controller and Node services and all the sidecars.
cd ~/k8slab/hour4 git clone --depth 1 -b v8.7.0 https://github.com/kubernetes-csi/external-snapshotter.git cd external-snapshotter kubectl kustomize client/config/crd | kubectl create -f - kubectl -n kube-system kustomize deploy/kubernetes/snapshot-controller | kubectl create -f - kubectl api-resources --api-group=snapshot.storage.k8s.io kubectl -n kube-system rollout status deploy/snapshot-controller cd ..
NAME SHORTNAMES APIVERSION NAMESPACED KIND volumesnapshotclasses vsclass,vsclasses snapshot.storage.k8s.io/v1 false VolumeSnapshotClass volumesnapshotcontents vsc,vscs snapshot.storage.k8s.io/v1 false VolumeSnapshotContent volumesnapshots vs snapshot.storage.k8s.io/v1 true VolumeSnapshot deployment "snapshot-controller" successfully rolled out
If a file path has changed in a new tag, follow the "Usage" section of the repository README. If the CRDs already exist, create returns AlreadyExists, which you can ignore.
git clone --depth 1 https://github.com/kubernetes-csi/csi-driver-host-path.git cd csi-driver-host-path ./deploy/kubernetes-latest/deploy.sh cd .. kubectl get pods -l app.kubernetes.io/instance=hostpath.csi.k8s.io -o wide kubectl get csidriver hostpath.csi.k8s.io kubectl get volumesnapshotclass
NAME READY STATUS RESTARTS AGE IP NODE csi-hostpathplugin-0 8/8 Running 0 60s 10.244.2.17 lab-worker2 NAME ATTACHREQUIRED PODINFOONMOUNT STORAGECAPACITY TOKENREQUESTS REQUIRESREPUBLISH MODES AGE hostpath.csi.k8s.io true true false <unset> false Persistent,Ephemeral 60s NAME DRIVER DELETIONPOLICY AGE csi-hostpath-snapclass hostpath.csi.k8s.io Delete 60s
The driver runs as a single-replica StatefulSet on one node (lab-worker2 in the example above), and all volumes are on that node. The container count and ATTACHREQUIRED columns may differ from your deployment. If the -l selector does not match, run kubectl get pods -A | grep hostpath directly.
HP_NODE=$(kubectl get pod csi-hostpathplugin-0 -o jsonpath='{.spec.nodeName}'); echo $HP_NODE
cat <<'EOF' | kubectl apply -f -
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata: { name: hostpath-csi }
provisioner: hostpath.csi.k8s.io
reclaimPolicy: Delete
volumeBindingMode: WaitForFirstConsumer
allowVolumeExpansion: true
EOF
kubectl get csinode $HP_NODE -o jsonpath='{range .spec.drivers[*]}{.name}{" topologyKeys="}{.topologyKeys}{"\n"}{end}'
lab-worker2 storageclass.storage.k8s.io/hostpath-csi created hostpath.csi.k8s.io topologyKeys=["topology.hostpath.csi/node"]
cat <<EOF | kubectl apply -f -
apiVersion: v1
kind: PersistentVolumeClaim
metadata: { name: csi-demo, namespace: shop }
spec:
accessModes: ["ReadWriteOnce"]
storageClassName: hostpath-csi
resources: { requests: { storage: 1Gi } }
---
apiVersion: v1
kind: Pod
metadata: { name: csi-demo, namespace: shop }
spec:
nodeSelector: { kubernetes.io/hostname: $HP_NODE }
containers:
- name: c
image: busybox:1.37
command: ["sh","-c","echo hello-csi > /data/hello; sleep 3600"]
volumeMounts: [{ name: d, mountPath: /data }]
volumes:
- name: d
persistentVolumeClaim: { claimName: csi-demo }
EOF
kubectl -n shop wait --for=condition=Ready pod/csi-demo --timeout=120s
kubectl get volumeattachment
kubectl logs csi-hostpathplugin-0 -c hostpath --tail=200 | grep -E 'GRPC call: /csi.v1.(Controller|Node)/' | awk '{print $NF}' | sort | uniq -c
NAME ATTACHER PV NODE ATTACHED AGE
csi-5b2f… hostpath.csi.k8s.io pvc-71d0… lab-worker2 true 12s
1 /csi.v1.Controller/ControllerPublishVolume
1 /csi.v1.Controller/CreateVolume
4 /csi.v1.Node/NodeGetCapabilities
1 /csi.v1.Node/NodePublishVolume
1 /csi.v1.Node/NodeStageVolume
The container name (-c hostpath) and log format may differ: kubectl get pod csi-hostpathplugin-0 -o jsonpath='{.spec.containers[*].name}'. If the driver does not declare the STAGE_UNSTAGE capability, NodeStageVolume will not appear.
csi-demo PVC for Module 5. Delete the Pod with kubectl -n shop delete pod csi-demo. On AKS: kubectl --context aks-lab -n shop delete pod disk-demo; kubectl --context aks-lab -n shop delete pvc disk-demo (the disk is deleted under the Delete policy).Case 1: Pods cannot be scheduled after the node pool moves to smaller VMs
Problem: To save money, the node pool running Kafka was changed from D8s_v5 to D2s_v5. Pods reported 0/3 nodes are available: 3 node(s) exceed max volume count.
Fix: Check CSINode.allocatable.count. Plan the number of PVCs per node using the "Max data disks" value for the VM SKU. If you need many small volumes, consider merging volumes, using Azure Files, or using Azure Container Storage.
Limitation: The limit is set by the Azure VM size and cannot be raised through Kubernetes configuration.
Case 2: Premium SSD v2 for a high-IOPS database
Problem: With Premium SSD (v1), IOPS is tied to capacity, so getting the IOPS it needed forced the team to buy a 1 TiB disk.
Fix: AKS 1.35+ provides the built-in managed-csi-premium-v2. To tune performance, create a new SC:
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata: { name: premium-v2-db }
provisioner: disk.csi.azure.com
parameters:
skuName: PremiumV2_LRS
cachingMode: None # PremiumV2_LRS supports only None
DiskIOPSReadWrite: "8000"
DiskMBpsReadWrite: "300"
reclaimPolicy: Retain
volumeBindingMode: WaitForFirstConsumer
allowVolumeExpansion: true
Limitation: Premium SSD v2 has zone and region availability requirements, and it supports only LRS. Confirm that the node pool's zone supports it.
Case 3: Migrating existing in-tree PVs
On an older cluster, SCs whose provisioner is kubernetes.io/azure-disk can no longer create new volumes, but existing PVs keep working through CSI migration. Approach: create a new CSI SC and make it the default. New workloads use the new SC. Existing volumes can be migrated during a maintenance window by taking a snapshot and creating a new PVC from it (see Microsoft Learn, "Migrate from in-tree to CSI drivers").
Common errors and fixes
driver name disk.csi.azure.com not found in the list of registered CSI drivers
Cause: The node plugin is not running on that node, or it has not yet registered with the kubelet. The DaemonSet may be blocked by a taint, the image pull may have failed, or the registrar may have crashed.
kubectl get csinode NODE -o yaml | grep -A3 drivers kubectl -n kube-system get pods -o wide | grep -E 'csi-azuredisk-node|NODE' kubectl -n kube-system logs POD -c node-driver-registrar --tail=50
Fix: Make the node plugin run on that node (check tolerations and nodeSelector). On AKS, run az aks update --enable-disk-driver to re-enable it.
AttachVolume.Attach failed for volume "pvc-…" : rpc error: code = ... timed out waiting for external-attacher
Cause: external-attacher is not running or has no leader, the cloud API is throttling requests, the VM has reached its data disk limit, or the disk is still attached to another VM.
kubectl get volumeattachment -o custom-columns=NAME:.metadata.name,PV:.spec.source.persistentVolumeName,NODE:.spec.nodeName,ATTACHED:.status.attached,ERR:.status.attachError.message kubectl -n kube-system logs deploy/csi-azuredisk-controller -c csi-attacher --tail=80
Fix: Act on the attachError. If an old node is still holding the disk, see Module 8, Multi-Attach.
MountVolume.MountDevice failed ... format of disk "/dev/sdc" failed / wrong fs type
Cause: The static PV's fsType does not match the filesystem already on the disk, or the disk has a partition table. NodeStage does not overwrite existing data.
Fix: Set the correct filesystem in the PV's csi.volumeAttributes.fsType, or use the partition parameter. Never force-format a disk that contains data.
the server could not find the requested resource (get volumesnapshots.snapshot.storage.k8s.io)
Cause: The snapshot CRDs are not installed (kind does not install them by default). On AKS, the snapshot controller is controlled with --enable-snapshot-controller / --disable-snapshot-controller.
kubectl api-resources --api-group=snapshot.storage.k8s.io kubectl -n kube-system get deploy | grep -i snapshot
1. List the PV, node, and attach status for each VolumeAttachment.
kubectl get volumeattachment -o custom-columns=PV:.spec.source.persistentVolumeName,NODE:.spec.nodeName,ATTACHED:.status.attached
2. Query the disk.csi.azure.com volume limit on every node.
kubectl get csinode -o json | jq -r '.items[] | .metadata.name + " " + ((.spec.drivers[] | select(.name=="disk.csi.azure.com") | .allocatable.count) | tostring)'
A CMS system has 3 Pods spread across 3 nodes, and all of them read and write the same uploads directory. A colleague suggests using managed-csi-premium. What do you think?
Azure Disk is block storage and supports only RWO (attached to one VM at a time), so the Pod on the second node will fail with Multi-Attach. Use Azure Files (azurefile-csi-premium, RWX). For small-file Linux workloads that are sensitive to performance, consider a Premium file share using the NFS protocol. Or change the uploads to write directly to Blob storage, with the application accessing it through the SDK and workload identity. The latter scales better.
Teaching videos
No video was found that can be fully verified (matching title, author, and YouTube ID) and that covers the CSI call chain specifically. The KubeCon EU 2025 session "Kubernetes SIG Storage: Intro & Deep Dive" (Xing Yang, Jan Šafránek) exists, but its YouTube link could not be verified, so no link is listed. You can search the CNCF YouTube channel for that title.
Official documentation
- Kubernetes CSI Developer Documentation (sidecar reference)
- CSI Spec
- AKS: CSI storage drivers (2026-08-03)
- AKS: Azure Disks persistent volumes (2026-10-16)
- csi-driver-host-path
Video storyboard script
This lesson cannot directly generate the video or MP3. The storyboard and narration script are provided instead.
Narration: CSI is the standard socket between Kubernetes and storage. Vendors only need to implement three groups of gRPC services.
Narration: The sidecars understand Kubernetes. The driver only needs to understand storage.
Narration: Creation and attach happen in the control plane. The results are written back to the PV and the VolumeAttachment.
Narration: The kubelet makes the node-side calls directly: one stage, then multiple publishes.
Narration: Choosing the right driver is the first step to choosing the right access mode.
Module 4 · Access Modes · Reclaim Policies · Topology
- State exactly what RWO, ROX, RWX, and RWOP mean. Say whether each one constrains a node or a Pod, and state which backends support which modes.
- Understand how the Retain and Delete reclaim policies affect data safety, and why Recycle is deprecated.
- Understand topology awareness: PV nodeAffinity, StorageClass
allowedTopologies,WaitForFirstConsumer, and Azure multi-zone with ZRS. - Know how node volume attach limits affect scheduling.
What: The four access modes
| Mode | Abbreviation | Exact meaning | Common misreading |
|---|---|---|---|
ReadWriteOnce | RWO | A volume can be mounted read-write by one node. Multiple Pods on that same node can use it at the same time. | Taken to mean "one Pod" |
ReadOnlyMany | ROX | Can be mounted read-only by multiple nodes | Assumed that all block storage supports it |
ReadWriteMany | RWX | Can be mounted read-write by multiple nodes at the same time | Assumed the application can safely write to the same file concurrently (this requires the application to coordinate its own writes) |
ReadWriteOncePod | RWOP | Can be used for reads and writes by one Pod across the entire cluster (v1.29 GA; CSI volumes only). It is enforced jointly by the scheduler's VolumeRestrictions plugin and the kubelet. | — |
An access mode is a capability declaration plus a matching condition. A PVC binds only if its requested modes are a subset of the modes the PV supports. Kubernetes does not block multiple Pods on the same node from writing to an RWO volume at runtime.
What each backend supports
| Backend | RWO | ROX | RWX | RWOP | Notes |
|---|---|---|---|---|---|
| Azure Disk (disk.csi.azure.com) | ✓ | △ | △ | ✓ | Block storage. RWX is limited to shared disks (maxShares) with cluster-aware applications. Do not use it for typical scenarios. |
| Azure Files (file.csi.azure.com) | ✓ | ✓ | ✓ | · | SMB / NFS shares, natively multi-node |
| Azure Blob CSI | ✓ | ✓ | ✓ | · | BlobFuse / NFS 3.0; not suitable for databases |
| kind local-path | ✓ | · | · | △ | Local directory, pinned to one node |
| csi-driver-host-path | ✓ | · | · | ✓ | Test driver, single node |
| NFS (nfs.csi.k8s.io) | ✓ | ✓ | ✓ | · | Self-hosted NFS server |
△ Indicates a condition or a version-dependent behavior. Check the driver documentation.
Why: Reclaim policies
| Policy | After the PVC is deleted | Use case |
|---|---|---|
Delete (default for dynamic provisioning) | external-provisioner calls DeleteVolume. The cloud disk is deleted, and the PV object is removed. | Development / rebuildable data |
Retain | The PV becomes Released. The cloud disk and its data are kept. Manual cleanup or rebinding is needed. | Production databases, compliance data |
Recycle | (Deprecated) Runs rm -rf, then becomes Available again | Do not use. Use dynamic provisioning instead. |
The PV's persistentVolumeReclaimPolicy can be changed on a live PV. Switching an important PV to Retain before a risky operation is a common safeguard for SREs. In newer versions, PVs carry a deletion-protection finalizer (such as external-provisioner.volume.kubernetes.io/finalizer). Even if the PV is deleted first, the backend is cleaned up according to the reclaim policy, which reduces orphaned disks.
How: Topology awareness
- PV.spec.nodeAffinity: The provisioner writes this from the CSI
accessible_topology. For example,topology.disk.csi.azure.com/zone In [canadacentral-2]. A Pod that uses the PV can only be scheduled to nodes that meet this condition. - WaitForFirstConsumer: The scheduler first weighs CPU, memory, affinity, and taints to choose a node. It then passes that node's topology to the provisioner (in
accessibility_requirements.preferredof CreateVolume). This ensures the disk follows the Pod. - allowedTopologies: A StorageClass-level restriction that limits disk creation to certain zones (for example, to meet data residency requirements).
- Azure ZRS:
Premium_ZRSandStandardSSD_ZRSdisks are synchronously replicated across three zones in a region. They can attach to a node in any zone. If a zone fails, the Pod can be rebuilt in another zone and attach the same disk. Trade-offs: higher price and slightly higher write latency. On multi-zone AKS clusters with 1.29+, the built-in Disk SC defaults to ZRS (except Premium SSD v2, which supports only LRS). - Node volume limit: CSINode
allocatable.count. The scheduler's NodeVolumeLimits plugin uses it to filter nodes.
When: Choosing a checklist
- Single-writer database → RWO (or the stricter RWOP) + Retain + WFFC + ZRS (high availability across zones), or application-level replication + LRS.
- Multiple replicas sharing static content → RWX (Azure Files), or ROX.
- Only one Pod may write (to prevent old and new Pods from writing at the same time during a rolling update) → RWOP.
Architecture diagram: the relationship between access modes and nodes / Pods
Flowchart: failover of LRS and ZRS disks across zones
Interactive: choose a backend, an access mode, and a scenario to check whether it works
The logic is based on the actual behavior of driver capabilities, the scheduler's VolumeRestrictions and VolumeBinding plugins, and the AD controller.
Core commands
| Command | Purpose | Notes |
|---|---|---|
kubectl get pv -o custom-columns=NAME:.metadata.name,MODES:.spec.accessModes,POLICY:.spec.persistentVolumeReclaimPolicy,STATUS:.status.phase | List access modes and reclaim policies | Audit production PVs for Retain |
kubectl patch pv PV -p '{"spec":{"persistentVolumeReclaimPolicy":"Retain"}}' | Change to Retain on a live PV | Safeguard before a risky operation |
kubectl get pv PV -o jsonpath='{.spec.nodeAffinity}' | Check topology constraints | Explain volume node affinity conflict |
kubectl get nodes -L topology.kubernetes.io/zone | Zone of the node | AKS: canadacentral-1/2/3 |
kubectl get csinode NODE -o jsonpath='{.spec.drivers[*].allocatable.count}' | Node volume limit | The scheduler filters on this |
PVC syntax for RWOP
apiVersion: v1
kind: PersistentVolumeClaim
metadata: { name: single-writer, namespace: shop }
spec:
accessModes: ["ReadWriteOncePod"] # can be used alone only; cannot be combined with other modes
storageClassName: hostpath-csi # requires a CSI driver
resources: { requests: { storage: 1Gi } }
Zone-restricted StorageClass (AKS)
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata: { name: premium-lrs-zone1 }
provisioner: disk.csi.azure.com
parameters: { skuName: Premium_LRS }
reclaimPolicy: Retain
volumeBindingMode: WaitForFirstConsumer
allowVolumeExpansion: true
allowedTopologies:
- matchLabelExpressions:
- key: topology.disk.csi.azure.com/zone
values: ["canadacentral-1"]
Azure Files RWX (AKS)
cat <<'EOF' | kubectl --context aks-lab apply -f -
apiVersion: v1
kind: PersistentVolumeClaim
metadata: { name: shared-uploads, namespace: shop }
spec:
accessModes: ["ReadWriteMany"]
storageClassName: azurefile-csi
resources: { requests: { storage: 100Gi } }
EOF
kubectl --context aks-lab -n shop get pvc shared-uploads -w
NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS AGE shared-uploads Bound pvc-a71c… 100Gi RWX azurefile-csi 15s
Common error: Requesting ReadWriteMany from managed-csi → ProvisioningFailed ... Volume capability not supported. Production uses: shared upload directories and model caches. For the minimum billable capacity and IOPS characteristics of Azure Files Standard-tier SMB, refer to Microsoft Learn.
Lab 4: RWO vs. RWOP, allowedTopologies, and Retain (about 6 minutes, kind)
cd ~/k8slab/hour4
HP_NODE=$(kubectl get pod csi-hostpathplugin-0 -o jsonpath='{.spec.nodeName}')
for mode in ReadWriteOnce ReadWriteOncePod; do
NAME=$(echo $mode | tr 'A-Z' 'a-z')
cat <<EOF | kubectl apply -f -
apiVersion: v1
kind: PersistentVolumeClaim
metadata: { name: $NAME, namespace: shop }
spec:
accessModes: ["$mode"]
storageClassName: hostpath-csi
resources: { requests: { storage: 1Gi } }
EOF
for i in 1 2; do
cat <<EOF | kubectl apply -f -
apiVersion: v1
kind: Pod
metadata: { name: $NAME-$i, namespace: shop }
spec:
nodeSelector: { kubernetes.io/hostname: $HP_NODE }
containers:
- { name: c, image: busybox:1.37, command: ["sh","-c","echo pod-$i >> /d/who; sleep 3600"], volumeMounts: [{ name: d, mountPath: /d }] }
volumes: [{ name: d, persistentVolumeClaim: { claimName: $NAME } }]
EOF
done; done
sleep 20; kubectl -n shop get pods -l '!app' -o wide | grep -E 'readwriteonce'
readwriteonce-1 1/1 Running 0 20s 10.244.2.21 lab-worker2 readwriteonce-2 1/1 Running 0 20s 10.244.2.22 lab-worker2 readwriteoncepod-1 1/1 Running 0 20s 10.244.2.23 lab-worker2 readwriteoncepod-2 0/1 Pending 0 20s <none> <none>
kubectl -n shop describe pod readwriteoncepod-2 | sed -n '/Events/,$p' kubectl -n shop exec readwriteonce-1 -- cat /d/who
Warning FailedScheduling default-scheduler 0/3 nodes are available: 1 node has pod using PersistentVolumeClaim with the same name and ReadWriteOncePod access mode, 2 node(s) didn't match Pod's node affinity/selector. … pod-1 pod-2
An RWO volume was written to by two Pods at the same time (the file contains pod-1 and pod-2). RWOP is enforced by the scheduler's VolumeRestrictions plugin. After you delete readwriteoncepod-1, Pod 2 is scheduled automatically.
kubectl label node lab-worker topology.kubernetes.io/zone=zone-a --overwrite
kubectl label node lab-worker2 topology.kubernetes.io/zone=zone-b --overwrite
cat <<'EOF' | kubectl apply -f -
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata: { name: local-zone-a }
provisioner: rancher.io/local-path
reclaimPolicy: Delete
volumeBindingMode: WaitForFirstConsumer
allowedTopologies:
- matchLabelExpressions:
- { key: topology.kubernetes.io/zone, values: ["zone-a"] }
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata: { name: zoned, namespace: shop }
spec:
accessModes: ["ReadWriteOnce"]
storageClassName: local-zone-a
resources: { requests: { storage: 1Gi } }
---
apiVersion: v1
kind: Pod
metadata: { name: zoned, namespace: shop }
spec:
containers: [{ name: c, image: busybox:1.37, command: ["sleep","3600"], volumeMounts: [{ name: d, mountPath: /d }] }]
volumes: [{ name: d, persistentVolumeClaim: { claimName: zoned } }]
EOF
kubectl -n shop wait --for=condition=Ready pod/zoned --timeout=60s
kubectl -n shop get pod zoned -o jsonpath='{.spec.nodeName}{"\n"}'
lab-worker
The scheduler's VolumeBinding plugin excludes nodes that do not meet allowedTopologies during the Filter stage.
PV=$(kubectl -n shop get pvc zoned -o jsonpath='{.spec.volumeName}')
kubectl patch pv $PV -p '{"spec":{"persistentVolumeReclaimPolicy":"Retain"}}'
kubectl -n shop exec zoned -- sh -c 'echo keep-me > /d/important'
kubectl -n shop delete pod zoned; kubectl -n shop delete pvc zoned
kubectl get pv $PV
docker exec lab-worker sh -c "cat /var/local-path-provisioner/${PV}_shop_zoned/important"
NAME CAPACITY ACCESS MODES RECLAIM POLICY STATUS CLAIM STORAGECLASS AGE pvc-6e2… 1Gi RWO Retain Released shop/zoned local-zone-a 2m keep-me
kubectl -n shop delete pod readwriteonce-1 readwriteonce-2 readwriteoncepod-1 readwriteoncepod-2 --ignore-not-found
kubectl -n shop delete pvc readwriteonce readwriteoncepod --ignore-not-found
kubectl delete pv $PV; docker exec lab-worker rm -rf /var/local-path-provisioner/${PV}_shop_zoned
kubectl delete sc local-zone-a
kubectl label node lab-worker lab-worker2 topology.kubernetes.io/zone-Case 1: A rolling update corrupted a SQLite file
Problem: A single-replica Deployment (RWO PVC) used the default RollingUpdate (maxSurge 25%). The new Pod was scheduled to the same node, so the old and new processes opened the SQLite file at the same time, and the database was corrupted.
Fix: Switch the PVC to ReadWriteOncePod (the new Pod stays Pending until the old Pod exits), and set the Deployment to strategy: Recreate. Or simply change it to a StatefulSet.
Limitation: RWOP is supported only for CSI volumes. An existing PVC's accessModes cannot be changed directly, so you must migrate through a snapshot or clone to a new PVC.
Case 2: Zone-level failure drill
Problem: During a drill, the node in zone 1 was shut down. A single-replica Redis (Premium_LRS) could not be rebuilt in another zone, and recovery time exceeded the SLO.
Fix: Switch to the Premium_ZRS SC. (On multi-zone AKS clusters with 1.29+, the built-in managed-csi-premium is ZRS.) The Pod is rebuilt in zone 2 and attaches the same disk directly. Combine this with the out-of-service taint to speed up detach (Module 8).
Limitation: ZRS is available only in some regions. Write latency is slightly higher. Premium SSD v2 does not support ZRS, so use application-level replication instead.
Case 3: Recovering data from an accidentally deleted PVC
A developer ran kubectl delete ns staging, and the PVCs were deleted with it. The PVs in the production namespace were kept because they use Retain. The admin cleared the claimRef on the Released PV and let a new PVC bind with volumeName, restoring service in 30 minutes. The PVs in staging used the Delete policy, so they were removed along with their Azure disks. The only option there was to restore from a Velero backup.
Common errors and fixes
0/3 nodes are available: 3 node(s) had volume node affinity conflict
Cause: The PV's nodeAffinity (node or zone) does not match any schedulable node. Possible reasons: with Immediate mode, the disk was created in another zone; the node hosting a local PV is unavailable; or the node was deleted and rebuilt, so its hostname changed.
kubectl get pv PV -o jsonpath='{.spec.nodeAffinity}' | jq .
kubectl get nodes -L topology.kubernetes.io/zone,kubernetes.io/hostname
Fix: Make sure the matching zone has available nodes (scale out the node pool). Use WFFC going forward. An LRS disk can only be recreated in a new zone from a snapshot.
node has pod using PersistentVolumeClaim with the same name and ReadWriteOncePod access mode
Cause: The RWOP PVC is already in use by another Pod (possibly an old replica still in Terminating).
kubectl -n shop get pods -o json | jq -r '.items[] | select(.spec.volumes[]?.persistentVolumeClaim.claimName=="PVC") | .metadata.name + " " + .status.phase'
Fix: Wait for the old Pod to exit, or check whether it was accidentally configured with multiple replicas.
failed to provision volume ... rpc error: code = InvalidArgument desc = Volume capability not supported
Cause: The requested access mode is not supported by the driver (such as Azure Disk with RWX, or Files with RWOP), or volumeMode: Block was used with a file-based driver.
Fix: Choose the backend using the support matrix on the "Principles" page. Delete and recreate the PVC, because accessModes cannot be changed.
0/3 nodes are available: 3 node(s) exceed max volume count
Cause: The number of CSI volumes already mounted on the node has reached CSINode.allocatable.count (the Azure VM data disk limit).
kubectl get csinode -o custom-columns=NODE:.metadata.name,LIMIT:.spec.drivers[*].allocatable.count kubectl get volumeattachment -o custom-columns=NODE:.spec.nodeName --no-headers | sort | uniq -c
Fix: Scale out the node pool, switch to a larger VM SKU, reduce the number of volumes per Pod, or use file shares instead.
1. Find all PVs that have the Delete reclaim policy and are bound in the prod namespace, and change them to Retain.
for pv in $(kubectl get pv -o json | jq -r '.items[] | select(.spec.claimRef.namespace=="prod" and .spec.persistentVolumeReclaimPolicy=="Delete") | .metadata.name'); do
kubectl patch pv $pv -p '{"spec":{"persistentVolumeReclaimPolicy":"Retain"}}'
done2. Check which zone a given PV is restricted to.
kubectl get pv PV -o jsonpath='{.spec.nodeAffinity.required.nodeSelectorTerms[*].matchExpressions[*].values}{"\n"}'A 3-replica Elasticsearch StatefulSet runs on an AKS cluster across 3 zones. It uses a self-managed Premium_LRS SC with Immediate binding. Occasionally, scaling up creates a new replica that gets stuck in Pending. Analyze the cause and suggest improvements.
Immediate mode picks a zone and creates the disk when the PVC is created. That can conflict with the Pod's anti-affinity or resource constraints and cause a volume node affinity conflict. Change to WaitForFirstConsumer. Elasticsearch has its own shard replicas, so it can keep using LRS (cheaper, lower latency), combined with topologySpreadConstraints to spread replicas across zones. Use ZRS only for components that must survive a zone failure as a single replica. Also set the reclaim policy of the production SC to Retain.
Teaching videos
No video was found that specifically covers access modes and topology and whose YouTube ID could be verified. The TechWorld with Nana video "Kubernetes Volumes explained" (0swOh5C3OVM), listed in Module 1, briefly covers access modes and can serve as an introductory reference.
Official documentation
- Access Modes (RWOP stable since v1.29)
- Allowed Topologies
- Node-specific Volume Limits
- Azure managed disks redundancy (LRS / ZRS)
Video storyboard script
This lesson cannot directly generate the video or MP3. The storyboard and narration script are provided instead.
Narration: The "Once" in RWO refers to a node, not a Pod.
Narration: To make sure only one Pod writes, use ReadWriteOncePod, which became generally available in v1.29.
Narration: For production data, use Retain. The disk stays behind when you delete the PVC.
Narration: ZRS lets a single-replica application survive a zone failure, but it is not a backup.
Module 5 · Expansion · Snapshots · Cloning
- Perform an online expansion: confirm
allowVolumeExpansion, edit the PVC'sspec.resources.requests.storage, and understand the two-phase ControllerExpand → NodeExpand flow and theFileSystemResizePendingcondition. Know that a PVC cannot be shrunk. - Know the three objects VolumeSnapshot, VolumeSnapshotContent, and VolumeSnapshotClass, and the three prerequisites: CRDs, snapshot-controller, and driver support.
- Restore from a snapshot (
dataSourcekind VolumeSnapshot) and clone a PVC (kind PersistentVolumeClaim). - Understand VolumeGroupSnapshot (crash-consistent across multiple volumes) and volume populators (
dataSourceRefpointing to a custom resource).
What: Three data operations
| Operation | Object you change or create | Responsible component | CSI call | Prerequisite |
|---|---|---|---|---|
| Expansion | Increase the PVC's spec.resources.requests.storage | external-resizer (control plane) + kubelet (node) | ControllerExpandVolume → NodeExpandVolume (resize2fs / xfs_growfs) | SC has allowVolumeExpansion: true + driver support |
| Snapshot | VolumeSnapshot | snapshot-controller creates VolumeSnapshotContent; csi-snapshotter calls the driver | CreateSnapshot | CRDs + snapshot-controller + VolumeSnapshotClass + driver support |
| Restore from snapshot | New PVC with dataSource: {kind: VolumeSnapshot} | external-provisioner | CreateVolume (content_source=snapshot) | Same namespace; capacity ≥ restoreSize |
| Clone | New PVC with dataSource: {kind: PersistentVolumeClaim} | external-provisioner | CreateVolume (content_source=volume) | Same namespace, same SC (same driver), capacity ≥ source |
Why: Why snapshots have three layers
They map directly to PVC / PV / StorageClass: VolumeSnapshot (namespace-scoped, the user's request) ↔ VolumeSnapshotContent (cluster-scoped, represents the actual backend snapshot and contains snapshotHandle) ↔ VolumeSnapshotClass (driver, deletionPolicy, and parameters such as incremental on Azure). This also lets an existing snapshot be imported statically: create a VSC that specifies the snapshotHandle, then create a VS that references it.
How: The two phases of expansion
- You change the PVC from 1Gi to 2Gi. The apiserver validates that the SC allows expansion and that the new value is larger than the old one. (You cannot shrink a volume. It reports
field can not be less than previous value.) - external-resizer calls
ControllerExpandVolume(on Azure, this resizes the managed disk). On success, it updates PV.spec.capacity. - If a filesystem resize is needed, the PVC shows the
FileSystemResizePendingcondition. If the volume is online (mounted), the kubelet callsNodeExpandVolumeduring its next sync to expand the filesystem. If the volume is offline, the resize waits for the next Pod to mount it. - When complete,
status.capacityupdates to 2Gi and the condition clears.status.allocatedResourceStatusesrecords progress (for example,ControllerResizeInProgressorNodeResizePending). - If an expansion fails (for example, because it exceeds the quota), you can retry with a smaller request that is still larger than
status.capacity. The request cannot be smaller than the current capacity.
Snapshot consistency
- A CSI snapshot is crash-consistent: it matches the disk state after a sudden power loss. PostgreSQL can recover from a crash-consistent state using WAL, but it is better to run
CHECKPOINTfirst or use an application-level backup (pg_dump or pg_basebackup, see the Module 7 hook). - VolumeGroupSnapshot (
groupsnapshot.storage.k8s.io/v1, GA in v1.36): Selects multiple PVCs by label and creates a set of snapshots at the same point in time. You must use it when the data and WAL are on separate volumes, so they stay consistent. It requires CSI driver support for group snapshots. - A snapshot is not a backup. Azure incremental snapshots are stored in the same region and subscription. For cluster-, region-, or subscription-level incidents, you need off-site backups (Velero data movement, Azure Backup for AKS).
Volume populator (GA in v1.33)
A PVC's dataSourceRef can point to any custom resource (for example, a CR that "downloads a dataset from S3"). The matching populator controller first creates a temporary PVC (PVC') and fills it with data, then rebinds the PV to your PVC. dataSource supports only PVC and VolumeSnapshot (and compatible populators). dataSourceRef is more general. If both are set, they must match. Cross-namespace data sources are still an Alpha feature (see the official documentation).
When
- Capacity alert → online expansion. First confirm that the SC and driver support it. Azure Disk up to 4 TiB can be expanded online; larger sizes require detaching. Premium SSD v2 and Ultra have no such limit.
- Before an upgrade, migration, or risky change → take a snapshot.
- To copy production data for a test environment (after anonymizing it) → restore from a snapshot or clone.
- Multi-volume application → VolumeGroupSnapshot.
Comparison with similar techniques
| Method | Granularity | Consistency | Speed | Works across regions or clusters? |
|---|---|---|---|---|
| CSI snapshot | Single volume | Crash-consistent | Seconds (incremental) | Usually no (same region in the cloud) |
| VolumeGroupSnapshot | Multiple volumes | Crash-consistent within the group | Seconds | No |
| PVC clone | Single volume | Crash-consistent | Depends on the backend | No (same namespace and same SC) |
| pg_dump / logical backup | Database | Transaction-consistent | Proportional to data size | Yes |
| Velero (Module 7) | Namespace / resources + volumes | Hooks can achieve application consistency | Medium | Yes (object storage) |
df -h will not change until then. ③ "Snapshots are useless once the source PVC is deleted." No. A snapshot is independent of its source PVC and can still be restored. In the other direction, deleting a VolumeSnapshot with deletionPolicy=Delete also deletes the backend snapshot. ④ "local-path can also expand." No. Its allowVolumeExpansion is false.Architecture diagram: snapshot-related objects and controllers
Flowchart: the two phases of online expansion
Interactive simulator: expand / shrink / snapshot / restore / clone
Each button corresponds to a real kubectl operation. The object list on the right shows the objects that appear in the API, and the log shows the controller and CSI calls.
Core commands
| Command | Purpose | Notes |
|---|---|---|
kubectl patch pvc P -p '{"spec":{"resources":{"requests":{"storage":"2Gi"}}}}' | Expand | Can also use kubectl edit; can only increase |
kubectl get pvc P -o jsonpath='{.status.conditions}' | Watch Resizing / FileSystemResizePending | Use together with .status.allocatedResourceStatuses |
kubectl get volumesnapshotclass / vsclass | Snapshot class | Set as default with the annotation snapshot.storage.kubernetes.io/is-default-class: "true" |
kubectl get vs,vsc | Snapshots and snapshot contents | READYTOUSE, RESTORESIZE, SNAPSHOTCONTENT |
kubectl wait vs/S --for=jsonpath='{.status.readyToUse}'=true | Wait for the snapshot to be available | Must be ready before restoring |
Expansion (hostpath-csi, Pod online)
HP_NODE=$(kubectl get pod csi-hostpathplugin-0 -o jsonpath='{.spec.nodeName}')
kubectl -n shop run csi-user --image=busybox:1.37 --restart=Never \
--overrides="{\"spec\":{\"nodeSelector\":{\"kubernetes.io/hostname\":\"$HP_NODE\"},\"volumes\":[{\"name\":\"d\",\"persistentVolumeClaim\":{\"claimName\":\"csi-demo\"}}],\"containers\":[{\"name\":\"csi-user\",\"image\":\"busybox:1.37\",\"command\":[\"sleep\",\"3600\"],\"volumeMounts\":[{\"name\":\"d\",\"mountPath\":\"/data\"}]}]}}"
kubectl -n shop wait --for=condition=Ready pod/csi-user --timeout=60s
kubectl -n shop patch pvc csi-demo -p '{"spec":{"resources":{"requests":{"storage":"2Gi"}}}}'
kubectl -n shop get pvc csi-demo -w
NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS AGE csi-demo Bound pvc-71d0… 1Gi RWO hostpath-csi 12m csi-demo Bound pvc-71d0… 2Gi RWO hostpath-csi 12m
kubectl -n shop describe pvc csi-demo | sed -n '/Events/,$p' | tail -4
kubectl -n shop patch pvc csi-demo -p '{"spec":{"resources":{"requests":{"storage":"1Gi"}}}}'
Normal Resizing external-resizer hostpath.csi.k8s.io External resizer is resizing volume pvc-71d0… Normal FileSystemResizeRequired external-resizer hostpath.csi.k8s.io Require file system resize of volume on node Normal FileSystemResizeSuccessful kubelet MountVolume.NodeExpandVolume succeeded for volume "pvc-71d0…" The PersistentVolumeClaim "csi-demo" is invalid: spec.resources.requests.storage: Forbidden: field can not be less than status.capacity
The exact shrink error wording varies slightly by version (in the AKS documentation it is "field can not be less than previous value"). The hostpath driver's "capacity" is logical bookkeeping, so df may show the node's disk size.
Snapshot, restore, clone
apiVersion: snapshot.storage.k8s.io/v1
kind: VolumeSnapshot
metadata: { name: csi-demo-snap1, namespace: shop }
spec:
volumeSnapshotClassName: csi-hostpath-snapclass # AKS: csi-azuredisk-vsc
source:
persistentVolumeClaimName: csi-demo
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata: { name: csi-demo-restored, namespace: shop }
spec:
storageClassName: hostpath-csi
accessModes: ["ReadWriteOnce"]
resources: { requests: { storage: 2Gi } } # ≥ restoreSize
dataSource:
name: csi-demo-snap1
kind: VolumeSnapshot
apiGroup: snapshot.storage.k8s.io
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata: { name: csi-demo-clone, namespace: shop }
spec:
storageClassName: hostpath-csi # must match the source
accessModes: ["ReadWriteOnce"]
resources: { requests: { storage: 2Gi } }
dataSource:
name: csi-demo
kind: PersistentVolumeClaim
AKS: Azure Disk snapshot class
kubectl --context aks-lab apply -f https://raw.githubusercontent.com/kubernetes-sigs/azuredisk-csi-driver/master/deploy/example/snapshot/storageclass-azuredisk-snapshot.yaml kubectl --context aks-lab get vsclass csi-azuredisk-vsc -o yaml | grep -E 'driver|deletionPolicy|incremental' kubectl --context aks-lab -n kube-system get deploy | grep -i snapshot # confirm snapshot-controller
volumesnapshotclass.snapshot.storage.k8s.io/csi-azuredisk-vsc created deletionPolicy: Delete driver: disk.csi.azure.com incremental: "true" snapshot-controller 2/2 2 2 1h
VolumeGroupSnapshot (GA in v1.36) example
apiVersion: groupsnapshot.storage.k8s.io/v1
kind: VolumeGroupSnapshot
metadata: { name: db-group-1, namespace: shop }
spec:
volumeGroupSnapshotClassName: my-group-snapclass # provided by the driver
source:
selector:
matchLabels: { app: db, consistency-group: pg }
Requires: the groupsnapshot CRD (external-snapshotter v8.6+ provides v1), snapshot-controller and csi-snapshotter with group snapshots enabled, and the driver declaring the VOLUME_GROUP_SNAPSHOT capability. Check the external-snapshotter documentation for whether it is enabled by default. Restore still creates a PVC for each VolumeSnapshot in the group.
Lab 5: Expand → snapshot → accidental deletion → restore → clone (about 7 minutes, kind + hostpath CSI; AKS steps are optional)
csi-demo PVC from Module 3 and the csi-user Pod from the "Commands" tab. If it has not been created, first run the first three lines of the expansion code block.
kubectl -n shop exec csi-user -- sh -c 'for i in $(seq 1 100); do echo "order-$i" >> /data/orders.txt; done; sync; wc -l /data/orders.txt'
100 /data/orders.txt
kubectl -n shop patch pvc csi-demo -p '{"spec":{"resources":{"requests":{"storage":"2Gi"}}}}'
kubectl -n shop wait pvc/csi-demo --for=jsonpath='{.status.capacity.storage}'=2Gi --timeout=60s
kubectl -n shop get pod csi-user -o jsonpath='{.status.containerStatuses[0].restartCount}{"\n"}'
persistentvolumeclaim/csi-demo condition met 0
snap-restore-clone.yaml from the "Commands" tab, and apply only the first document first):
cd ~/k8slab/hour4
kubectl -n shop exec csi-user -- sync
awk 'BEGIN{RS="---\n"} NR==1' snap-restore-clone.yaml | kubectl apply -f -
kubectl -n shop wait vs/csi-demo-snap1 --for=jsonpath='{.status.readyToUse}'=true --timeout=60s
kubectl -n shop get vs csi-demo-snap1
kubectl get vsc
NAME READYTOUSE SOURCEPVC SOURCESNAPSHOTCONTENT RESTORESIZE SNAPSHOTCLASS SNAPSHOTCONTENT CREATIONTIME AGE csi-demo-snap1 true csi-demo 2Gi csi-hostpath-snapclass snapcontent-1f2e… 5s 6s NAME READYTOUSE RESTORESIZE DELETIONPOLICY DRIVER VOLUMESNAPSHOTCLASS VOLUMESNAPSHOT VOLUMESNAPSHOTNAMESPACE AGE snapcontent-1f2e… true 2147483648 Delete hostpath.csi.k8s.io csi-hostpath-snapclass csi-demo-snap1 shop 6s
kubectl -n shop exec csi-user -- sh -c 'rm /data/orders.txt; ls -la /data'
awk 'BEGIN{RS="---\n"} NR==2' snap-restore-clone.yaml | kubectl apply -f -
HP_NODE=$(kubectl get pod csi-hostpathplugin-0 -o jsonpath='{.spec.nodeName}')
kubectl -n shop run restore-check --image=busybox:1.37 --restart=Never \
--overrides="{\"spec\":{\"nodeSelector\":{\"kubernetes.io/hostname\":\"$HP_NODE\"},\"volumes\":[{\"name\":\"d\",\"persistentVolumeClaim\":{\"claimName\":\"csi-demo-restored\"}}],\"containers\":[{\"name\":\"c\",\"image\":\"busybox:1.37\",\"command\":[\"sh\",\"-c\",\"wc -l /data/orders.txt; sleep 600\"],\"volumeMounts\":[{\"name\":\"d\",\"mountPath\":\"/data\"}]}]}}"
kubectl -n shop wait --for=condition=Ready pod/restore-check --timeout=90s
kubectl -n shop logs restore-check
100 /data/orders.txt
awk 'BEGIN{RS="---\n"} NR==3' snap-restore-clone.yaml | kubectl apply -f -
kubectl -n shop get pvc csi-demo-clone -w # Pending (WFFC) until a consumer exists
kubectl -n shop get pvc
A cloned PVC also follows WFFC, so it is provisioned only after a Pod uses it. Think about it: does the clone contain orders.txt? (No. A clone copies the current state of the source volume.)
volumeSnapshotClassName to csi-azuredisk-vsc and storageClassName to managed-csi, and remove the nodeSelector. Observe the Azure side:
MC=$(az aks show -g rg-k8s-lab -n aks-lab --query nodeResourceGroup -o tsv)
az snapshot list -g $MC --query "[].{name:name,incremental:incremental,sizeGb:diskSizeGB,time:timeCreated}" -o table
Cost: Incremental snapshots are billed by the amount of data that actually changed. After the lab, delete the VolumeSnapshot (deletionPolicy Delete also deletes the Azure snapshot).
kubectl -n shop delete pod csi-user restore-check --ignore-not-found kubectl -n shop delete pvc csi-demo-restored csi-demo-clone --ignore-not-found kubectl -n shop delete vs csi-demo-snap1 kubectl get vsc # deletionPolicy=Delete, the VSC should disappear with it
Case 1: database disk at 90%, expand online
Problem: On Friday night the PostgreSQL PVC reached 90% usage and needs to expand without downtime.
Approach: Confirm the SC has allowVolumeExpansion: true (the built-in AKS SCs all set it to true). Take a snapshot first as a safety net. Run kubectl patch pvc data-db-0 to the new size. Watch the events until you see FileSystemResizeSuccessful. Update volumeClaimTemplates in the GitOps repo so it does not drift (see the orphan rebuild technique in Module 6).
Limits: On Azure Standard/Premium SSD, expanding beyond 4 TiB requires detaching first (scaling to 0). Premium SSD v2 and Ultra support online expansion. Expansion cannot be undone: a disk can only grow, never shrink, so watch the cost.
Case 2: nightly copy of production data for the test environment
Problem: QA needs the latest data, and pg_dump/restore of 300 GB takes 2 hours.
Approach: A CronJob creates a timestamped VolumeSnapshot in the production namespace. A VolumeSnapshot cannot be used directly as a dataSource across namespaces. So a platform job creates a static VolumeSnapshotContent that points to the same snapshotHandle, then creates a VolumeSnapshot in the test namespace that references it (importing a pre-existing snapshot). Next it restores the PVC, and finally runs a data-masking script.
Limits: Requires strict access control (who can read production data). The cross-namespace data source feature is still Alpha, so do not depend on it.
Case 3: consistent snapshots for a multi-volume app
A messaging system kept its data and indexes on two separate disks. Restoring separate snapshots left the indexes out of sync with the data. Switch to VolumeGroupSnapshot (GA in v1.36). Select the two PVCs by label, and the snapshots are taken at the same point in time. Prerequisite: the driver must support group snapshots.
Common errors and fixes
persistentvolumeclaims "x" is forbidden: only dynamically provisioned pvc can be resized and the storageclass that provisions the pvc must support resize
Cause: The SC does not set allowVolumeExpansion: true (for example, kind's standard SC), or the PVC is statically bound and has no SC.
kubectl get sc $(kubectl -n shop get pvc x -o jsonpath='{.spec.storageClassName}') -o jsonpath='{.allowVolumeExpansion}{"\n"}'
Fix: If the driver supports expansion, add allowVolumeExpansion: true to the SC (this field can be changed). local-path does not support expansion, so migrate to a new, larger PVC.
PVC stuck in FileSystemResizePending
Cause: Control-plane expansion is done, and the node is waiting to expand the filesystem. Either no Pod currently mounts the volume (offline expansion), or the node plugin does not support online expansion.
kubectl -n shop get pvc x -o jsonpath='{.status.conditions}' | jq .
kubectl -n shop get pvc x -o jsonpath='{.status.allocatedResourceStatuses}'
Fix: Start a Pod that uses the PVC, or restart an existing Pod. kubelet runs NodeExpandVolume when it mounts the volume.
VolumeSnapshot READYTOUSE stays empty / Failed to check and update snapshot content
Cause: snapshot-controller is not running; the VolumeSnapshotClass does not exist, or its driver does not match the PVC's driver; the CSI driver is missing the csi-snapshotter sidecar; or there is a cloud snapshot quota or permission problem.
kubectl -n shop describe vs NAME | sed -n '/Events/,$p' kubectl -n kube-system logs deploy/snapshot-controller --tail=50 kubectl get vsc -o custom-columns=NAME:.metadata.name,READY:.status.readyToUse,ERR:.status.error.message
clone source pvc ... different storage class / requested size is smaller than source
Cause: Cloning requires the same namespace, the same SC (same driver), and a new PVC size ≥ the source PVC. Restoring from a snapshot requires a size ≥ restoreSize.
Fix: Correct storageClassName and the size, then recreate the PVC.
1. Create a snapshot named db-pre-upgrade for shop/data-db-0 (AKS), and wait until it is ready.
cat <<'EOF' | kubectl apply -f -
apiVersion: snapshot.storage.k8s.io/v1
kind: VolumeSnapshot
metadata: { name: db-pre-upgrade, namespace: shop }
spec:
volumeSnapshotClassName: csi-azuredisk-vsc
source: { persistentVolumeClaimName: data-db-0 }
EOF
kubectl -n shop wait vs/db-pre-upgrade --for=jsonpath='{.status.readyToUse}'=true --timeout=300s2. Check whether the requested capacity and the actual capacity of a PVC match.
kubectl -n shop get pvc data-db-0 -o jsonpath='requested={.spec.resources.requests.storage} actual={.status.capacity.storage}{"\n"}'An operator changed a PVC from 100Gi to 1000Gi (an extra zero) and wants to change it back to 200Gi. What should they do?
If the expansion has already finished (status.capacity=1000Gi), Kubernetes does not support shrinking. You can only: create a new 200Gi PVC, migrate the data with an application-level tool (pg_dump or rsync), switch the workload over, and delete the old PVC. If the expansion has not succeeded yet (for example, because the backend failed), you can lower the request to a smaller value that is still larger than status.capacity. This is how a failed expansion recovers. Prevention: GitOps review, a ValidatingAdmissionPolicy that limits how much one expansion can change, and approval for production PVC changes.
Teaching videos
No verifiable YouTube video specifically on VolumeSnapshot or expansion was found, so the official docs and a storyboard script are provided below.
Official docs
- Volume Snapshots
- CSI Volume Cloning
- v1.36: Moving Volume Group Snapshots to GA (2026-05-08)
- v1.33: Volume Populators Graduate to GA (2025-05-08)
- external-snapshotter releases (v8.7.0)
Video storyboard script
This course file cannot generate the video or MP3 directly, so a storyboard and narration script are provided instead.
Narration: Expansion happens in two steps. First the cloud disk grows. Then the filesystem grows.
Narration: A PVC can only grow. It cannot shrink.
Narration: A snapshot has three objects. Each one matches a PVC, PV, or StorageClass.
Narration: Restoring means using the snapshot as the data source to create a new disk.
Narration: For multi-volume apps, use volume group snapshots, which became GA in the v1.36 release, to keep everything at the same point in time.
Module 6 · StatefulSet + PostgreSQL in practice
- Understand how
volumeClaimTemplatescreates a separate PVC for each replica (data-db-0), and how a Pod that is deleted and recreated rebinds to the same PVC. - Configure
persistentVolumeClaimRetentionPolicy(whenDeleted / whenScaled: Retain or Delete). - Run postgres:17 correctly: PGDATA in a subdirectory (to avoid lost+found), fsGroup and fsGroupChangePolicy, a long enough terminationGracePeriodSeconds, and a fast shutdown.
- Understand that a StatefulSet only provides "stable identity + stable storage". It does not provide replication or failover. In production, use an Operator such as CloudNativePG, or Azure Database for PostgreSQL flexible server.
What: three things a StatefulSet gives a stateful app
- Stable network identity: Pod names
db-0, db-1…plus a headless Service givedb-0.db.shop.svc.cluster.local. - Stable storage: the
datatemplate involumeClaimTemplatescreates a PVCdata-db-<ordinal>for each ordinal. When a Pod is recreated, the StatefulSet controller references the PVC by the same name, so the Pod reattaches to the same disk. - Ordered deployment and updates: the default is
podManagementPolicy: OrderedReady. Pods are created from 0 to N and deleted from N to 0. Rolling updates start from the highest ordinal.
PVC retention policy (GA in v1.32)
| Field | Retain (default) | Delete |
|---|---|---|
whenDeleted (deleting the StatefulSet) | PVC is kept | After the StatefulSet is deleted, the PVCs created from the template are deleted (the PV is then handled by its reclaim policy) |
whenScaled (scaling down) | PVCs of scaled-down replicas are kept and reused when scaling back up | PVCs with an ordinal ≥ the new replica count are deleted |
Under the hood, the controller sets an ownerReference on each PVC (pointing to the StatefulSet or Pod), and the garbage collector deletes it. This only affects PVCs created by volumeClaimTemplates. Production databases usually keep Retain/Retain. A temporary compute cluster can use Delete to save cost.
How: four PostgreSQL pitfalls
| Pitfall | Symptom | Correct approach |
|---|---|---|
| lost+found | An ext4 block device (Azure Disk) has lost+found at the mount root, so initdb reports "directory exists but is not empty" | Mount at /var/lib/postgresql/data and set PGDATA=/var/lib/postgresql/data/pgdata (a subdirectory) |
| Permissions | Running as non-root gives Permission denied; or recursively chowning many files on every start, which is very slow | securityContext.fsGroup: 999 (the postgres image user) + fsGroupChangePolicy: OnRootMismatch. Whether this takes effect depends on the CSIDriver's fsGroupPolicy. hostPath and local-path do not change ownership, but the directory is 0777. |
| Graceful shutdown | If the database has not stopped within the default 30-second grace period, it gets SIGKILL. On restart it must run crash recovery (WAL replay), so large databases start slowly. | terminationGracePeriodSeconds: 120, and a preStop hook that runs pg_ctl stop -m fast |
| Multiple replicas ≠ high availability | Change replicas to 3 and you get three unrelated, empty databases | Streaming replication needs extra setup (primary_conninfo, replication slots, failover). Use an Operator. |
Note: the postgres 18 image moved the default PGDATA to a versioned directory and recommends mounting /var/lib/postgresql. This hour uses postgres:17, with the path /var/lib/postgresql/data. Read the image documentation before upgrading major versions.
When: self-managed vs. Operator vs. managed service
| Option | Best for | You are responsible for |
|---|---|---|
| Plain StatefulSet (this hour) | Learning, development, single-instance non-critical data | Backups, upgrades, monitoring, and failover, all by hand |
| CloudNativePG (CNCF project, current version v1.30.1, 2026-09-23) | Running production PostgreSQL in Kubernetes, with consistent environments | The Operator handles replication, automatic failover, rolling upgrades, backups to object storage (Barman Cloud plugin), and PITR. You handle capacity and Operator upgrades. |
| Azure Database for PostgreSQL flexible server | Most production workloads, where the team does not want to run a database | You only manage connections and parameters. Azure provides zone-redundant HA, automatic backups, and PITR. Access is through Private Endpoint or VNet integration. |
Diagram: object relationships in shop/db
Flowchart: what happens to the PVCs when scaling to 0 and back up
Interactive simulator: binding between StatefulSet replicas and PVCs
Choose a retention policy first, then run the operations. Green = Running, yellow = Pending/creating, blue = newly created, red = deleting. The log shows the real actions of the StatefulSet controller and GC.
Core commands
| Command | Purpose | Notes |
|---|---|---|
kubectl -n shop scale sts db --replicas=N | Scaling | OrderedReady: one at a time |
kubectl -n shop rollout status sts db | Wait for the update or scaling to finish | Common in CI |
kubectl -n shop get pvc -l app=db | List the PVCs created from the template | PVCs inherit the labels from the template's metadata.labels and selector labels |
kubectl -n shop delete sts db --cascade=orphan | Delete the StatefulSet but keep its Pods | Use after changing an immutable field (such as storage in the template), to rebuild |
kubectl -n shop exec -it db-0 -- psql -U shop -d shop | Open a shell in the database | Verify the data |
kubectl -n shop get pvc data-db-0 -o jsonpath='{.metadata.ownerReferences}' | Check the owner set by the retention policy | With the Delete policy, you see the StatefulSet/Pod owner |
Full manifest db.yaml (Secret + headless Service + StatefulSet)
apiVersion: v1
kind: Secret
metadata: { name: db-secret, namespace: shop }
type: Opaque
stringData:
POSTGRES_USER: shop
POSTGRES_DB: shop
POSTGRES_PASSWORD: change-me-in-hour5 # For the lab only; in hour 5, switch to external secret management
---
apiVersion: v1
kind: Service
metadata: { name: db, namespace: shop, labels: { app: db } }
spec:
clusterIP: None # headless: gives each Pod a DNS record
selector: { app: db }
ports: [{ name: pg, port: 5432, targetPort: pg }]
---
apiVersion: apps/v1
kind: StatefulSet
metadata: { name: db, namespace: shop }
spec:
serviceName: db
replicas: 1
selector: { matchLabels: { app: db } }
persistentVolumeClaimRetentionPolicy:
whenDeleted: Retain
whenScaled: Retain
template:
metadata: { labels: { app: db } }
spec:
nodeSelector: __NODESEL__
terminationGracePeriodSeconds: 120
securityContext:
runAsUser: 999
runAsGroup: 999
runAsNonRoot: true
fsGroup: 999
fsGroupChangePolicy: OnRootMismatch
initContainers:
# Fallback: not every volume type changes ownership based on fsGroup (hostPath PVs, drivers with fsGroupPolicy=None)
- name: fix-perms
image: busybox:1.37
securityContext: { runAsUser: 0, runAsNonRoot: false }
command: ["sh","-c","mkdir -p /data/pgdata /data/dumps && chown 999:999 /data/pgdata /data/dumps && chmod 700 /data/pgdata"]
volumeMounts: [{ name: data, mountPath: /data }]
containers:
- name: postgres
image: postgres:17
ports: [{ name: pg, containerPort: 5432 }]
envFrom: [{ secretRef: { name: db-secret } }]
env:
- { name: PGDATA, value: /var/lib/postgresql/data/pgdata } # subdirectory, to avoid lost+found
resources:
requests: { cpu: 100m, memory: 256Mi }
limits: { memory: 512Mi }
readinessProbe:
exec: { command: ["sh","-c","pg_isready -U \"$POSTGRES_USER\" -d \"$POSTGRES_DB\" -h 127.0.0.1"] }
periodSeconds: 5
livenessProbe:
exec: { command: ["sh","-c","pg_isready -U \"$POSTGRES_USER\" -h 127.0.0.1"] }
initialDelaySeconds: 30
periodSeconds: 10
lifecycle:
preStop:
exec: { command: ["sh","-c","pg_ctl -D \"$PGDATA\" -m fast -w -t 100 stop"] }
volumeMounts:
- { name: data, mountPath: /var/lib/postgresql/data }
volumeClaimTemplates:
- metadata:
name: data
labels: { app: db }
spec:
accessModes: ["ReadWriteOnce"]
storageClassName: __SC__
resources: { requests: { storage: 1Gi } }
__SC__ and __NODESEL__ are placeholders, replaced with sed. For the kind default route, use SC=standard NODESEL='{}'. For the kind hostpath route, use SC=hostpath-csi NODESEL="{kubernetes.io/hostname: $HP_NODE}". For the AKS route, use SC=managed-csi NODESEL='{}'.
SC=standard; NODESEL='{}'
sed -e "s#__SC__#$SC#" -e "s#__NODESEL__#$NODESEL#" db.yaml | kubectl apply -f -
kubectl -n shop rollout status sts db --timeout=180s
kubectl -n shop get sts,pod,pvc -l app=db
statefulset rolling update complete 1 pods at revision db-7c9d5b6f8d... NAME READY AGE statefulset.apps/db 1/1 45s NAME READY STATUS RESTARTS AGE pod/db-0 1/1 Running 0 45s NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS AGE persistentvolumeclaim/data-db-0 Bound pvc-5d0c… 1Gi RWO standard 45s
How to verify: kubectl -n shop exec db-0 -- ls -la /var/lib/postgresql/data should show the pgdata subdirectory (owned by postgres, permissions drwx------). Common error: if the hour 2 db used different volumeClaimTemplates, kubectl apply reports Forbidden (templates are immutable). First run kubectl -n shop delete sts db (PVCs are kept by default). Production use: this manifest is the basis for understanding an Operator. For production, use CloudNativePG or a managed service.
Operator approach (CloudNativePG, for reference)
# Follow the official Installation docs at cloudnative-pg.io for the install method (version 1.30.x)
kubectl apply --server-side -f \
https://raw.githubusercontent.com/cloudnative-pg/cloudnative-pg/release-1.30/releases/cnpg-1.30.1.yaml
cat <<'EOF' | kubectl apply -f -
apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata: { name: shop-pg, namespace: shop }
spec:
instances: 3 # 1 primary, 2 standbys, automatic failover
storage: { size: 10Gi, storageClass: managed-csi-premium }
walStorage: { size: 4Gi, storageClass: managed-csi-premium }
EOF
kubectl -n shop get cluster shop-pg
Lab 6: write → delete Pod → scale to 0 → scale up → expand PVC (about 10 minutes)
~/k8slab/hour4/db.yaml. If the hour 2 db already exists:
cd ~/k8slab/hour4
kubectl -n shop delete sts db --ignore-not-found # PVC is kept by default
# To start from a clean state (this discards the hour 2 data):kubectl -n shop delete pvc data-db-0 --ignore-not-found
SC=standard; NODESEL='{}' # AKS: SC=managed-csi
sed -e "s#__SC__#$SC#" -e "s#__NODESEL__#$NODESEL#" db.yaml | kubectl apply -f -
kubectl -n shop rollout status sts db --timeout=180skubectl -n shop exec -i db-0 -- psql -U shop -d shop -v ON_ERROR_STOP=1 <<'SQL' CREATE TABLE IF NOT EXISTS orders (id serial PRIMARY KEY, item text, created_at timestamptz DEFAULT now()); INSERT INTO orders (item) SELECT 'item-' || g FROM generate_series(1,1000) g; SELECT count(*) FROM orders; SQL
CREATE TABLE INSERT 0 1000 count ------- 1000 (1 row)
PV_BEFORE=$(kubectl -n shop get pvc data-db-0 -o jsonpath='{.spec.volumeName}')
time kubectl -n shop delete pod db-0
kubectl -n shop wait --for=condition=Ready pod/db-0 --timeout=120s
kubectl -n shop exec db-0 -- psql -U shop -d shop -tAc 'SELECT count(*) FROM orders'
[ "$PV_BEFORE" = "$(kubectl -n shop get pvc data-db-0 -o jsonpath='{.spec.volumeName}')" ] && echo "same PV ✓"
kubectl -n shop logs db-0 --previous 2>/dev/null | tail -3 || kubectl -n shop logs db-0 | head -5
pod "db-0" deleted real 0m3.2s 1000 same PV ✓
The new Pod log should not contain "database system was not properly shut down; automatic recovery in progress". If it does, the database was killed with SIGKILL during shutdown. Check the grace period and the preStop hook.
kubectl -n shop scale sts db --replicas=2 && kubectl -n shop rollout status sts db kubectl -n shop get pvc -l app=db kubectl -n shop scale sts db --replicas=0 kubectl -n shop wait --for=delete pod -l app=db --timeout=180s kubectl -n shop get pvc -l app=db # both PVCs are kept (whenScaled: Retain) kubectl -n shop scale sts db --replicas=1 && kubectl -n shop rollout status sts db kubectl -n shop exec db-0 -- psql -U shop -d shop -tAc 'SELECT count(*) FROM orders'
NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS AGE data-db-0 Bound pvc-5d0c… 1Gi RWO standard 12m data-db-1 Bound pvc-8e4a… 1Gi RWO standard 30s … 1000
Note: db-1 is an independent, empty database, not a replica of db-0! StatefulSet does not set up replication for you. After the lab, delete the extra PVC: kubectl -n shop delete pvc data-db-1.
kubectl -n shop patch pvc data-db-0 -p '{"spec":{"resources":{"requests":{"storage":"2Gi"}}}}'
Error from server (Forbidden): persistentvolumeclaims "data-db-0" is forbidden: only dynamically provisioned pvc can be resized and the storageclass that provisions the pvc must support resize
kubectl -n shop patch pvc data-db-0 -p '{"spec":{"resources":{"requests":{"storage":"2Gi"}}}}'
kubectl -n shop wait pvc/data-db-0 --for=jsonpath='{.status.capacity.storage}'=2Gi --timeout=300s
kubectl -n shop exec db-0 -- df -h /var/lib/postgresql/data
# Make the template match the actual size (the approach when template fields are immutable):
kubectl -n shop delete sts db --cascade=orphan
sed -e "s#__SC__#$SC#" -e "s#__NODESEL__#$NODESEL#" -e 's#storage: 1Gi#storage: 2Gi#' db.yaml | kubectl apply -f -
kubectl -n shop get pod db-0 -o jsonpath='{.metadata.ownerReferences[0].name}{"\n"}' # the new StatefulSet takes over the Pod again
persistentvolumeclaim/data-db-0 condition met Filesystem Size Used Avail Use% Mounted on /dev/sdc 2.0G 60M 1.9G 4% /var/lib/postgresql/data statefulset.apps "db" deleted statefulset.apps/db created db
If your cluster allows changing storage in volumeClaimTemplates directly (this depends on the version and feature gates, so check the official docs), you do not need the orphan rebuild.
kubectl -n shop delete pvc data-db-1 --ignore-not-found.Case 1: slower database restarts during node maintenance
Problem: During an AKS node upgrade, db-0 was evicted, and the new Pod took 8 minutes to start. The log showed "automatic recovery in progress".
Approach: The default grace period is 30 seconds. SIGTERM triggers a smart shutdown that waits for connections to close, and SIGKILL follows if that times out. Change it to terminationGracePeriodSeconds: 120 plus a preStop pg_ctl -m fast, and add a PodDisruptionBudget. With a single replica, maxUnavailable: 0 blocks drain, so coordinate it with the maintenance window.
Limits: A long grace period slows node upgrades. AKS node upgrades have their own drain timeout settings.
Case 2: recursive fsGroup chown causes a startup timeout
Problem: A volume of 500 GB with millions of files: on every Pod start, kubelet recursively changes ownership. Startup took 20 minutes and triggered a liveness failure loop.
Approach: Use fsGroupChangePolicy: OnRootMismatch, which skips the recursion when the root directory already has the right owner. In v1.37, SELinuxMount is enabled by default. On SELinux systems, labels are applied with a mount option, which avoids a recursive relabel.
Case 3: migrating from a self-managed StatefulSet to managed PostgreSQL
Problem: Within half a year, the team restored the database twice after mistakes. The manual effort was high.
Approach: Migrate to Azure Database for PostgreSQL flexible server (zone-redundant HA, automatic backups, PITR). Apps reach it through a Private Endpoint. In K8s, keep only an ExternalName Service, or set the connection string directly. Authenticate with workload identity (Microsoft Entra). Keep the StatefulSet approach for development environments.
Limits: Extensions and version choices on managed services are limited. Cross-VNet network planning is needed. The cost model is different.
Common errors and fixes
initdb: error: directory "/var/lib/postgresql/data" exists but is not empty ... It contains a lost+found directory
Cause: The ext4 block device has lost+found at its root, and PGDATA points to the volume root.
Fix: Set PGDATA=/var/lib/postgresql/data/pgdata, or mount with subPath: pgdata.
chmod: changing permissions of '/var/lib/postgresql/data/pgdata': Operation not permitted / could not change permissions of directory
Cause: The container runs as uid 999, but the volume root is owned by root and there is no fsGroup. Or the CSIDriver's fsGroupPolicy is None, so ownership is not changed. Or the NFS/SMB backend does not support chmod/chown (Azure Files SMB needs the uid/gid mount options).
kubectl -n shop exec db-0 -- ls -ldn /var/lib/postgresql/data kubectl get csidriver -o custom-columns=NAME:.metadata.name,FSGROUP:.spec.fsGroupPolicy
Fix: Add securityContext.fsGroup: 999. Do not put the database on Azure Files SMB.
Forbidden: updates to statefulset spec for fields other than 'replicas', 'ordinals', 'template', 'updateStrategy', 'persistentVolumeClaimRetentionPolicy' and 'minReadySeconds' are forbidden
Cause: You changed immutable fields such as volumeClaimTemplates, serviceName, or selector (the wording varies slightly between versions).
kubectl -n shop delete sts db --cascade=orphan # Pods and PVCs are kept kubectl apply -f db-new.yaml # the new StatefulSet adopts the existing Pods by label
For expansion, patch each PVC one at a time first, then rebuild with orphan to sync the template.
db-0 stuck in Terminating / no new db-0 after the node became NotReady
Cause: A StatefulSet guarantees "at most one": it does not create a new Pod until the API confirms the old Pod has stopped. When a node is unreachable, the state of the old Pod is unknown.
kubectl get node NODE # After confirming the node is shut down, add the out-of-service taint so the control plane force-deletes the Pods and detaches the volumes kubectl taint nodes NODE node.kubernetes.io/out-of-service=nodeshutdown:NoExecute
Do not use --force --grace-period=0 unless you have confirmed the node is shut down. Otherwise two instances may write to the same disk at once (see Module 8).
1. Change the PVC retention policy of the StatefulSet db to "delete PVCs when the StatefulSet is deleted, keep them on scale-down".
kubectl -n shop patch sts db --type merge -p '{"spec":{"persistentVolumeClaimRetentionPolicy":{"whenDeleted":"Delete","whenScaled":"Retain"}}}'2. Without entering the interactive psql, query the row count of the orders table.
kubectl -n shop exec db-0 -- psql -U shop -d shop -tAc 'SELECT count(*) FROM orders'
A product manager asks for "a highly available database", and a colleague changes the StatefulSet replicas to 3. What happens? What would you propose?
You get two independent, empty PostgreSQL instances (db-1 and db-2). The db Service load-balances connections across all three, so the app reads and writes to different databases, and data "randomly disappears". Correct approach: (1) a managed service (Azure Database for PostgreSQL flexible server, zone-redundant HA); (2) in K8s, CloudNativePG (instances: 3, automatic streaming replication and failover, with -rw/-ro Services); (3) combined with zone spreading, a PDB, backups to object storage, and PITR. A StatefulSet only provides identity and storage.
Verified teaching videos
Official docs
- StatefulSets (PVC retention policy Stable v1.32)
- fsGroupChangePolicy
- postgres official image docs (PGDATA)
- CloudNativePG docs
- Azure Database for PostgreSQL flexible server
Video storyboard script
This course file cannot generate the video or MP3 directly, so a storyboard and narration script are provided instead.
Narration: A StatefulSet gives each replica a fixed name and a fixed disk.
Narration: The Pod name decides the PVC name, so the recreated Pod reattaches to the same disk.
Narration: The retention policy, released in the v1.32 release, decides whether PVCs are kept or deleted on scale-down and delete.
Narration: PostgreSQL's data directory has to be in a subdirectory.
Narration: Multiple replicas do not mean high availability. For production, use an Operator or a managed database.
Module 7 · Backup and restore (Velero)
- Tell apart three kinds of backup: etcd snapshots (cluster state), application-level logical backups (pg_dump), and volume-level backups (CSI snapshots or file-system backup). Know what each one can restore.
- Understand the Velero architecture: Backup / Restore / Schedule CRDs, BackupStorageLocation, VolumeSnapshotLocation, CSI snapshots and data movement, node-agent (Kopia) file-system backup, and hooks.
- Do this in kind + MinIO:
velero install→velero backup create --include-namespaces shop→ delete the namespace →velero restore create --from-backup→ verify the row count. - Learn about Azure Backup for AKS, the managed option on AKS.
What: what to back up and what you can restore
| Method | Contents | Can restore | Cannot restore / notes |
|---|---|---|---|
etcd snapshot (etcdctl snapshot save) | API objects for the whole cluster | Roll back the whole control plane (self-managed clusters) | Does not include PV data; all or nothing. On AKS the control plane is managed by the platform, so users cannot access etcd directly. |
| Velero resource backup | API objects selected by namespace or label (packaged as JSON in object storage) | Namespace-level accidental deletion, migration to another cluster | Data restore also needs a volume backup |
| CSI snapshot (called by Velero) | Snapshot of a volume (in the cloud) | Fast volume restore | The snapshot is in the same region and subscription as the source. On its own, it does not protect against region-level or subscription-level incidents. |
CSI snapshot + data movement (--snapshot-move-data) | Upload the snapshot contents to object storage using Kopia | Cross-cluster or cross-region restore | Needs node-agent; time scales with data size |
| File-system backup (node-agent + Kopia) | Reads from the Pod volume directory and uploads | Any volume that does not support snapshots (NFS, Azure Files, etc.) | hostPath volumes are not supported (kind local-path creates hostPath PVs); an online copy is not guaranteed to be consistent |
| Application-level backup (pg_dump / pg_basebackup) | Database logical or physical backup | Transaction-consistent, works across versions | Needs orchestration (Velero hooks, CronJob, Operator) |
Why: why you need Velero
A VolumeSnapshot only covers the volume. It does not include the Deployment, Service, Secret, ConfigMap, or RBAC. It also does not protect the snapshot objects themselves when the namespace is deleted, because VolumeSnapshots are namespaced resources. Velero packages resources + volumes into one portable backup, stores it in object storage outside the cluster, and can run on a schedule with a retention period (TTL).
How: Velero architecture
- velero server (Deployment, in the velero namespace): watches Backup/Restore/Schedule CRs, runs the backup logic, and talks to object storage and snapshot APIs through plugins.
- BackupStorageLocation (BSL): the object storage bucket that holds resource JSON, logs, and the Kopia repository (S3, Azure Blob, or GCS; MinIO is S3-compatible).
- VolumeSnapshotLocation (VSL): the snapshot location for cloud-native snapshot plugins (non-CSI). With CSI snapshots, the VolumeSnapshotClass decides, and you must add the label
velero.io/csi-volumesnapshot-class: "true"to the VSC. - node-agent (DaemonSet): runs file-system backup and restore, and CSI snapshot data movement (Kopia uploader; the Restic path was fully removed starting in v1.19).
- Hook: runs a command in the specified container before or after the backup (set through Pod annotations such as
pre.hook.backup.velero.io/command). During restore, it can run init or exec hooks. - Restore order: CRDs, namespaces, and PV/PVCs are restored first, then the workloads. For file-system restore, Velero injects a
restore-waitinit container into the Pod, which waits for node-agent to write the data back before the app starts.
When: choosing an option
| Scenario | Recommended |
|---|---|
| AKS, and you want it managed and unified with the Azure Backup center | Azure Backup for AKS (Backup vault + in-cluster backup extension, supports Azure Disk CSI snapshots and the vault tier; check Microsoft Learn for details) |
| Multi-cloud, on-premises, or you need full control | Velero (open source) + object storage |
| Database | Mainly application-level backups (CloudNativePG's object storage backups + PITR, or the managed database's own backups), with volume or cluster backups as a supplement |
Diagram: Velero components
Flowchart: backup → disaster → restore
Step-by-step animation: Velero backup and restore flow
Uses file-system backup (node-agent + Kopia) as the example. Each step shows the actual objects and logs.
Core commands
| Command | Purpose | Key flags |
|---|---|---|
velero install … | Install CRDs, the server, node-agent, and the BSL | --provider, --plugins, --bucket, --use-node-agent, --default-volumes-to-fs-backup, --features=EnableCSI |
velero backup-location get | BSL status | PHASE should be Available |
velero backup create NAME --include-namespaces shop --wait | Back up a namespace | --snapshot-move-data, --ttl 72h, -l app=db |
velero backup describe NAME --details / logs | View results, volume backups, hooks | Phase: Completed / PartiallyFailed |
velero restore create --from-backup NAME --wait | Restore | --namespace-mappings shop:shop-restore, --include-resources |
velero schedule create NAME --schedule="0 2 * * *" --include-namespaces shop --ttl 168h | Scheduled backup | cron expression (UTC) |
Hook: pre-backup pg_dump (writes to a volume that gets backed up)
kubectl -n shop patch sts db --type merge -p '{"spec":{"template":{"metadata":{"annotations":{
"pre.hook.backup.velero.io/container":"postgres",
"pre.hook.backup.velero.io/command":"[\"/bin/sh\",\"-c\",\"pg_dump -U \\\"$POSTGRES_USER\\\" -d \\\"$POSTGRES_DB\\\" -Fc -f /var/lib/postgresql/data/dumps/shop.dump\"]",
"pre.hook.backup.velero.io/timeout":"3m",
"pre.hook.backup.velero.io/on-error":"Fail"}}}}}'
kubectl -n shop rollout status sts db
Changing a Pod template annotation triggers a rebuild of db-0 (a rolling update). The hook runs in the container with exec, and the environment variables come from the container itself. You can also write it as YAML directly in template.metadata.annotations in db.yaml, which is easier to read.
CSI snapshot + data movement (AKS or hostpath CSI)
# Tell Velero which VolumeSnapshotClass to use kubectl label volumesnapshotclass csi-hostpath-snapclass velero.io/csi-volumesnapshot-class=true # AKS: csi-azuredisk-vsc velero backup create shop-csi-1 --include-namespaces shop --snapshot-move-data --wait velero backup describe shop-csi-1 --details | sed -n '/CSI Snapshots/,/^$/p'
Install with --features=EnableCSI. Since v1.14, CSI support is built into Velero itself, but it is still turned on with a feature flag. Check the velero.io docs for details.
Lab 7: back up shop in kind + MinIO → delete the namespace → restore (about 12 minutes)
cd ~/k8slab/hour4
kubectl -n shop exec db-0 -- sh -c 'pg_dump -U "$POSTGRES_USER" -d "$POSTGRES_DB" -Fc' > shop-migrate.dump
ls -lh shop-migrate.dump
kubectl -n shop delete sts db
kubectl -n shop delete pvc -l app=db
HP_NODE=$(kubectl get pod csi-hostpathplugin-0 -o jsonpath='{.spec.nodeName}')
SC=hostpath-csi; NODESEL="{kubernetes.io/hostname: $HP_NODE}"
sed -e "s#__SC__#$SC#" -e "s#__NODESEL__#$NODESEL#" db.yaml | kubectl apply -f -
kubectl -n shop rollout status sts db --timeout=180s
kubectl -n shop exec -i db-0 -- sh -c 'pg_restore -U "$POSTGRES_USER" -d "$POSTGRES_DB" --no-owner' < shop-migrate.dump
kubectl -n shop exec db-0 -- psql -U shop -d shop -tAc 'SELECT count(*) FROM orders'
kubectl -n shop get pvc data-db-0
-rw-r--r-- 1 azureuser azureuser 21K Nov 15 04:10 shop-migrate.dump … 1000 NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS AGE data-db-0 Bound pvc-c41a… 1Gi RWO hostpath-csi 40s
VV=v1.18.4 curl -fsSLO https://github.com/vmware-tanzu/velero/releases/download/$VV/velero-$VV-linux-amd64.tar.gz tar xzf velero-$VV-linux-amd64.tar.gz && sudo mv velero-$VV-linux-amd64/velero /usr/local/bin/ velero version --client-only kubectl apply -f https://raw.githubusercontent.com/vmware-tanzu/velero/$VV/examples/minio/00-minio-deployment.yaml kubectl -n velero rollout status deploy/minio --timeout=180s kubectl -n velero get pods
Client: Version: v1.18.4 deployment "minio" successfully rolled out NAME READY STATUS RESTARTS AGE minio-6b8f… 1/1 Running 0 40s minio-setup-xxxxx 0/1 Completed 0 40s
The sample manifest creates the velero namespace, MinIO (credentials minio/minio123), and a bucket named velero. The way MinIO Community Edition is distributed has changed in recent years. If the sample image fails to pull, use any S3-compatible implementation, or on AKS use Azure Blob (velero-plugin-for-microsoft-azure) instead.
cat > credentials-velero <<'EOF' [default] aws_access_key_id = minio aws_secret_access_key = minio123 EOF velero install \ --provider aws \ --plugins velero/velero-plugin-for-aws:v1.14.4 \ --bucket velero \ --secret-file ./credentials-velero \ --use-volume-snapshots=false \ --backup-location-config region=minio,s3ForcePathStyle="true",s3Url=http://minio.velero.svc:9000 \ --use-node-agent \ --default-volumes-to-fs-backup \ --features=EnableCSI \ --wait velero backup-location get kubectl -n velero get ds node-agent
Velero is installed! ⛵ Use 'kubectl logs deployment/velero -n velero' to view the status. NAME PROVIDER BUCKET/PREFIX PHASE LAST VALIDATED ACCESS MODE DEFAULT default aws velero Available 2026-11-15 04:20:11 +0000 UTC ReadWrite true NAME DESIRED CURRENT READY UP-TO-DATE AVAILABLE NODE SELECTOR AGE node-agent 3 3 3 3 3 <none> 60s
kubectl -n shop exec db-0 -- psql -U shop -d shop -tAc 'SELECT count(*) FROM orders' | tee rows-before.txt velero backup create shop-b1 --include-namespaces shop --wait velero backup describe shop-b1 --details | grep -E 'Phase|Items backed up|Pod Volume Backups' -A3 | head -20
1000
Backup request "shop-b1" submitted successfully.
Waiting for backup to complete. ........
Backup completed with status: Completed.
Phase: Completed
Items backed up: 47
Pod Volume Backups - kopia:
Completed:
shop/db-0: data
velero backup logs shop-b1 | grep -i hook | head kubectl -n velero exec deploy/minio -- ls /storage/velero/backups/shop-b1 2>/dev/null || true
The hook log should show that pg_dump ran successfully. The path in MinIO depends on the data directory in the sample manifest, so check the actual location.
kubectl delete ns shop --wait kubectl get pv | grep shop/ || echo "all shop PVs have been deleted"
velero restore create shop-r1 --from-backup shop-b1 --wait velero restore describe shop-r1 --details | grep -E 'Phase|Pod Volume Restores' -A3 kubectl -n shop get pods,pvc kubectl -n shop wait --for=condition=Ready pod/db-0 --timeout=300s kubectl -n shop exec db-0 -- psql -U shop -d shop -tAc 'SELECT count(*) FROM orders' | tee rows-after.txt diff rows-before.txt rows-after.txt && echo "row counts match ✓"
Restore completed with status: Completed.
Phase: Completed
Pod Volume Restores:
Completed:
shop/db-0: data
NAME READY STATUS RESTARTS AGE
pod/db-0 1/1 Running 0 70s
…
1000
row counts match ✓
If the data directory restores but the database cannot start (the extreme case where the online file copy is inconsistent), run pg_restore on /var/lib/postgresql/data/dumps/shop.dump, which the hook produced. This is the point of a "two-layer backup".
velero schedule create shop-daily --schedule="0 2 * * *" --include-namespaces shop --ttl 168h0m0s velero schedule get # After the lab (you can also keep velero for the capstone lab): # velero schedule delete shop-daily --confirm; velero backup delete shop-b1 --confirm # velero uninstall --force; kubectl delete ns velero
Case 1: recovering in 15 minutes after an accidental namespace deletion
Problem: The cleanup script in the CI pipeline had an empty variable, so it ran kubectl delete ns $NS, which deleted the production namespace.
Approach: A Velero schedule runs every hour (resources + CSI snapshot data movement to Blob in another region). To recover: velero restore create --from-schedule shop-hourly. RPO 1 hour, RTO 15 minutes. Follow-up hardening: RBAC that stops CI from deleting namespaces, and a ValidatingAdmissionPolicy that requires a second confirmation before a namespace with a protection label can be deleted.
Limits: During recovery, external dependencies (DNS, certificates, external Secrets) must be verified separately.
Case 2: Azure Backup for AKS
Problem: The company requires all backups to be managed in the Backup center, with a vault tier (immutable) and cross-region restore.
Approach: Create a Backup vault, install the backup extension in the cluster, and configure trusted access. The backup policy includes Azure Disk CSI snapshots (operational tier) and the vault tier. Restore can target the same or another AKS cluster. For the supported volume types, regions, and commands, follow the Microsoft Learn document "Azure Kubernetes Service backup".
Limits: The managed service charges for protected instances and storage. Check the feature boundaries (such as Azure Files support) against the docs.
Case 3: cluster migration (1.3x → new cluster)
Use Velero to move a namespace from an old AKS cluster to a new one. Both clusters configure the same BSL (the new cluster is read-only with --access-mode ReadOnly). Run the restore on the new cluster. Use --namespace-mappings to restore into a shadow namespace first and verify it, then switch DNS.
Common errors and fixes
BackupStorageLocation "default" is unavailable: rpc error: ... NoSuchBucket / connection refused
Cause: The bucket does not exist, s3Url is wrong (in-cluster DNS name minio.velero.svc:9000), the credentials are wrong, or Azure Blob network rules are blocking access.
velero backup-location get kubectl -n velero logs deploy/velero | grep -i -E 'error|bucket' | tail kubectl -n velero run s3check --rm -it --image=busybox:1.37 --restart=Never -- wget -qO- http://minio.velero.svc:9000/minio/health/live; echo $?
Backup PartiallyFailed: pod volume backup failed: ... hostPath volume not supported
Cause: File-system backup does not support hostPath volumes (the PV type kind local-path uses).
Fix: Put the data on a CSI volume (step 1 of this module's lab), or use application-level backup instead. For production cloud disks, use CSI snapshots + data movement.
Pod stuck at Init:0/1 after restore (restore-wait)
Cause: node-agent is not running on the node where the Pod is, or the PodVolumeRestore failed (repository password or connection problem).
kubectl -n velero get podvolumerestores -o custom-columns=NAME:.metadata.name,POD:.spec.pod.name,PHASE:.status.phase,MSG:.status.message kubectl -n velero logs ds/node-agent --tail=50
Hook fails: command terminated with exit code 1 (pg_dump: error: could not open output file)
Cause: The output directory does not exist or is not writable, the container name is wrong, or the hook timed out.
Fix: Make sure the init container creates the dumps directory and owns it as uid 999. Set pre.hook.backup.velero.io/container to the correct container name, and increase the timeout if needed. on-error: Fail makes the backup fail, so you get an alert.
1. Restore backup shop-b1 into a new namespace, shop-verify, for a drill, without affecting the existing shop.
velero restore create shop-verify-1 --from-backup shop-b1 --namespace-mappings shop:shop-verify --wait kubectl -n shop-verify get pods
Note that constraints like hostPath/local volumes and nodeSelector are restored too.
2. Create a schedule that runs every 6 hours, keeps backups for 3 days, and only backs up resources labeled app=db.
velero schedule create db-6h --schedule="0 */6 * * *" --include-namespaces shop -l app=db --ttl 72h0m0s
An audit finds that Velero's BSL is a MinIO inside the same AKS cluster, and the VolumeSnapshots are only in this region. Point out the risks and suggest improvements.
Risks: if the cluster is deleted, the region fails, or the subscription is compromised, backups and production are lost together. Snapshots are in the same region and subscription as the source. Improvements: move the BSL to Azure Blob in another region (ideally another subscription), with versioning, immutable storage, and soft delete enabled. Use --snapshot-move-data to move volume data to the BSL. Use least-privilege access through a managed identity. Run regular restore drills in an isolated cluster and verify the data. Add application-level backups for the database, or use the managed database's cross-region backups. You can also evaluate the vault tier of Azure Backup for AKS.
Teaching videos
A catalog page for videos such as Rawkode Academy's "Hands-on Introduction to Velero - Backup and Restore for Kubernetes" (about 1 hour 12 minutes) was found, but their YouTube video IDs could not be verified, so no links are listed (no verified video found). You can search YouTube for that title.
Official docs
- Velero docs (File System Backup, CSI Snapshot Data Movement, Backup Hooks)
- Velero releases (v1.18.4; v1.19.0-rc.1)
- velero-plugin-for-aws releases (v1.14.4)
- Azure Backup for AKS overview
Video storyboard script
This course file cannot generate the video or MP3 directly, so a storyboard and narration script are provided instead.
Narration: A backup is not a single button. It is a combination of three methods.
Narration: First, the hook makes a transaction-consistent export. Then the resources and volumes are backed up.
Narration: File-system backup is done by node-agent on each node. Remember that it does not support hostPath volumes.
Narration: A backup only proves its value through a restore drill.
Module 8 · Storage troubleshooting
- Troubleshoot by following the object chain: PVC events → Pod events → PV / VolumeAttachment → CSINode → driver and kubelet logs.
- Identify and fix: PVC Pending (no default SC, normal WFFC waiting, quota, or topology mismatch), Multi-Attach error, FailedAttachVolume / FailedMount timeouts, Permission denied, full volumes, node volume count limits, Released PVs that cannot rebind, and deletions stuck on finalizers.
- Understand the timeline for detaching volumes after a node failure, and the role of the out-of-service taint.
- Use the interactive troubleshooting decision tree to locate problems quickly.
What: which layer a storage problem appears in
| Layer | Typical symptom | First command | Responsible component |
|---|---|---|---|
| Provisioning / binding | PVC Pending | kubectl describe pvc | PV controller, external-provisioner, scheduler |
| Scheduling | Pod Pending: volume node affinity conflict, exceed max volume count, RWOP conflict | kubectl describe pod | kube-scheduler |
| Attach | Multi-Attach error, FailedAttachVolume, AttachVolume.Attach failed | kubectl get volumeattachment | AD controller, external-attacher, cloud API |
| Mount | FailedMount, timed out waiting for the condition, MountVolume.MountDevice failed | Pod events + kubelet logs | kubelet, CSI node plugin |
| Runtime | Permission denied, No space left on device, Read-only file system | kubectl exec … df -h; ls -ln | Application, fsGroup, filesystem |
| Deletion / reclaim | Stuck in Terminating, stuck Released (can't rebind), orphaned cloud disks | kubectl get pvc,pv -o yaml | grep -A3 finalizers | protection controller, provisioner |
Why: node failures and Multi-Attach
An RWO disk can only attach to one VM at a time. When a node suddenly becomes unreachable, the API cannot tell whether the old Pod is still writing to the disk. To prevent data corruption, Kubernetes by default does not mount the volume on a new node right away:
- The node is NotReady (about 40 seconds), then about 5 minutes later (the default tolerationSeconds 300), the node lifecycle controller evicts the Pod. The Pod enters Terminating, but kubelet cannot confirm the deletion.
- A Deployment immediately creates a new Pod (with a new name). When the new Pod is scheduled to a healthy node, it reports
Multi-Attach error for volume … Volume is already exclusively attached to one node and can't be attached to another. A StatefulSet does not create a Pod with the same name until the old Pod's deletion is confirmed. - After the Pod is deleted, the AD controller waits for
maxWaitForUnmountDuration(about 6 minutes) before forcing a detach. The kube-controller-manager flag--disable-force-detach-on-timeoutcan turn this off. Check the official docs for details. - Faster and safer approach: after confirming the node is shut down (or the VM is stopped), add the
node.kubernetes.io/out-of-service=nodeshutdown:NoExecutetaint to the node (GA in v1.28). Pods are force-deleted and volumes are detached immediately. Remove the taint after the fix is done.
How: troubleshooting path (remember this chain)
# 1. PVC: phase and events kubectl -n shop get pvc; kubectl -n shop describe pvc NAME | sed -n '/Events/,$p' # 2. Pod: scheduling and mount events kubectl -n shop describe pod POD | sed -n '/Events/,$p' # 3. PV and attach kubectl get pv PV -o yaml | grep -E 'phase|claimRef|nodeAffinity' -A3 kubectl get volumeattachment | grep PV # 4. Node and driver kubectl get csinode NODE -o yaml kubectl -n kube-system get pods -o wide | grep -i csi kubectl -n kube-system logs POD -c <driver-container> --tail=100 # 5. Cluster-wide events (sorted by time) kubectl get events -A --sort-by=.lastTimestamp | grep -i -E 'volume|attach|mount|provision' | tail -30
When: when not to act yourself
- Do not manually remove the finalizers on a PVC or PV to "fix" Terminating. That can leave orphaned cloud disks or delete data that is still in use.
- Do not delete Pods that use RWO volumes with
--force --grace-period=0when you have not confirmed the node is shut down. - Do not manually detach a disk that still has a VolumeAttachment in the Azure portal. Fix it on the Kubernetes side first.
Compared with Docker troubleshooting
| Docker | Kubernetes |
|---|---|
Mounts in docker inspect | Pod volumes + PVC/PV/VolumeAttachment chain |
| bind source path does not exist | FailedMount / hostPath type check failed |
Accidental deletion with docker volume prune | reclaimPolicy Delete + deleting the PVC |
Architecture diagram: troubleshooting object chain
Flowchart: detach timeline for an RWO volume after a node failure
Step-by-step animation: node failure → Multi-Attach → out-of-service → recovery
Example: a Deployment on AKS (one replica, Azure Disk RWO). Watch when each controller takes action.
Troubleshooting command cheat sheet
| Command | Purpose | When to use |
|---|---|---|
kubectl get events -A --field-selector reason=FailedMount | Cluster-wide mount failure events | Widespread failure |
kubectl get events -A --field-selector reason=FailedAttachVolume | Attach failure | Multi-Attach / cloud API |
kubectl get pv -o json | jq -r '.items[] | select(.status.phase=="Released") | .metadata.name' | List Released PVs | Cost cleanup, rebinding |
kubectl patch pv PV --type json -p '[{"op":"remove","path":"/spec/claimRef"}]' | Clear the claimRef so the PV returns to Available | Rebind a Released PV |
kubectl taint nodes N node.kubernetes.io/out-of-service=nodeshutdown:NoExecute | After you confirm the shutdown, force-reclaim the Pod and volume | Permanent node failure |
kubectl get --raw /api/v1/nodes/N/proxy/metrics | grep kubelet_volume_stats_used_bytes | Volume usage metrics | Volume full alert |
kubectl debug node/N -it --image=busybox:1.37 | Enter the node and check the mounts (chroot /host mount | grep pvc) | Deep dive into FailedMount |
Rebind a Released PV (Retain case)
PV=pvc-6e2… # PV in Released state
kubectl get pv $PV -o jsonpath='{.spec.claimRef.namespace}/{.spec.claimRef.name} {.status.phase}{"\n"}'
kubectl patch pv $PV --type json -p '[{"op":"remove","path":"/spec/claimRef"}]'
kubectl get pv $PV # Available
cat <<EOF | kubectl apply -f -
apiVersion: v1
kind: PersistentVolumeClaim
metadata: { name: rebind, namespace: shop }
spec:
accessModes: ["ReadWriteOnce"]
storageClassName: $(kubectl get pv $PV -o jsonpath='{.spec.storageClassName}')
volumeName: $PV
resources: { requests: { storage: $(kubectl get pv $PV -o jsonpath='{.spec.capacity.storage}') } }
EOF
kubectl -n shop get pvc rebind
shop/zoned Released persistentvolume/pvc-6e2… patched NAME CAPACITY ACCESS MODES RECLAIM POLICY STATUS CLAIM STORAGECLASS AGE pvc-6e2… 1Gi RWO Retain Available local-zone-a 9m NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS AGE rebind Bound pvc-6e2… 1Gi RWO local-zone-a 2s
If the SC has been deleted, a PVC that specifies the same storageClassName can still bind statically (no provisioning is triggered). If you want only a specific PVC to bind, you can also change the claimRef to the new PVC's name instead of deleting it (pre-binding).
Diagnosing a full volume
kubectl -n shop exec db-0 -- df -h /var/lib/postgresql/data kubectl -n shop exec db-0 -- du -sh /var/lib/postgresql/data/pgdata/pg_wal /var/lib/postgresql/data/dumps kubectl -n shop exec db-0 -- psql -U shop -d shop -c "SELECT slot_name, active, pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) FROM pg_replication_slots;"
Common causes of a full PostgreSQL volume: inactive replication slots that cause WAL buildup, backup dump files left on the data volume, and long transactions that block vacuum.
Lab 8: Create and fix 4 storage failures (about 8 minutes, kind)
kubectl patch sc standard -p '{"metadata":{"annotations":{"storageclass.kubernetes.io/is-default-class":"false"}}}'
cat <<'EOF' | kubectl apply -f -
apiVersion: v1
kind: PersistentVolumeClaim
metadata: { name: nodefault, namespace: shop }
spec: { accessModes: ["ReadWriteOnce"], resources: { requests: { storage: 1Gi } } }
EOF
kubectl -n shop describe pvc nodefault | tail -2
kubectl -n shop get pvc nodefault -o jsonpath='SC={.spec.storageClassName}{"\n"}'
Normal FailedBinding 2s (x3 over 20s) persistentvolume-controller no persistent volumes available for this claim and no storage class is set SC=
Fix: Restore the default annotation. When a PVC's storageClassName is nil, newer PV controller versions backfill it after a default SC appears (retroactive default StorageClass, GA in v1.28). The PVC then follows the normal flow:
kubectl patch sc standard -p '{"metadata":{"annotations":{"storageclass.kubernetes.io/is-default-class":"true"}}}'
sleep 5; kubectl -n shop get pvc nodefault -o jsonpath='SC={.spec.storageClassName}{"\n"}'
kubectl -n shop delete pvc nodefaultcat <<'EOF' | kubectl apply -f -
apiVersion: v1
kind: PersistentVolumeClaim
metadata: { name: pinned, namespace: shop }
spec: { accessModes: ["ReadWriteOnce"], resources: { requests: { storage: 1Gi } } }
---
apiVersion: v1
kind: Pod
metadata: { name: pinned, namespace: shop }
spec:
containers: [{ name: c, image: busybox:1.37, command: ["sleep","3600"], volumeMounts: [{ name: d, mountPath: /d }] }]
volumes: [{ name: d, persistentVolumeClaim: { claimName: pinned } }]
EOF
kubectl -n shop wait --for=condition=Ready pod/pinned --timeout=60s
N=$(kubectl -n shop get pod pinned -o jsonpath='{.spec.nodeName}'); echo $N
kubectl cordon $N
kubectl -n shop delete pod pinned
kubectl -n shop apply -f - <<'EOF'
apiVersion: v1
kind: Pod
metadata: { name: pinned, namespace: shop }
spec:
containers: [{ name: c, image: busybox:1.37, command: ["sleep","3600"], volumeMounts: [{ name: d, mountPath: /d }] }]
volumes: [{ name: d, persistentVolumeClaim: { claimName: pinned } }]
EOF
sleep 5; kubectl -n shop describe pod pinned | grep -A2 FailedScheduling
lab-worker2
Warning FailedScheduling … 0/3 nodes are available: 1 node(s) were unschedulable, 1 node(s) had untolerated taint {node-role.kubernetes.io/control-plane: }, 1 node(s) had volume node affinity conflict. …
Fix: kubectl uncordon $N, and the Pod is scheduled back automatically. Production lesson: local storage ties availability to a single node. Cleanup: kubectl -n shop delete pod pinned; kubectl -n shop delete pvc pinned.
cat <<'EOF' | kubectl apply -f -
apiVersion: v1
kind: PersistentVolume
metadata: { name: perm-pv }
spec:
capacity: { storage: 1Gi }
accessModes: ["ReadWriteOnce"]
storageClassName: ""
hostPath: { path: /mnt/perm-demo, type: DirectoryOrCreate }
nodeAffinity:
required:
nodeSelectorTerms: [{ matchExpressions: [{ key: kubernetes.io/hostname, operator: In, values: ["lab-worker"] }] }]
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata: { name: perm, namespace: shop }
spec: { accessModes: ["ReadWriteOnce"], storageClassName: "", volumeName: perm-pv, resources: { requests: { storage: 1Gi } } }
---
apiVersion: v1
kind: Pod
metadata: { name: perm, namespace: shop }
spec:
securityContext: { runAsUser: 1000, fsGroup: 1000 }
containers: [{ name: c, image: busybox:1.37, command: ["sh","-c","touch /d/x && echo OK || echo FAIL; sleep 3600"], volumeMounts: [{ name: d, mountPath: /d }] }]
volumes: [{ name: d, persistentVolumeClaim: { claimName: perm } }]
EOF
kubectl -n shop wait --for=condition=Ready pod/perm --timeout=60s; kubectl -n shop logs perm
touch: /d/x: Permission denied FAIL
Cause: hostPath volumes do not support fsGroup ownership changes, and kubelet creates the directory as root with mode 0755. Fix: Use a CSI volume that supports fsGroup (check CSIDriver.fsGroupPolicy), or fix the ownership with an init container (the fix-perms container from Module 6). Cleanup: kubectl -n shop delete pod perm; kubectl -n shop delete pvc perm; kubectl delete pv perm-pv.
Demonstrate with a throwaway PVC (do not use data-db-0 for this lab):
cat <<'EOF' | kubectl apply -f -
apiVersion: v1
kind: PersistentVolumeClaim
metadata: { name: busy, namespace: shop }
spec: { accessModes: ["ReadWriteOnce"], resources: { requests: { storage: 1Gi } } }
---
apiVersion: v1
kind: Pod
metadata: { name: busy, namespace: shop }
spec:
containers: [{ name: c, image: busybox:1.37, command: ["sleep","3600"], volumeMounts: [{ name: d, mountPath: /d }] }]
volumes: [{ name: d, persistentVolumeClaim: { claimName: busy } }]
EOF
kubectl -n shop wait --for=condition=Ready pod/busy --timeout=60s
kubectl -n shop delete pvc busy --wait=false
kubectl -n shop get pvc busy
kubectl -n shop get pvc busy -o jsonpath='{.metadata.finalizers}{" deletionTimestamp="}{.metadata.deletionTimestamp}{"\n"}'
NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS AGE busy Terminating pvc-0c9d… 1Gi RWO standard 20s ["kubernetes.io/pvc-protection"] deletionTimestamp=2026-11-15T05:01:02Z
Explanation: The busy Pod is still using the PVC, so the protection controller blocks the actual deletion. This is protection, not a fault: the Pod keeps reading and writing as usual. Note: Kubernetes cannot “cancel” a deletion. Once the Pod stops, the PVC is deleted, and with the Delete policy the data goes with it. In a real environment, if you accidentally delete a production PVC, back it up right away (Velero / snapshot / pg_dump), then plan the migration.
kubectl -n shop delete pod busy kubectl -n shop get pvc busy 2>&1 | tail -1 # NotFound: after the Pod exits, the finalizer is removed and the PVC finishes deleting
Case 1: Many Multi-Attach errors during an AKS node pool upgrade
Problem: During a rolling node pool upgrade, Pods on new nodes reported Multi-Attach for more than 6 minutes.
Root cause: Some Deployments used RWO disks but set maxSurge: 1. New Pods were scheduled to another node while the old Pods still held the disk.
Approach: Use strategy: Recreate or a StatefulSet for RWO workloads. Set PDBs and terminationGracePeriodSeconds sensibly. Watch the drain timeout and surge settings for AKS node upgrades.
Case 2: Database volume full, causing read-only mode
Problem: Early in the morning, PostgreSQL reported could not write to file "pg_wal/xlogtemp": No space left on device, and the service went down.
Root cause: A decommissioned logical replication subscriber left behind an inactive replication slot, so WAL could not be recycled.
Approach: Expand the PVC online as an emergency fix (supported by Azure Disk) → delete the unused replication slot → set max_slot_wal_keep_size. Alert when kubelet_volume_stats_available_bytes / capacity_bytes < 15% (Azure Monitor managed Prometheus can scrape kubelet metrics directly).
Case 3: Bill for orphaned disks
Problem: Finance found 80 unattached managed disks in the node resource group.
Approach: Compare the output of az disk list --query "[?diskState=='Unattached']" with the PV list in the cluster. Use the PVC Unused condition in v1.37 and the PV Released phase to find idle resources. Set a policy that every Retain PV must have an owner label.
Interactive troubleshooting decision tree
Common errors and fixes
Multi-Attach error for volume "pvc-…" Volume is already exclusively attached to one node and can't be attached to another
Cause: The RWO disk is still attached to the old node (the old Pod has not finished, the node is unreachable, or a rolling update surge is in progress).
kubectl get volumeattachment -o custom-columns=PV:.spec.source.persistentVolumeName,NODE:.spec.nodeName,ATTACHED:.status.attached | grep PV kubectl get pods -A -o wide --field-selector spec.nodeName=OLD_NODE | grep -v Running kubectl get node OLD_NODE
Fix: If the old Pod is still running normally, this is a configuration problem (surge or multiple replicas), so switch to Recreate or a StatefulSet. If the old node is powered off, add the out-of-service taint. If the old node is healthy but the Pod is stuck in Terminating, check the kubelet and unmount logs.
Unable to attach or mount volumes: unmounted volumes=[data], unattached volumes=[data]: timed out waiting for the condition
Cause: This is kubelet's summary timeout message. The real cause is in earlier events, such as FailedAttachVolume, MountVolume.SetUp failed, or driver not found.
kubectl -n shop get events --field-selector involvedObject.name=POD --sort-by=.lastTimestamp kubectl get volumeattachment | grep PV
Fix: Handle the specific cause. For attach issues, see Module 3. For permissions, see the next item.
could not open file "pg_hba.conf": Permission denied / mkdir: can't create directory: Permission denied
Cause: The container user does not match the owner of the volume directory. fsGroup is not set, or the driver does not support it. With fsGroupChangePolicy=OnRootMismatch, the root directory may have the right owner while subdirectories do not.
kubectl -n shop exec POD -- id
kubectl -n shop exec POD -- ls -lnd /mount /mount/*
kubectl get csidriver DRIVER -o jsonpath='{.spec.fsGroupPolicy}{"\n"}'
Fix: Set fsGroup. If needed, make a one-time fix with the Always policy, then switch back to OnRootMismatch. Or use an init container to run chown.
No space left on device
Cause: The volume is full (or out of inodes). It can also be node ephemeral storage that is full (emptyDir or logs).
kubectl -n shop exec POD -- df -h /data; kubectl -n shop exec POD -- df -i /data
Fix: If expansion is supported, expand the PVC. Clean up data. For local-path, migrate to a larger PVC.
PV stays Released, and the new PVC cannot bind
Cause: Under the Retain policy, the PV keeps the old claimRef, which includes the old PVC's UID.
Fix: After you confirm the data can go to the new user, delete the claimRef (see the “Commands” tab). The new PVC then binds with volumeName.
PV stuck in Terminating, finalizers: [kubernetes.io/pv-protection external-provisioner.volume.kubernetes.io/finalizer]
Cause: The PV is still bound to a PVC (pv-protection), or the provisioner is deleting the backend volume or cannot delete it (driver unavailable, cloud API error).
kubectl get pv PV -o jsonpath='{.spec.claimRef}{"\n"}{.metadata.finalizers}{"\n"}'
kubectl -n kube-system logs deploy/CSI_CONTROLLER -c csi-provisioner | grep PV | tail
Fix: Delete the PVC first. After the driver is fixed, the finalizer is removed automatically. Remove the finalizer manually only after you confirm the backend volume no longer exists.
1. List the 30 most recent volume-related Warning events (all namespaces, sorted by time).
kubectl get events -A --field-selector type=Warning --sort-by=.lastTimestamp | grep -i -E 'volume|attach|mount|provision' | tail -30
2. The VM for node n1 is confirmed stopped in Azure. Write the command that lets the StatefulSet Pods on it recover on other nodes as quickly as possible, and the command to clean up after recovery.
kubectl taint nodes n1 node.kubernetes.io/out-of-service=nodeshutdown:NoExecute # Pods are force-deleted and volumes are detached. The StatefulSet is recreated on another node (the volume must be mountable in that zone, such as ZRS) kubectl taint nodes n1 node.kubernetes.io/out-of-service=nodeshutdown:NoExecute- # remove the taint after the node is repaired or deleted
A user reports that “the order service does not start after the AKS upgrade.” The Pod event is FailedAttachVolume … AttachVolume.Attach failed … The maximum number of data disks allowed to be attached to a VM of this size is 4. Analyze the issue and propose short-term and long-term fixes.
The new node pool uses a smaller VM SKU (for example, D2s_v5 allows up to 4 data disks), and this node is already full. The scheduler should have filtered on CSINode.allocatable.count. This error can occur if the CSINode information was not updated in time or if attaches happened at the same time. Short term: scale out the node pool, or schedule the Pod to another node (cordon the full node). Long term: choose a SKU with a higher data disk limit, use dedicated node pools for stateful workloads, reduce the number of volumes per Pod, switch shared data to Azure Files, and add a “volumes per node” dimension to capacity planning.
Video lesson
No video was found that has a verified YouTube ID and covers Kubernetes storage troubleshooting. Study this module with its decision tree and the official docs.
Official documentation
- Node Shutdowns (out-of-service taint)
- Storage Object in Use Protection
- Microsoft Learn: Troubleshoot AKS disk mount failures
Video storyboard script
This course material cannot generate a video or MP3 directly, so a storyboard and narration script are provided instead.
Narration: To troubleshoot storage, follow the object chain and check the events one at a time.
Narration: Step one: first decide whether this is normal waiting.
Narration: After you confirm a node is shut down, use the out-of-service taint so the control plane can force-reclaim safely.
Narration: When a deletion is stuck, the protection mechanism is usually doing its job. Don't delete the finalizer casually.
Command cheat sheet
StorageClass
kubectl get sc
kubectl get sc NAME -o yaml
kubectl patch sc NAME -p '{"metadata":{"annotations":{"storageclass.kubernetes.io/is-default-class":"true"}}}'
kubectl explain storageclass.volumeBindingMode
kubectl get sc -o custom-columns=NAME:.metadata.name,PROV:.provisioner,RECLAIM:.reclaimPolicy,BIND:.volumeBindingMode,EXPAND:.allowVolumeExpansionPVC / PV
kubectl get pvc -A -o wide
kubectl describe pvc NAME | sed -n '/Events/,$p'
kubectl get pv -o custom-columns=NAME:.metadata.name,CLAIM:.spec.claimRef.name,PHASE:.status.phase,POLICY:.spec.persistentVolumeReclaimPolicy,SC:.spec.storageClassName
kubectl patch pv PV -p '{"spec":{"persistentVolumeReclaimPolicy":"Retain"}}'
kubectl patch pv PV --type json -p '[{"op":"remove","path":"/spec/claimRef"}]'
kubectl get pvc NAME -o jsonpath='{.status.conditions[?(@.type=="Unused")]}' # v1.37 BetaCSI objects
kubectl get csidriver kubectl get csinode -o custom-columns=NODE:.metadata.name,DRIVERS:.spec.drivers[*].name,LIMIT:.spec.drivers[*].allocatable.count kubectl get volumeattachment -o custom-columns=PV:.spec.source.persistentVolumeName,NODE:.spec.nodeName,ATTACHED:.status.attached kubectl -n kube-system get pods -o wide | grep -i csi kubectl -n kube-system logs POD -c csi-provisioner --tail=50
Expansion · snapshots · cloning
kubectl patch pvc P -p '{"spec":{"resources":{"requests":{"storage":"20Gi"}}}}'
kubectl get pvc P -o jsonpath='{.status.capacity.storage} {.status.conditions}{"\n"}'
kubectl get vsclass; kubectl get vs,vsc
kubectl wait vs/S --for=jsonpath='{.status.readyToUse}'=true --timeout=300s
# Restore: PVC.spec.dataSource {name: S, kind: VolumeSnapshot, apiGroup: snapshot.storage.k8s.io}
# Clone: PVC.spec.dataSource {name: SRC_PVC, kind: PersistentVolumeClaim}StatefulSet
kubectl scale sts db --replicas=N
kubectl rollout status sts db
kubectl get pvc -l app=db
kubectl patch sts db --type merge -p '{"spec":{"persistentVolumeClaimRetentionPolicy":{"whenDeleted":"Retain","whenScaled":"Retain"}}}'
kubectl delete sts db --cascade=orphan # before changing an immutable field
kubectl exec db-0 -- psql -U shop -d shop -tAc 'SELECT count(*) FROM orders'Velero
velero install --provider aws --plugins velero/velero-plugin-for-aws:v1.14.4 \ --bucket velero --secret-file ./credentials-velero --use-volume-snapshots=false \ --backup-location-config region=minio,s3ForcePathStyle="true",s3Url=http://minio.velero.svc:9000 \ --use-node-agent --default-volumes-to-fs-backup --features=EnableCSI --wait velero backup-location get velero backup create B --include-namespaces shop [--snapshot-move-data] --wait velero backup describe B --details; velero backup logs B velero restore create --from-backup B [--namespace-mappings shop:shop2] --wait velero schedule create S --schedule="0 2 * * *" --include-namespaces shop --ttl 168h0m0s
AKS storage
az aks show -g RG -n AKS --query storageProfile az aks update -g RG -n AKS --enable-disk-driver --enable-file-driver --enable-snapshot-controller az aks update -g RG -n AKS --enable-blob-driver MC=$(az aks show -g RG -n AKS --query nodeResourceGroup -o tsv) az disk list -g $MC -o table az disk list -g $MC --query "[?diskState=='Unattached'].name" -o tsv az snapshot list -g $MC -o table
Troubleshooting
kubectl get events -A --sort-by=.lastTimestamp | grep -i -E 'volume|attach|mount|provision' kubectl describe pod POD | sed -n '/Events/,$p' kubectl get pvc,pv -o yaml | grep -A3 finalizers kubectl taint nodes N node.kubernetes.io/out-of-service=nodeshutdown:NoExecute kubectl debug node/N -it --image=busybox:1.37 -- chroot /host sh -c 'mount | grep -E "pvc|csi"' kubectl exec POD -- df -h /data; kubectl exec POD -- df -i /data
Quick troubleshooting table
| Symptom | What to check first | Common causes |
|---|---|---|
| PVC Pending, event WaitForFirstConsumer | Check whether a Pod uses it; check the Pod scheduling events | Normal waiting, or the Pod failed to schedule |
| PVC Pending, no storage class is set | kubectl get sc | No default SC |
| ProvisioningFailed | Provisioner logs, cloud quota | SKU unavailable, permissions, unsupported access mode |
| volume node affinity conflict | PV nodeAffinity vs node labels | Immediate mode, local volume node unavailable |
| Multi-Attach error | VolumeAttachment, old node state | Old Pod not finished, surge update, node unreachable |
| exceed max volume count | CSINode allocatable | VM SKU data disk limit |
| Permission denied | id, ls -ln, fsGroupPolicy | Missing fsGroup, hostPath, SMB |
| No space left on device | df -h / df -i | WAL / log buildup |
| PVC/PV Terminating | finalizers, Pods using the PVC | pvc-protection working as intended; driver failure |
| PV Released | claimRef | Retain policy, needs manual handling |
For the full interactive troubleshooting flow, see Module 8 → Troubleshooting → Decision tree.
Recommended configuration snippet
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata: { name: db-premium-zrs-retain }
provisioner: disk.csi.azure.com
parameters:
skuName: Premium_ZRS
cachingMode: ReadOnly
reclaimPolicy: Retain
volumeBindingMode: WaitForFirstConsumer
allowVolumeExpansion: truespec:
persistentVolumeClaimRetentionPolicy:
whenDeleted: Retain
whenScaled: Retain
template:
spec:
terminationGracePeriodSeconds: 120
securityContext:
fsGroup: 999
fsGroupChangePolicy: OnRootMismatch
volumeClaimTemplates:
- metadata: { name: data }
spec:
accessModes: ["ReadWriteOncePod"]
storageClassName: db-premium-zrs-retain
resources: { requests: { storage: 64Gi } }ReadWriteOncePod requires a CSI driver. Azure Disk supports it. For ZRS availability zones and pricing, follow the Azure documentation. If cost is a concern and the application handles its own replication, you can switch to Premium_LRS.
Capstone lab + final quiz
SC=hostpath-csi, VSC=csi-hostpath-snapclass, NODESEL pinned to the node where csi-hostpathplugin-0 runs. Velero uses MinIO (Module 7). AKS: SC=managed-csi, VSC=csi-azuredisk-vsc, NODESEL='{}'. Velero uses Azure Blob (velero-plugin-for-microsoft-azure, configured according to the plugin docs), or Azure Backup for AKS.cd ~/k8slab/hour4
kubectl create ns shop --dry-run=client -o yaml | kubectl apply -f -
HP_NODE=$(kubectl get pod csi-hostpathplugin-0 -o jsonpath='{.spec.nodeName}')
SC=hostpath-csi; VSC=csi-hostpath-snapclass; NODESEL="{kubernetes.io/hostname: $HP_NODE}"
sed -e "s#__SC__#$SC#" -e "s#__NODESEL__#$NODESEL#" db.yaml | kubectl apply -f -
kubectl -n shop rollout status sts db --timeout=180s
kubectl -n shop get pvc data-db-0 -o jsonpath='{.spec.storageClassName} {.status.phase}{"\n"}'kubectl -n shop exec -i db-0 -- psql -U shop -d shop -v ON_ERROR_STOP=1 <<'SQL' CREATE TABLE IF NOT EXISTS orders (id serial PRIMARY KEY, item text, created_at timestamptz DEFAULT now()); INSERT INTO orders (item) SELECT 'final-' || g FROM generate_series(1,5000) g; SQL ROWS=$(kubectl -n shop exec db-0 -- psql -U shop -d shop -tAc 'SELECT count(*) FROM orders'); echo "ROWS=$ROWS" | tee evidence.txt
kubectl -n shop patch pvc data-db-0 -p '{"spec":{"resources":{"requests":{"storage":"2Gi"}}}}'
kubectl -n shop wait pvc/data-db-0 --for=jsonpath='{.status.capacity.storage}'=2Gi --timeout=300s
kubectl -n shop delete sts db --cascade=orphan
sed -e "s#__SC__#$SC#" -e "s#__NODESEL__#$NODESEL#" -e 's#storage: 1Gi#storage: 2Gi#' db.yaml | kubectl apply -f -
kubectl -n shop get pvc data-db-0 -o jsonpath='capacity={.status.capacity.storage}{"\n"}' | tee -a evidence.txtkubectl -n shop exec db-0 -- psql -U shop -d shop -c CHECKPOINT
cat <<EOF | kubectl apply -f -
apiVersion: snapshot.storage.k8s.io/v1
kind: VolumeSnapshot
metadata: { name: db-pre-release, namespace: shop }
spec:
volumeSnapshotClassName: $VSC
source: { persistentVolumeClaimName: data-db-0 }
EOF
kubectl -n shop wait vs/db-pre-release --for=jsonpath='{.status.readyToUse}'=true --timeout=300s
kubectl -n shop get vs db-pre-release -o jsonpath='snapshot ready={.status.readyToUse} size={.status.restoreSize}{"\n"}' | tee -a evidence.txtvelero backup-location get # must show Available
# After the orphan rebuild in step 3, the hook annotations are gone from the template. Add them back here (this rolls db-0 again)
kubectl -n shop patch sts db --type merge -p '{"spec":{"template":{"metadata":{"annotations":{
"pre.hook.backup.velero.io/container":"postgres",
"pre.hook.backup.velero.io/command":"[\"/bin/sh\",\"-c\",\"pg_dump -U \\\"$POSTGRES_USER\\\" -d \\\"$POSTGRES_DB\\\" -Fc -f /var/lib/postgresql/data/dumps/shop.dump\"]",
"pre.hook.backup.velero.io/timeout":"3m"}}}}}'
kubectl -n shop rollout status sts db --timeout=180s
velero backup create shop-final --include-namespaces shop --wait
velero backup describe shop-final --details | grep -E 'Phase|Completed:' -A1 | tee -a evidence.txtkubectl delete ns shop --wait kubectl get vsc | grep db-pre-release || echo "VolumeSnapshotContent is also deleted along with the VS (deletionPolicy=Delete). A snapshot is not a backup!" | tee -a evidence.txt
velero restore create shop-final-r --from-backup shop-final --wait
kubectl -n shop wait --for=condition=Ready pod/db-0 --timeout=300s
AFTER=$(kubectl -n shop exec db-0 -- psql -U shop -d shop -tAc 'SELECT count(*) FROM orders')
echo "ROWS_AFTER=$AFTER" | tee -a evidence.txt
[ "$AFTER" = "$ROWS" ] && echo "✓ Row counts match" || echo "✗ Row counts do not match. Check PodVolumeRestore, or run pg_restore with dumps/shop.dump"
kubectl -n shop get pvc data-db-0 -o jsonpath='restored capacity request={.spec.resources.requests.storage}{"\n"}' | tee -a evidence.txt
cat evidence.txt
ROWS=5000 capacity=2Gi snapshot ready=true size=2Gi Phase: Completed VolumeSnapshotContent is also deleted along with the VS (deletionPolicy=Delete). A snapshot is not a backup! ROWS_AFTER=5000 restored capacity request=2Gi
az aks delete -g rg-k8s-lab -n aks-lab --yes --no-wait. When you no longer need the whole environment, run az group delete -n rg-k8s-lab --yes --no-wait.Open-ended self-check (answer on your own first, then expand the reference answers)
1. What happens to the data in emptyDir, hostPath, and PVC volumes when the container restarts, the Pod is deleted, or the node fails?
emptyDir: data survives a container restart, but is lost when the Pod is deleted or the node fails. hostPath: data stays on the original node and is not visible after the Pod moves to another node. PVC (network or cloud disk): data survives all three cases. If the node fails, the volume is detached and attached to a new node (RWO needs to wait, or use out-of-service).
2. Why should the disk SC in a multi-zone cluster use WaitForFirstConsumer?
It lets the scheduler weigh all constraints and pick a node first, then create the LRS disk in that node's zone. Immediate mode can create the disk in a zone where the Pod cannot be scheduled, which causes a volume node affinity conflict.
3. Describe the order of CSI calls for an Azure Disk PVC, from creation until the container can write to it.
CreateVolume (external-provisioner, creates the PV) → ControllerPublishVolume (the AD controller creates the VolumeAttachment; called by external-attacher, attaches the disk to the VM LUN) → NodeStageVolume (kubelet, formats the disk and mounts it to globalmount) → NodePublishVolume (kubelet, bind mount into the Pod directory) → CRI mounts it into the container.
4. What is the difference between RWO and RWOP? When is RWOP required?
RWO limits access to one node, so multiple Pods on the same node can mount the volume at the same time. RWOP limits access to a single Pod across the whole cluster. Use RWOP when you need a single writer, for example with SQLite, or to stop old and new instances from writing at the same time during a rolling update.
5. What problem does each of these solve: snapshots, Velero, and pg_dump?
Snapshots: fast, crash-consistent volume-level rollback. They are usually in the same region and tied to cluster objects. Velero: packages resources and volumes into object storage outside the cluster. It supports cross-cluster restore and schedules. pg_dump: a transaction-consistent logical backup that works across versions. In production, combine them and rehearse restores regularly.
6. A PVC is stuck in Terminating. What is the correct way to handle it?
Check the finalizers. If it is kubernetes.io/pvc-protection, find the Pods that use the PVC and confirm you really want to delete it (with the Delete policy, the data is lost). Back up first, then stop the Pods. Do not delete the finalizer manually.
Final quiz (12 questions, covering all modules)
Sources and versions
| Topic | Verified finding | Source |
|---|---|---|
| Kubernetes version | 1.37 (1.37.1, 2026-09-15) is the latest supported branch. v1.37 was released on 2026-08-26. | kubernetes.io/releases · v1.37 release blog (2026-08-26) |
| PVC Unused condition | v1.37 Beta, enabled by default. Feature gate PersistentVolumeClaimUnusedSinceTime. Maintained by the PVC protection controller. type: Unused, with reasons NoPodsUsingPVC / PodUsingPVC. Use lastTransitionTime to determine how long the PVC has been idle. | Tracking When a PVC Was Last Used (2026-09-21) |
| Volumes | Image volume: Stable since v1.36 (first introduced in v1.31), with subPath support since v1.33. recursiveReadOnly: Stable since v1.33. mountPropagation values: None/HostToContainer/Bidirectional. hostPath security warning. | Volumes (accessed 2026-11) |
| Persistent Volumes | ReadWriteOncePod: Stable since v1.29. PV phases: Available/Bound/Released/Failed. lastPhaseTransitionTime has been stable since 1.31. Shrinking is not supported. If expansion fails, you can retry with a smaller value that is still larger than status.capacity. | Persistent Volumes (accessed 2026-11) |
| StatefulSet | persistentVolumeClaimRetentionPolicy: Stable since v1.32, default Retain. Recreate update strategy: Alpha since v1.37 (StatefulSetRecreateStrategy). maxUnavailable: Beta since v1.37. ordinals.start: Stable since v1.31. | StatefulSets (accessed 2026-11) |
| VolumeGroupSnapshot | GA in v1.36, groupsnapshot.storage.k8s.io/v1. Alpha in v1.27, Beta in v1.32. | v1.36 VGS GA (2026-05-08) |
| Volume populators | GA in v1.33. AnyVolumeDataSource is always enabled and uses dataSourceRef. | v1.33 Volume Populators GA (2025-05-08) |
| external-snapshotter | Latest v8.7.0 (10-13). v8.6.0 promoted the VolumeGroupSnapshot API to v1. | GitHub releases (accessed 2026-11) |
| csi-driver-host-path | Install order: snapshot CRDs → snapshot-controller → deploy/kubernetes-latest/deploy.sh. VolumeSnapshotClass csi-hostpath-snapclass. For testing only. | deploy-1.17-and-later.md (accessed 2026-11) |
| local-path-provisioner | Latest v0.0.37 (08-05). The kind default SC standard uses it (WFFC, Delete, no expansion support). | GitHub releases (accessed 2026-11) |
| AKS storage classes | default = managed-csi (Standard SSD), managed-csi-premium, managed-csi-premium-v2 (1.35+, LRS), azurefile-csi(-premium), azureblob-*. On multi-zone clusters from 1.29, the built-in SCs use ZRS. AKS reconciles the built-in SCs. | AKS storage concepts (ms.date 2026-11-08) |
| AKS CSI drivers | In-tree volume creation is no longer supported from 1.26. Disk supports Premium SSD v1/v2, ZRS, snapshots, cloning, and online expansion. The per-node volume limit depends on the VM SKU. The snapshot controller is controlled with --enable/--disable-snapshot-controller. | CSI storage drivers on AKS (2026-08-03) |
| Azure Disk PV | SC parameters (skuName, cachingMode, DiskIOPSReadWrite…). VolumeSnapshotClass csi-azuredisk-vsc (incremental defaults to true). Online expansion up to 4 TiB (v2/Ultra are exceptions). Shrinking is not supported. | Azure Disks on AKS (2026-10-16) |
| Velero | Latest stable v1.18.4 (09-28). v1.19.0-rc.1 removes the Restic path and moves to Kopia 0.23.1. velero-plugin-for-aws v1.14.4 (09-28). | Velero releases · AWS plugin releases (accessed 2026-11) |
| CloudNativePG | Latest v1.30.1 (2026-09-23) | GitHub releases (accessed 2026-11) |
Video verification notes
The following videos were verified through the YouTube oEmbed API, and their titles, authors and IDs match: TechWorld with Nana, “Kubernetes Volumes explained | Persistent Volume, Persistent Volume Claim & Storage Class” (0swOh5C3OVM); TechWorld with Nana, “Kubernetes StatefulSet simply explained | Deployment vs StatefulSet” (pPQKAR1pA9U); CNCF, “Project Lightning Talk: CloudNativePG: Running Postgres The Kubernetes Way - Gabriele Bartolini” (pYwYwehQX3U, KubeCon NA 2025). Run times were not checked one by one, so refer to the YouTube pages. The first two videos were recorded on earlier Kubernetes versions. No verifiable YouTube IDs were found for videos on CSI, snapshots, Velero, or storage troubleshooting. The related modules say “No verified video found” and provide a storyboard script instead. No verifiable high-quality video with Chinese narration was found.
Voice narration notes
The “Voice” tab reads the narration aloud in real time with the browser Web Speech API (speechSynthesis, en-US). English terms are pronounced with en-US. The result depends on the English voices installed on the system (for example, the Windows and macOS English voices). The environment that generated this course material cannot call a TTS service, so it cannot embed an MP3. For audio, send the narration script to a service such as Azure AI Speech.
Known limitations and conservative handling
- The UIDs, PV names, IPs, times, object counts, and column widths in “Expected output” are sample values. Use your actual environment as the reference. Column names may differ slightly between minor versions of kubectl and velero.
- On AKS, check the VOLUMEBINDINGMODE of
kubectl get sc(Azure Files), the Deployment and container names of the CSI controller, and whether snapshot-controller is enabled by default against your cluster's actual output. - The official docs do not confirm whether changing the storage size in StatefulSet volumeClaimTemplates is allowed in v1.37. This course material gives a general orphan-rebuild approach instead.
- VolumeGroupSnapshot requires driver support. Support for group snapshots in csi-driver-host-path and Azure Disk has not been checked one by one.
- The MinIO example manifest comes from the Velero repository. MinIO Community Edition's release method has changed in recent years, so check image availability yourself.
- This hour does not cover the specific commands, support matrix, or pricing for Azure Backup for AKS. Refer to Microsoft Learn.
- Cost estimates are rough orders of magnitude. Confirm them with the Azure pricing calculator. The timings in the animation are illustrative.
- The CloudNativePG install manifest URL follows the project's usual convention. Check the official Installation docs before you install.