Kubernetes Hour 4: Storage and Stateful Apps

From emptyDir to CSI, from PVC binding timing to StatefulSet + PostgreSQL, snapshots and Velero backup and restore: making shop's database truly "impossible to lose"
Kubernetes v1.37.1kind v0.33.0AKS (optional)Verified against official docs · 2026-11
Overall learning goals
  • 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

#TimeModuleCore contentAnimation / interactionLab
0Before classWarm-upCheck 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
100–07Volume basicsemptyDir (Memory, sizeLimit), configMap/secret/downwardAPI/projected, hostPath risks, image volume (GA in v1.36), generic ephemeral volumes; readOnly, subPath, mountPropagationContainer restart / Pod deletion / node failure data-location simulatorMulti-volume Pod: observe the data in each volume type after restarts and deletions
207–15PV · PVC · StorageClassStatic vs dynamic provisioning, PV controller binding, SC fields, default SC, PVC/PV phases, v1.37 Beta: PVC Unused conditionPVC → WaitForFirstConsumer → scheduling → provision → bind → attach → mount timing animationDynamic provisioning with local-path + manual binding to a static PV
315–22CSI architecture and Azure Diskcontroller plugin + sidecar, node plugin + registrar, CSIDriver/CSINode/VolumeAttachment; Azure Disk / Files CSI, AKS built-in SCs, Premium SSD v2CSI gRPC call-chain animation (each step shows the method name and the K8s object)Install csi-driver-host-path; observe VolumeAttachment on AKS
422–29Access modes · reclaim policies · topologyRWO/ROX/RWX/RWOP, Retain/Delete, zone topology, allowedTopologies, ZRS, node volume limits"Backend × access mode × scenario" feasibility checkerRWOP conflict reproduction, Retain reclaim drill
529–36Expansion · snapshots · clonesOnline expansion, no shrinking, VolumeSnapshot/Content/Class, dataSource restore, PVC cloning, VolumeGroupSnapshot, populatorsExpansion / snapshot / restore / clone object relationship simulatorSnapshot restore with hostpath CSI (kind) or Azure Disk (AKS)
636–46StatefulSet + PostgreSQL in practicevolumeClaimTemplates, data-db-0, PVC retention policy, PGDATA subdirectory, fsGroup, graceful shutdown, Operator vs managedStatefulSet replica and PVC binding relationship simulatorWrite → delete Pod → scale to 0 → scale up → data still there
746–53Backup and restore (Velero)etcd snapshot vs application-level vs volume snapshot; BSL/VSL, CSI snapshots, Kopia node-agent, hooks, schedules; Azure Backup for AKSBackup and restore workflow animationkind + MinIO: back up shop → delete namespace → restore
853–60Storage troubleshootingPending, Multi-Attach, FailedMount, permissions, full volumes, Released, finalizersDetach/attach timeline after node failure + troubleshooting decision treeTrigger 4 kinds of failure on purpose and fix them
—After classCheat sheet · Capstone labshop db: StatefulSet + PVC + expansion + snapshot + Velero backup → delete namespace → restore → verify row count12-question final quizCapstone lab

Knowledge Coverage Matrix

Target skillM1M2M3M4M5M6M7M8Key commandsLab
Choose the right Pod-internal volume type✓····✓··kubectl explain pod.spec.volumesM1 Multi-volume Pod
Dynamic / static provisioning and binding·✓✓··✓·✓kubectl get pvc,pv -o wideM2 local-path
Understand CSI components and objects·✓✓·✓··✓kubectl get csidriver,csinode,volumeattachmentM3 hostpath CSI
Access mode and topology design·✓✓✓·✓·✓kubectl get pv -L topology.kubernetes.io/zoneM4 RWOP
Expansion / snapshot / clone··✓·✓✓✓·kubectl patch pvc, kubectl get vs,vscM5 Snapshot restore
Running a stateful database···✓·✓✓✓kubectl scale sts, psqlM6 PostgreSQL
Backup and disaster recovery····✓·✓·velero backup/restore createM7 Velero
Storage troubleshooting✓✓✓✓·✓·✓kubectl describe pvc, kubectl get eventsM8 Fault injection

Topics excluded from this hour

TopicWhy not coveredWhere to learn
Writing your own CSI driverBelongs to the storage vendor development domain and cannot be covered within 1 hourKubernetes CSI Developer Documentation
Self-managed distributed storage such as Ceph/Rook, Longhorn, OpenEBSHigh operational complexity; this hour focuses on cloud-managed disksOfficial project docs; KubeCon storage sessions
PostgreSQL primary-replica replication details, Patroni, PITRBelongs to the database specialtyCloudNativePG docs; Azure Database for PostgreSQL docs
Hands-on etcd backup and restoreControl-plane operations; on AKS, handled by the platformKubernetes docs "Operating etcd clusters"; hour 6, Module 6 gives an overview
RBAC limits on who can create PVs, Pod Security detailsBelongs to security hardeningHour 5 (RBAC / PSS / hardening)
Azure Container Storage, Azure NetApp Files, deeper Blob CSITime-limited; mentioned only in comparison tablesMicrosoft Learn: AKS storage concepts
Volumes on Windows nodesAll labs in this hour use Linux nodesMicrosoft Learn: Use Azure Disks with Windows containers

How to use this course material

10 pages per module
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.
Learning progress
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).
English voice
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.
Version notesThis hour uses Kubernetes v1.37 (latest patch 1.37.1) as the reference. Recent storage changes: image volumes became GA in v1.36; VolumeGroupSnapshot became GA in v1.36 (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)

Reuse the kind cluster lab and the shop namespace from hours 1–3. Optionally create the AKS cluster aks-lab for the CSI expansion / snapshot / Azure Disk labs.
Before class ≈ 10 minkind v0.33.0 · v1.37.0AKS optional (incurs costs)
Prerequisites
  • Completed hours 1–3: kind cluster lab (1 control plane + 2 workers), with namespace shop containing web (nginx), api (podinfo 6.17.0), and db (postgres:17 StatefulSet).
  • Lab machine: Azure VM Standard_D4s_v5 (Ubuntu 24.04, resource group rg-k8s-lab, region canadacentral), 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
Is the db from hour 2 different?If you did not configure a PVC for db in hour 2 (or it has a different name), that's fine. Module 6 provides a complete StatefulSet manifest and rebuilds db. If the shop namespace does not exist, run 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
AKS built-in StorageClasses (Microsoft Learn, verified 2026-11-08 / 2026-10-16)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.
Cost and cleanup2 × D2s_v5 (about 0.1 USD/hour per node, varies slightly by region) + managed OS disks + lab PVC disks and snapshots. The free-tier control plane is not charged. Rough estimate: 0.25–0.4 USD/hour (see the Azure pricing calculator for exact figures). When the lab is finished, be sure to run 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.
PermissionsCreating an AKS cluster requires Contributor (or equivalent) permissions on the resource group. The cluster's managed identity creates disks and snapshots in the node resource group. Do not run this lab in a shared production subscription.

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
Self-check list

Module 1 · Volume basics

00:00 – 07:00 · What does a volume's lifecycle depend on? Pod-internal volumes vs persistent volumes, explained thoroughly
7 minimage volume GA v1.36RRO mount GA v1.33Importance ★★★★
Learning objectives
  • 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: Memory and sizeLimit, 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, and recursiveReadOnly.
Prerequisites:ConfigMap/Secret from hour 2; Docker course Module 6 (volume / bind / tmpfs). Importance:★★★★ (the foundation for all later modules)

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

CategoryVolume typeLifecycleTypical 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 restartsCache, 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 registryModel files, static assets, plugins, and other data decoupled from the application image
Node-localhostPath, local PVTied to the node; if the Pod moves to another node, it cannot "see" the dataNode agents (logging, CNI, CSI node plugin); local PVs for high-performance local disks
PersistentpersistentVolumeClaimPVC and PV are independent of the Pod; deleting the Pod does not lose dataDatabases, 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: true ConfigMaps/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: true makes only the top-level mount read-only. If there are sub-mounts under the volume, use recursiveReadOnly: 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

DockerKubernetes equivalentDifference
Named volumePVC + PVK8s creates cloud disks dynamically through a StorageClass, and they can be re-attached across nodes
bind mounthostPathIn K8s it is bound to a node and carries high security risk; PSS Baseline forbids it
tmpfsemptyDir medium: MemoryIn K8s it counts toward Pod memory, and it survives container restarts (the Pod still exists)
Anonymous volume + --rmemptyDir / generic ephemeral volumeLifecycle is bound to the Pod, not the container
Common misconceptions① "emptyDir is cleared when the container restarts": wrong. When the container crashes and restarts (RestartCount+1), emptyDir is kept. It is deleted only when the Pod is deleted or evicted. ② "During a Deployment rolling update, emptyDir carries over to the new Pod": wrong. The new Pod has a new UID, so its emptyDir is brand new. ③ "If I change the ConfigMap, the file mounted with subPath also changes": wrong. subPath does not update in place, so the Pod must be restarted. ④ "A read-only hostPath is safe": not necessarily. It can still read sensitive files on the node (kubelet credentials, other Pods' data).

Architecture diagram: where the volumes of one Pod sit on the node

Pod shop/cache-demo (uid 7f3a…) Container app /cache ← emptyDir/etc/app ← configMap (ro)/podinfo ← downwardAPI/models ← image (ro)/data ← PVC sidecar log-shipper /cache ← the same emptyDir(shared files between containers) Node lab-worker: /var/lib/kubelet/pods/7f3a…/volumes/ kubernetes.io~empty-dir/cache (node disk) kubernetes.io~configmap/conf (node disk + atomic symlink) kubernetes.io~secret/tls (tmpfs, not on disk) kubernetes.io~downward-api/podinfo kubernetes.io~image/models (OCI layers mounted at runtime) kubernetes.io~csi/pvc-…/mount (PV, independent lifecycle) kube-apiserver / etcdConfigMap, Secret, Pod metadatakubelet watch → refreshes the ..data linksubPath mount is not refreshed Image registry (OCI)image volume: pulled according to pullPolicyRead-only, noexec Storage backend (cloud disk / NFS / local)PVC → PV → CSI driverSurvives Pod deletion(detailed in Modules 2–3)
Figure 1-1 The kubelet prepares a volume directory for each Pod on the node, then bind-mounts them into the containers through CRI

Flow diagram: where volume data goes under three events

Event ① Container crash and restart② Delete Pod (recreated)③ Node failure / rescheduling emptyDir (disk) Kept ✓Deleted ✗Lost ✗ hostPath / local PV Kept ✓Kept (visible only on the same node)Not visible on the new node ✗ PVC (cloud disk / network storage) Kept ✓Kept ✓ (remounted)detach → attach to new node ✓
Figure 1-2 The lifecycle determines where data goes: emptyDir follows the Pod, hostPath follows the node, and a PVC exists independently

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.

Pod / container
Actual data location

Core commands and fields

Command / fieldPurposeKey parameters / notes
kubectl explain pod.spec.volumes --recursive | lessView all volume types and fieldsWorks offline; fields depend on the cluster version
kubectl explain pod.spec.containers.volumeMountsView mount fieldsreadOnly, recursiveReadOnly, subPath, subPathExpr, mountPropagation
kubectl describe pod PThe Volumes section shows volume types and sources; Events show mount errorsWatch for FailedMount and Evicted
kubectl exec P -c C -- df -h /cacheView volume capacity and filesystemMemory volumes show tmpfs
kubectl get pod P -o jsonpath='{.status.containerStatuses[*].restartCount}'Check whether the container has restartedVerify that emptyDir survives container restarts
docker exec lab-worker ls /var/lib/kubelet/pods/UID/volumesView the volume directory on the node in kindUID: 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)

Goal and environment: kind cluster lab, namespace shop. Use 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'
Container crash and restart: make the main process exit with code 1, and the kubelet creates a new container according to restartPolicy (Always). The Pod UID does not change. Note: running 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.

View the actual directories on the node:
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.

Delete the Pod: a bare Pod is not recreated, so we recreate a Pod with the same name ourselves and observe the data:
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.

Try sizeLimit eviction (optional):
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".
Cleanup:
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.

Command-line exercises
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.

Scenario analysis
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

▶
Kubernetes Volumes explained | Persistent Volume, Persistent Volume Claim & Storage Class — TechWorld with Nana
English · Duration as shown on the YouTube page · Suited to this module and Module 2: the overall concepts from volumes to PV/PVC/SC (recorded on an earlier version; newer features such as image volumes are not covered)

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.

Shot 1 · 0:00–0:20
Visual:A Pod box with two containers, and a node disk below.
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.
Shot 2 · 0:20–0:50
Visual:An emptyDir directory appears under /var/lib/kubelet/pods/uid/volumes. The container crashes (red flash), restarts, and the files are still there.
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.
Shot 3 · 0:50–1:20
Visual:A configMap is updated and the ..data link switches. Beside it, a file mounted with subPath keeps its old value and is highlighted in red.
Narration:The kubelet refreshes ConfigMaps and Secrets automatically, but files mounted with subPath are not refreshed.
Shot 4 · 1:20–1:50
Visual:A hostPath volume connects to the node's /etc, and a warning shield appears: "PSS Baseline forbids".
Narration:hostPath exposes the node's filesystem directly, so business workloads should not use it.
Shot 5 · 1:50–2:20
Visual:A node fails and the Pod moves to a new node. emptyDir and hostPath data stay on the old node, while the PVC follows the Pod and is mounted again.
Narration:To carry data across Pods and nodes, you need persistent volumes. That is the star of the next module.
Or score ≥ 70% on the quiz

Module 2 · PV · PVC · StorageClass

07:00 – 15:00 · How the request "I want a 10Gi disk" becomes a real disk in the cluster
8 mincore/v1 · storage.k8s.io/v1 GAPVC Unused condition Beta v1.37Importance ★★★★★
Learning objectives
  • 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 Unused condition to find idle PVCs.
Prerequisites:Module 1, and the controller and watch mechanism from hour 1. Importance:★★★★★

What: The division of labor among the three objects

ObjectScopeWho creates itAnalogyKey fields
StorageClass (storage.k8s.io/v1)ClusterPlatform admin / AKS built-in"Storage tier"provisioner, parameters, reclaimPolicy, volumeBindingMode, allowVolumeExpansion, mountOptions, allowedTopologies
PersistentVolumeClaim (v1)NamespaceApplication developer / StatefulSet template"Request form"accessModes, resources.requests.storage, storageClassName, volumeName, dataSource(Ref), volumeMode
PersistentVolume (v1)ClusterAdmin (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

  1. PVC creation: the DefaultStorageClass admission plugin fills in the default SC for a PVC that does not specify storageClassName. Explicitly writing storageClassName: "" means dynamic provisioning is forbidden, and the PVC binds only to a static PV.
  2. 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).
  3. If none is found and the SC is Immediate: the controller adds the annotation volume.kubernetes.io/storage-provisioner to the PVC, handing it to the external provisioner to create the volume right away.
  4. If the SC is WaitForFirstConsumer, the PVC stays Pending (event WaitForFirstConsumer) until a Pod references it. After the scheduler's VolumeBinding plugin picks a node for the Pod, it writes the annotation volume.kubernetes.io/selected-node on the PVC.
  5. 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 nodeAffinity topology). The PV controller binds the PV and PVC in both directions (PV.spec.claimRef ↔ PVC.spec.volumeName), and both become Bound.
  6. 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

PVC phase
  • Pending: not yet bound (waiting for WFFC, no matching PV, or provisioning failed)
  • Bound: bound to a PV
  • Lost: the bound PV no longer exists (data may be lost)
PV phase
  • Available: free, can be bound
  • Bound: bound to a PVC
  • Released: the PVC has been deleted but the resource has not been reclaimed yet (with Retain, it stays here)
  • Failed: automatic reclamation failed
The PV's 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 volumeName to pin a specific PV, and sets storageClassName to match the PV (or both are "").

Comparison with similar technologies

ConceptKubernetesDocker / ComposeAWS ECS / VM world
Requesting storagePVCNamed volume in volumes:EBS volume configuration in the task definition
Storage tierStorageClassvolume driver + driver_optsEBS volume types gp3/io2
Real storagePV/var/lib/docker/volumes/xOne EBS volume / Azure managed disk
Common misconceptions① "A PVC stuck in Pending means it is broken": with WaitForFirstConsumer, Pending is expected behavior when no Pod is using it. ② "Deleting the PV deletes the disk": you should delete the PVC, and the provisioner handles the disk according to reclaimPolicy. Deleting the PV directly can leave orphaned cloud disks (newer versions have a PV deletion-protection finalizer to mitigate this). ③ "Changing the StorageClass affects existing volumes": SC parameters are only used at provisioning time, so existing PVs are unaffected (most SC fields are also immutable). ④ "The PVC capacity is the upper limit": for local-path or hostPath-type volumes, capacity is only bookkeeping and does not limit writes.

Architecture diagram: control-plane components involved in storage

kube-apiserver + etcdPVC · PV · SC · VolumeAttachment kube-controller-managerPV controller (binder)AD controller (attach/detach)PVC/PV protection · expand kube-schedulerVolumeBinding plugin: topology / capacityVolumeRestrictions · NodeVolumeLimitsWrites the selected-node annotation CSI controller (Deployment)external-provisioner / attacherresizer / snapshotter→ cloud API (create / attach disks) On each node: kubelet (volume manager) + CSI node plugin (DaemonSet)NodeStage (format + mount to globalmount) → NodePublish (bind mount into the Pod directory) watch PVC/PVwatch PVC / VolumeAttachment
Figure 2-1 All components collaborate by watching the apiserver and do not call each other directly

Flow diagram: WaitForFirstConsumer dynamic provisioning sequence

PVC createdPending Pod references itWFFC wait ends Scheduler picks a nodeselected-node ProvisionCreateVolume BindPV ↔ PVC AttachVolumeAttachment MountStage + Publish Immediate mode: steps 4–5 happen right after the PVC is created, and the disk may be built in an availability zone where the Pod cannot be scheduled
Figure 2-2 local-path has no Attach step (it is a local directory); Azure Disk has one; Azure Files' CSIDriver sets attachRequired=false

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.

kubectl apply kube-apiserveradmission: DefaultStorageClass PV controllerkube-controller-manager kube-schedulerVolumeBinding external-provisioner+ disk.csi.azure.com Azure managed diskARM API AD controller → attacherVolumeAttachment kubelet + CSI node pluginNodeStage / NodePublish Pod db-0 (Running)/var/lib/postgresql/data PVC: — · PV: —
Ready. Click "Play".
$ kubectl apply -f pvc.yaml -f pod.yaml

Core commands

CommandPurposeKey parameters / notes
kubectl get scList StorageClasses and the default SCDefault SC marked with the suffix (default)
kubectl get pvc -A -o wideView PVC status, bound PV, capacity, VOLUMEMODE-w to watch status changes
kubectl get pv --sort-by=.spec.capacity.storageView PVs with CLAIM, RECLAIM POLICY, STATUSPVs in Released state must be handled manually
kubectl describe pvc NAMECheck events: WaitForFirstConsumer, ProvisioningFailed, ExternalProvisioningFirst troubleshooting command
kubectl patch sc NAME -p '{"metadata":{"annotations":{"storageclass.kubernetes.io/is-default-class":"false"}}}'Remove the default SCWhen 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 whenRequires 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)

Observe WaitForFirstConsumer: create only the PVC, with no Pod.
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
Full dynamic provisioning process: apply 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.

Data survives Pod deletion:
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
v1.37 Beta: Unused condition: after deleting the Pod, observe the PVC conditions.
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 and Retain: apply 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.

Cleanup:
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).

Command-line exercises
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 sc
Scenario analysis
A 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

▶
Kubernetes Volumes explained | Persistent Volume, Persistent Volume Claim & Storage Class — TechWorld with Nana
English · Duration as shown on the YouTube page · Diagram walkthrough of the relationship between PV, PVC, and SC (does not cover WFFC timing or new v1.37 features)

Official documentation

Video storyboard script

This lesson cannot directly generate the video or MP3. The storyboard and narration script are provided instead.

Shot 1 · 0:00–0:25
Visual: A developer holds a request slip, "PVC: 10Gi RWO". In front of the platform admin are three plan cards labeled StorageClass.
Narration: A PVC is the request slip. A StorageClass is the plan. The PV is the actual disk.
Shot 2 · 0:25–1:00
Visual: The PVC reaches the apiserver. The PV controller fails to find a free PV, and the PVC shows a "Pending · waiting for first consumer" label.
Narration: In WaitForFirstConsumer mode, Pending is normal when no Pod is using the PVC.
Shot 3 · 1:00–1:40
Visual: A Pod appears. The scheduler picks zone 2 out of three zones and tags the PVC with selected-node. The provisioner creates the disk in zone 2.
Narration: Pick the node first, then create the disk. This keeps the disk and the Pod in the same zone.
Shot 4 · 1:40–2:10
Visual: A two-way arrow connects the PV and the PVC. Both turn green and show Bound. Then the attach and mount animations play.
Narration: Binding is one-to-one. The PV records claimRef, and the PVC records volumeName.
Shot 5 · 2:10–2:30
Visual: After the Pod is deleted, the PVC condition changes to Unused=True and shows a timestamp.
Narration: This beta feature in v1.37 shows when the PVC became idle.
Or score 70% or higher on the quiz

Module 3 · CSI Architecture and Azure Disks

15:00 – 22:00 · From CreateVolume to NodePublishVolume: which Kubernetes object each gRPC call maps to
7 minCSI GA · in-tree migration completedisk.csi.azure.com · file.csi.azure.comImportance ★★★★
Learning goals
  • 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.
Prerequisite: Module 2. Importance: ★★★★ (the core model for troubleshooting and choosing storage)

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 formContainerObject watchedCSI methods called
Controller plugin (Deployment, 1–2 replicas, leader election)external-provisionerPVC (with the storage-provisioner annotation)CreateVolume / DeleteVolume, create and delete PVs
external-attacherVolumeAttachmentControllerPublishVolume / ControllerUnpublishVolume
external-resizerPVC's spec.resources is increasedControllerExpandVolume
external-snapshotter (csi-snapshotter)VolumeSnapshotContentCreateSnapshot / 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), runs mkfs if 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

ObjectCreated byPurpose
CSIDriverDriver install manifestDeclares driver capabilities: attachRequired (whether ControllerPublish is needed), podInfoOnMount, fsGroupPolicy (who changes ownership: File / ReadWriteOnceWithFSType / None), volumeLifecycleModes, storageCapacity, requiresRepublish, seLinuxMount
CSINodekubelet (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)
VolumeAttachmentAD controllerThe 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 typeBlock device (managed disk), formatted as ext4 or xfs on the nodeSMB 3.x or NFS 4.1 file share
Access modesRWO (/RWOP); multi-node sharing only in the special case of a shared diskRWX / ROX / RWO
attachRequired (ControllerPublish attaches the disk to a LUN on the VM)Not required (the node mounts the share directly over the network)
Performance tiersStandard HDD/SSD, Premium SSD, Premium SSD v2 (IOPS and throughput can be set independently; cachingMode None only), Ultra DiskStandard (HDD) / Premium (SSD, FileStorage account)
RedundancyLRS; Premium_ZRS and StandardSSD_ZRS can be attached across zonesLRS / ZRS (storage account level)
Snapshots / clones / expansionSupported (incremental snapshots by default). Online expansion up to 4 TiB; Premium SSD v2 and Ultra have no such limitExpansion supported; snapshots are shared snapshots
Node limitLimited 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 usesDatabases and single-writer stateful servicesShared 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).
Common misconceptions ① "The kubelet calls the Node service through a sidecar." No. The kubelet calls the driver's Node service directly over a Unix socket. The sidecar only handles registration. ② "The kubelet creates the VolumeAttachment." No. The AD controller in kube-controller-manager creates it. ③ "local-path is also a CSI driver." No. It is a non-CSI external provisioner with no attach, snapshot, or expansion support. ④ "Deleting the PV immediately deletes the cloud disk." No. external-provisioner responds to PVC deletion and the reclaim policy. The AKS documentation recommends deleting the PVC, not the PV.

Architecture diagram: how the CSI driver is deployed in the cluster

kube-apiserverPVC · PV · VolumeAttachment · VolumeSnapshotContent Controller plugin Pod (Deployment) csi-provisioner csi-attacher csi-resizer csi-snapshotter liveness-probe CSI driver (Identity + Controller)unix:///csi/csi.sock (a shared emptyDir inside the Pod) Node plugin Pod (DaemonSet, privileged) node-driver-registrar liveness-probe CSI driver (Identity + Node)/var/lib/kubelet/plugins/<driver>/csi.sock mountPropagation: Bidirectional (mount propagation back to the host) kubelet (volume manager)Calls NodeStage / NodePublish directly over gRPCWrites CSINode at registration (nodeID, topology, allocatable) Cloud / storage backendAzure Resource Manager: Disks / VM dataDisks / Storage(uses the cluster managed identity or the kubelet identity) watch / update(the registrar does not watch the API)
Figure 3-1: The Controller plugin responds to API objects through sidecars. The Node plugin is called directly by the kubelet.

Flowchart: CSI methods ↔ Kubernetes objects ↔ Azure operations

CreateVolumeTrigger: PVC (+selected-node)Output: PV (volumeHandle)Azure: PUT Microsoft.Compute/disksSidecar: external-provisioner ControllerPublishVolumeTrigger: VolumeAttachmentOutput: status.attached=trueAzure: LUN added to the VM's dataDisksSidecar: external-attacher NodeStageVolumeCaller: kubeletFind the device by LUN → mkfs (first time only)Mount to globalmountOnce per volume per node NodePublishVolumeCaller: kubeletBind mount to pods/<uid>/…/mountfsGroup changes ownership (per fsGroupPolicy)Once per Pod → the CRI mounts it into the container
Figure 3-2: On deletion, steps run in reverse: NodeUnpublish → NodeUnstage → ControllerUnpublish → DeleteVolume (depending on reclaimPolicy)

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.

PVC data-db-0Pending → Bound external-provisionersidecar azuredisk controllerIdentity + Controller Azure Resource Managerdisks / virtualMachines PV pvc-3c1e…csi.volumeHandle AD controllerkube-controller-manager VolumeAttachmentcsi-9f8e… (attached?) external-attachersidecar kubelet (aks-nodepool1-…-1)volume manager / reconciler azuredisk node pluginIdentity + Node Container postgres/var/lib/postgresql/data
Ready. Click "Play".
$ kubectl apply -f db-statefulset.yaml # volumeClaimTemplates: data, storageClassName: managed-csi

Core commands

CommandPurposeNotes
kubectl get csidriverList installed drivers and their capabilitiesATTACHREQUIRED, PODINFOONMOUNT, MODES, FSGROUPPOLICY (-o wide)
kubectl get csinode NODE -o yamlDrivers registered by nodes, topology keys, volume limitsspec.drivers[].allocatable.count
kubectl get volumeattachmentAttach intent and statusATTACHED column; -o yaml shows attachError
kubectl -n kube-system get pods -l app=csi-azuredisk-node -o wideDisk CSI node plugin on AKSLabels may differ, so check the actual values: kubectl -n kube-system get ds | grep csi
kubectl -n kube-system logs POD -c azuredisk --tail=100Driver logs, including every gRPC callSearch for GRPC call: /csi.v1.Controller/
az disk list -g MC_… -o tableSee the provisioned disk on the Azure sideThe 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.

Install the VolumeSnapshot CRDs and snapshot-controller (external-snapshotter v8.7.0, the latest version as of 2026-10-13):
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.

Deploy the hostpath CSI driver:
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.

Create a StorageClass that supports expansion, and note the node where the driver runs:
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"]
Verify the CSI path: Pin the Pod to the node where the driver runs. The hostpath driver only provides volumes on that 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.

Keep the 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
Command-line exercises
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)'
Scenario analysis
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

Video storyboard script

This lesson cannot directly generate the video or MP3. The storyboard and narration script are provided instead.

Shot 1 · 0:00–0:20
Visual: On the left, the Kubernetes logo. On the right, several storage vendors. In the middle, a pipe labeled "CSI" with gRPC.
Narration: CSI is the standard socket between Kubernetes and storage. Vendors only need to implement three groups of gRPC services.
Shot 2 · 0:20–0:55
Visual: The Controller Pod expands. Four sidecars each watch one kind of object: PVC, VolumeAttachment, PVC expansion, and VolumeSnapshotContent.
Narration: The sidecars understand Kubernetes. The driver only needs to understand storage.
Shot 3 · 0:55–1:30
Visual: CreateVolume makes Azure create a disk. ControllerPublish attaches it to LUN 1 on the VM.
Narration: Creation and attach happen in the control plane. The results are written back to the PV and the VolumeAttachment.
Shot 4 · 1:30–2:05
Visual: Inside the node: the kubelet calls NodeStage (mkfs and globalmount), then calls NodePublish (bind mount into the Pod directory).
Narration: The kubelet makes the node-side calls directly: one stage, then multiple publishes.
Shot 5 · 2:05–2:30
Visual: Comparison cards: Azure Disk (block, RWO, needs attach) vs. Azure Files (file, RWX, no attach needed).
Narration: Choosing the right driver is the first step to choosing the right access mode.
Or score 70% or higher on the quiz

Module 4 · Access Modes · Reclaim Policies · Topology

22:00 – 29:00 · "Can multiple Pods write at the same time?" "Is the disk still there after I delete the PVC?" "The disk is in zone 1. Can the Pod run in zone 2?"
7 minReadWriteOncePod GA v1.29Recycle deprecatedImportance ★★★★★
Learning goals
  • 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.
Prerequisites: Modules 2–3. Importance: ★★★★★ (a wrong choice can cause data loss or an availability incident)

What: The four access modes

ModeAbbreviationExact meaningCommon misreading
ReadWriteOnceRWOA 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"
ReadOnlyManyROXCan be mounted read-only by multiple nodesAssumed that all block storage supports it
ReadWriteManyRWXCan be mounted read-write by multiple nodes at the same timeAssumed the application can safely write to the same file concurrently (this requires the application to coordinate its own writes)
ReadWriteOncePodRWOPCan 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

BackendRWOROXRWXRWOPNotes
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

PolicyAfter the PVC is deletedUse case
Delete (default for dynamic provisioning)external-provisioner calls DeleteVolume. The cloud disk is deleted, and the PV object is removed.Development / rebuildable data
RetainThe 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 againDo 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.preferred of 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_ZRS and StandardSSD_ZRS disks 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.
Common misconceptions ① "RWO guarantees that only one Pod writes." No. Multiple Pods on the same node can all mount it. To guarantee a single Pod, use RWOP. ② "RWX lets any application scale out horizontally." No. If a database file sits on an RWX share and multiple instances open it at the same time, the data will be corrupted. ③ "ZRS is a backup." No. ZRS protects against zone failures, but not against accidental deletion, logical corruption, or ransomware. You still need snapshots and backups (Modules 5 and 7). ④ "With Retain, there is nothing else to manage." No. A Released PV still incurs charges, and it will not rebind automatically.

Architecture diagram: the relationship between access modes and nodes / Pods

RWO Node APod 1 ✓Pod 2 ✓Multiple Pods on the same node can share Node BPod 3 ✗ Multi-Attach RWOP Node APod 1 ✓Pod 2 ✗Rejected by the scheduler (Pending) Node BPod 3 ✗ RWX Node APod 1 ✓ Pod 2 ✓ Node BPod 3 ✓ (read-write)Azure Files / NFS ROX Node APod 1 read-only ✓ Node BPod 2 read-only ✓Write → EROFS
Figure 4-1: RWO constrains the node; RWOP constrains the Pod

Flowchart: failover of LRS and ZRS disks across zones

Zone 1 (failed)Node n1 ✗Premium_LRS disk: in zone 1 only→ db-0 cannot be mounted elsewhere ✗ zone 2Node n2 ✓Premium_ZRS disk (synchronous replicas)db-0 rebuilt and attached ✓ zone 3Node n3 ✓ZRS replica LRS approach: depends on application-level replication (primary/replica), or restoring from a snapshot or backup into a new zone
Figure 4-2: ZRS lets a single-replica stateful application survive a zone failure. LRS requires application-level replication.

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.

Storage backend
Access mode
Scenario

Core commands

CommandPurposeNotes
kubectl get pv -o custom-columns=NAME:.metadata.name,MODES:.spec.accessModes,POLICY:.spec.persistentVolumeReclaimPolicy,STATUS:.status.phaseList access modes and reclaim policiesAudit production PVs for Retain
kubectl patch pv PV -p '{"spec":{"persistentVolumeReclaimPolicy":"Retain"}}'Change to Retain on a live PVSafeguard before a risky operation
kubectl get pv PV -o jsonpath='{.spec.nodeAffinity}'Check topology constraintsExplain volume node affinity conflict
kubectl get nodes -L topology.kubernetes.io/zoneZone of the nodeAKS: canadacentral-1/2/3
kubectl get csinode NODE -o jsonpath='{.spec.drivers[*].allocatable.count}'Node volume limitThe 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)

RWO: two Pods on the same node can read and write at the same time (hostpath-csi, pinned to the driver's node):
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>
Check why RWOP rejects the second Pod:
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.

allowedTopologies: Simulate zone labels on kind nodes, and create an SC that allows only zone-a.
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.

Retain walkthrough: Change the zoned PV to Retain, delete the PVC, and confirm the data directory still exists.
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
Cleanup:
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.

Command-line exercises
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"}}'
done
2. Check which zone a given PV is restricted to.
kubectl get pv PV -o jsonpath='{.spec.nodeAffinity.required.nodeSelectorTerms[*].matchExpressions[*].values}{"\n"}'
Scenario analysis
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

Video storyboard script

This lesson cannot directly generate the video or MP3. The storyboard and narration script are provided instead.

Shot 1 · 0:00–0:25
Visual: Two nodes. An RWO disk is attached to node A, and two Pods on node A are both writing. A Pod on node B is blocked by a red X.
Narration: The "Once" in RWO refers to a node, not a Pod.
Shot 2 · 0:25–0:50
Visual: An RWOP disk. A second Pod on the same node is marked Pending by the scheduler.
Narration: To make sure only one Pod writes, use ReadWriteOncePod, which became generally available in v1.29.
Shot 3 · 0:50–1:20
Visual: The PVC is deleted. A disk with the Delete policy turns to ash. A disk with the Retain policy becomes Released and still exists.
Narration: For production data, use Retain. The disk stays behind when you delete the PVC.
Shot 4 · 1:20–2:00
Visual: Three availability zones. Zone 1 goes dark. The LRS disk is stuck in zone 1, while the ZRS disk is remounted in zone 2.
Narration: ZRS lets a single-replica application survive a zone failure, but it is not a backup.
Or score 70% or higher on the quiz

Module 5 · Expansion · Snapshots · Cloning

29:00 – 36:00 · What do you do when the disk is full? How do you keep a fallback before an upgrade? How do you copy test data in seconds?
7 minsnapshot.storage.k8s.io/v1 GAVolumeGroupSnapshot GA v1.36Volume populator GA v1.33Importance ★★★★
Learning goals
  • Perform an online expansion: confirm allowVolumeExpansion, edit the PVC's spec.resources.requests.storage, and understand the two-phase ControllerExpand → NodeExpand flow and the FileSystemResizePending condition. 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 (dataSource kind VolumeSnapshot) and clone a PVC (kind PersistentVolumeClaim).
  • Understand VolumeGroupSnapshot (crash-consistent across multiple volumes) and volume populators (dataSourceRef pointing to a custom resource).
Prerequisites: Module 3 (you installed the hostpath CSI and snapshot components on kind, or use AKS). Importance: ★★★★

What: Three data operations

OperationObject you change or createResponsible componentCSI callPrerequisite
ExpansionIncrease the PVC's spec.resources.requests.storageexternal-resizer (control plane) + kubelet (node)ControllerExpandVolume → NodeExpandVolume (resize2fs / xfs_growfs)SC has allowVolumeExpansion: true + driver support
SnapshotVolumeSnapshotsnapshot-controller creates VolumeSnapshotContent; csi-snapshotter calls the driverCreateSnapshotCRDs + snapshot-controller + VolumeSnapshotClass + driver support
Restore from snapshotNew PVC with dataSource: {kind: VolumeSnapshot}external-provisionerCreateVolume (content_source=snapshot)Same namespace; capacity ≥ restoreSize
CloneNew PVC with dataSource: {kind: PersistentVolumeClaim}external-provisionerCreateVolume (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

  1. 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.)
  2. external-resizer calls ControllerExpandVolume (on Azure, this resizes the managed disk). On success, it updates PV.spec.capacity.
  3. If a filesystem resize is needed, the PVC shows the FileSystemResizePending condition. If the volume is online (mounted), the kubelet calls NodeExpandVolume during its next sync to expand the filesystem. If the volume is offline, the resize waits for the next Pod to mount it.
  4. When complete, status.capacity updates to 2Gi and the condition clears. status.allocatedResourceStatuses records progress (for example, ControllerResizeInProgress or NodeResizePending).
  5. 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 CHECKPOINT first 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

MethodGranularityConsistencySpeedWorks across regions or clusters?
CSI snapshotSingle volumeCrash-consistentSeconds (incremental)Usually no (same region in the cloud)
VolumeGroupSnapshotMultiple volumesCrash-consistent within the groupSecondsNo
PVC cloneSingle volumeCrash-consistentDepends on the backendNo (same namespace and same SC)
pg_dump / logical backupDatabaseTransaction-consistentProportional to data sizeYes
Velero (Module 7)Namespace / resources + volumesHooks can achieve application consistencyMediumYes (object storage)
Common misconceptions ① "Changing the StatefulSet's volumeClaimTemplates expands all replicas." The storage field in the template generally cannot be changed directly (check the official documentation for v1.37, as related KEPs are still in progress). In practice, you patch each PVC one at a time. ② "The application sees the new capacity right away after expansion." No. You must wait for NodeExpand to finish, and 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

PVC data-db-0Namespace shop VolumeSnapshotsource.persistentVolumeClaimName New PVC (restored)dataSource: VolumeSnapshot snapshot-controllerVS → creates VSC and binds both ways VolumeSnapshotClassdriver · deletionPolicy · parameters VolumeSnapshotContent (cluster-scoped)status.snapshotHandle · readyToUse csi-snapshotter → CSI CreateSnapshotAzure: Microsoft.Compute/snapshots (incremental) external-provisionerCreateVolume(content_source)
Figure 5-1: VolumeSnapshot / Content / Class map one-to-one to PVC / PV / SC

Flowchart: the two phases of online expansion

kubectl patch pvc1Gi → 2Gi apiserver validationallowVolumeExpansion · can only grow ControllerExpandexternal-resizer · PV=2Gi FileSystemResizePendingPVC condition NodeExpandkubelet · resize2fs
Figure 5-2: PVC status.capacity changes to the new value only after NodeExpand completes

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

CommandPurposeNotes
kubectl patch pvc P -p '{"spec":{"resources":{"requests":{"storage":"2Gi"}}}}'ExpandCan also use kubectl edit; can only increase
kubectl get pvc P -o jsonpath='{.status.conditions}'Watch Resizing / FileSystemResizePendingUse together with .status.allocatedResourceStatuses
kubectl get volumesnapshotclass / vsclassSnapshot classSet as default with the annotation snapshot.storage.kubernetes.io/is-default-class: "true"
kubectl get vs,vscSnapshots and snapshot contentsREADYTOUSE, RESTORESIZE, SNAPSHOTCONTENT
kubectl wait vs/S --for=jsonpath='{.status.readyToUse}'=trueWait for the snapshot to be availableMust 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)

Prepare data: Use the 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
Expand online to 2Gi (skip this if you already did it in the Commands tab), and confirm that the Pod did not restart:
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
Create a snapshot and wait until it is ready (save 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
Simulate an accidental deletion, then restore from the snapshot to a new PVC and verify:
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
Clone (clone from the source PVC that was just accidentally deleted, and verify that the clone is a copy of the current state):
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.)

(Optional) Repeat on AKS: Change 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).

Cleanup (keep csi-demo as a reference for the capstone lab, or delete everything):
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.

Command-line exercise
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=300s
2. 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"}'
Scenario analysis
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

Video storyboard script

This course file cannot generate the video or MP3 directly, so a storyboard and narration script are provided instead.

Shot 1 · 0:00–0:25
Scene: The disk usage bar turns red at 90%, and the PVC size changes from 10Gi to 20Gi. Two gears appear below it: ControllerExpand and NodeExpand.
Narration: Expansion happens in two steps. First the cloud disk grows. Then the filesystem grows.
Shot 2 · 0:25–0:45
Scene: An attempt to change 20Gi back to 10Gi shows a red Forbidden error.
Narration: A PVC can only grow. It cannot shrink.
Shot 3 · 0:45–1:20
Scene: A VolumeSnapshot card creates a VolumeSnapshotContent, which links to the Azure incremental snapshot icon.
Narration: A snapshot has three objects. Each one matches a PVC, PV, or StorageClass.
Shot 4 · 1:20–1:55
Scene: Data is deleted by mistake. A new PVC uses dataSource to point at the snapshot, and 100 rows come back.
Narration: Restoring means using the snapshot as the data source to create a new disk.
Shot 5 · 1:55–2:20
Scene: Two disks are boxed together at once, with a click sound effect.
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.
Or score ≥ 70% on the quiz

Module 6 · StatefulSet + PostgreSQL in practice

36:00 – 46:00 · One disk per replica: delete a Pod, scale to 0, then scale back up, and the data is still there
10 minPVC retention policy GA v1.32StatefulSet Recreate strategy Alpha v1.37Importance ★★★★★
Learning objectives
  • Understand how volumeClaimTemplates creates 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.
Prerequisites: hour 2 StatefulSet basics; Modules 2–5. Importance: ★★★★★

What: three things a StatefulSet gives a stateful app

  • Stable network identity: Pod names db-0, db-1… plus a headless Service give db-0.db.shop.svc.cluster.local.
  • Stable storage: the data template in volumeClaimTemplates creates a PVC data-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)

FieldRetain (default)Delete
whenDeleted (deleting the StatefulSet)PVC is keptAfter 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 upPVCs 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

PitfallSymptomCorrect approach
lost+foundAn 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)
PermissionsRunning as non-root gives Permission denied; or recursively chowning many files on every start, which is very slowsecurityContext.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 shutdownIf 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 availabilityChange replicas to 3 and you get three unrelated, empty databasesStreaming 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

OptionBest forYou are responsible for
Plain StatefulSet (this hour)Learning, development, single-instance non-critical dataBackups, 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 environmentsThe 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 serverMost production workloads, where the team does not want to run a databaseYou only manage connections and parameters. Azure provides zone-redundant HA, automatic backups, and PITR. Access is through Private Endpoint or VNet integration.
Common misconceptions (1) "Deleting a StatefulSet deletes the data": the default is whenDeleted=Retain, so the PVCs are kept. (2) "Scaling to 0 loses data": the default is whenScaled=Retain, so scaling back up remounts the PVCs with the same names. (3) "A StatefulSet fixes node failures automatically": when a node is NotReady, the StatefulSet does not create a Pod with the same name somewhere else (this prevents two db-0 Pods from writing at the same time). You need to confirm the node is shut down, or use the out-of-service taint (Module 8). (4) "Changing volumeClaimTemplates updates existing PVCs": it does not. The template is only used to create new PVCs.

Diagram: object relationships in shop/db

StatefulSet dbserviceName: db · replicas: 2volumeClaimTemplates: dataretention: Retain / Retain headless Service dbdb-0.db.shop.svc · db-1.db.shop.svc Pod db-0lab-worker Pod db-1lab-worker2 PVC data-db-0Bound PVC data-db-1Bound PV pvc-aa…Disk A PV pvc-bb…Disk B Container postgres (uid 999, fsGroup 999)mountPath /var/lib/postgresql/data (volume root, may contain lost+found)PGDATA = /var/lib/postgresql/data/pgdata (subdirectory, 0700)
Figure 6-1 The Pod name decides the PVC name: db-0 always uses data-db-0

Flowchart: what happens to the PVCs when scaling to 0 and back up

replicas=2db-0 ↔ data-db-0db-1 ↔ data-db-1 scale --replicas=0Delete db-1 first, then db-0All PVCs kept (Retain) Unused=TruePVC idle but still BoundCloud disk detached, still billed scale --replicas=2db-0 reattaches data-db-0Data unchanged ✓
Figure 6-2 With whenScaled: Delete, the second step deletes data-db-1, and scaling back up gives an empty disk

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.

whenDeleted:whenScaled:
Pods
PVCs

Core commands

CommandPurposeNotes
kubectl -n shop scale sts db --replicas=NScalingOrderedReady: one at a time
kubectl -n shop rollout status sts dbWait for the update or scaling to finishCommon in CI
kubectl -n shop get pvc -l app=dbList the PVCs created from the templatePVCs inherit the labels from the template's metadata.labels and selector labels
kubectl -n shop delete sts db --cascade=orphanDelete the StatefulSet but keep its PodsUse after changing an immutable field (such as storage in the template), to rebuild
kubectl -n shop exec -it db-0 -- psql -U shop -d shopOpen a shell in the databaseVerify the data
kubectl -n shop get pvc data-db-0 -o jsonpath='{.metadata.ownerReferences}'Check the owner set by the retention policyWith 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)

Deploy: save the manifest from the "Commands" tab as ~/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=180s
Write data:
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 'item-' || g FROM generate_series(1,1000) g;
SELECT count(*) FROM orders;
SQL
CREATE TABLE
INSERT 0 1000
 count
-------
  1000
(1 row)
Delete the Pod: the StatefulSet recreates it with the same name, db-0, and reattaches data-db-0. Watch how long the stop takes (preStop fast shutdown):
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.

Scale to 0, then back up, and watch whenScaled:
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.

Expand the PVC: the request is rejected on kind's default SC, and succeeds on AKS (or the hostpath route).
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.

Keep db and data-db-0 (needed for the Module 7 backup and the capstone lab). Clean up extra resources: 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).

Command-line exercises
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'
Scenario analysis
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

▶
Kubernetes StatefulSet simply explained | Deployment vs StatefulSet — TechWorld with Nana
English · duration as shown on the YouTube page · for understanding StatefulSet stable identity, storage, and the primary-replica replication challenge
▶
Project Lightning Talk: CloudNativePG: Running Postgres The Kubernetes Way - Gabriele Bartolini — CNCF [Cloud Native Computing Foundation]
English · about 5-minute lightning talk (KubeCon NA 2025) · understand running PostgreSQL with an Operator

Official docs

Video storyboard script

This course file cannot generate the video or MP3 directly, so a storyboard and narration script are provided instead.

Shot 1 · 0:00–0:25
Scene: Deployment Pod names are random, while StatefulSet Pod names db-0 and db-1 line up, each attached to its own disk.
Narration: A StatefulSet gives each replica a fixed name and a fixed disk.
Shot 2 · 0:25–0:55
Scene: db-0 is deleted, and a new db-0 appears and reattaches to data-db-0. A counter shows 1000 rows.
Narration: The Pod name decides the PVC name, so the recreated Pod reattaches to the same disk.
Shot 3 · 0:55–1:30
Scene: Scale to 0, and the PVC stays. Scale back to 1, and the data is still there. Switch whenScaled to Delete and demonstrate again: data-db-1 disappears.
Narration: The retention policy, released in the v1.32 release, decides whether PVCs are kept or deleted on scale-down and delete.
Shot 4 · 1:30–2:00
Scene: The lost+found directory at the disk root blocks initdb. After PGDATA is changed to a subdirectory, it passes.
Narration: PostgreSQL's data directory has to be in a subdirectory.
Shot 5 · 2:00–2:30
Scene: Three independent empty databases, versus an Operator-managed primary with two standbys.
Narration: Multiple replicas do not mean high availability. For production, use an Operator or a managed database.
Or score ≥ 70% on the quiz

Module 7 · Backup and restore (Velero)

46:00 – 53:00 · A snapshot is not enough: how to bring shop back when a namespace is deleted, a cluster is destroyed, or a region fails
7 minVelero v1.18.4velero-plugin-for-aws v1.14.4Importance ★★★★★
Learning objectives
  • 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.
Prerequisites: Module 5 (snapshots), Module 6 (shop db). Importance: ★★★★★

What: what to back up and what you can restore

MethodContentsCan restoreCannot restore / notes
etcd snapshot (etcdctl snapshot save)API objects for the whole clusterRoll 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 backupAPI objects selected by namespace or label (packaged as JSON in object storage)Namespace-level accidental deletion, migration to another clusterData restore also needs a volume backup
CSI snapshot (called by Velero)Snapshot of a volume (in the cloud)Fast volume restoreThe 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 KopiaCross-cluster or cross-region restoreNeeds node-agent; time scales with data size
File-system backup (node-agent + Kopia)Reads from the Pod volume directory and uploadsAny 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 backupTransaction-consistent, works across versionsNeeds 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-wait init container into the Pod, which waits for node-agent to write the data back before the app starts.

When: choosing an option

ScenarioRecommended
AKS, and you want it managed and unified with the Azure Backup centerAzure 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 controlVelero (open source) + object storage
DatabaseMainly application-level backups (CloudNativePG's object storage backups + PITR, or the managed database's own backups), with volume or cluster backups as a supplement
Common misconceptions (1) "Snapshots or ZRS mean you don't need backups": accidental deletion, ransomware, and logical corruption get replicated too, and snapshots can be deleted along with the subscription. (2) "A successful Velero backup means it can be restored": run regular restore drills and verify the data (the lab in this module is a drill). (3) "A file-system backup of a running database is consistent": it is not. You need a pre hook that runs pg_dump, or CHECKPOINT/freeze. (4) "A MinIO in the same cluster is safe enough for backups": a production BSL must be outside the cluster (object storage in another region or subscription, with immutability and soft delete enabled).

Diagram: Velero components

velero CLICreate Backup / Restore CRs kube-apiservervelero.io CRD velero serverBackup controller · restore controllerPlugin: aws (S3/MinIO)Built-in CSI support (EnableCSI) node-agent (DaemonSet, one per node)Kopia: reads /var/lib/kubelet/pods/<uid>/volumes/…File-system backup / restore, CSI snapshot data movement BackupStorageLocation (object storage)backups/shop-b1/shop-b1.tar.gz (resource JSON)kopia/shop/… (volume data repository, deduplicated and encrypted) CSI snapshot (VolumeSnapshotClass)or VolumeSnapshotLocation (cloud-native snapshot plugin) Workload shoppre hook: pg_dump → /var/lib/postgresql/data/dumpsPVC data-db-0 (CSI volume)
Figure 7-1 Resources go to object storage; volume data is either snapshotted or uploaded by node-agent using Kopia

Flowchart: backup → disaster → restore

pre hookpg_dump (transaction-consistent) Package resources→ BSL tar.gz Volume dataKopia upload / CSI snapshot Disasterkubectl delete ns shop velero restorePVC → Pod (restore-wait)
Figure 7-2 After restore, always verify: resources complete, Pods Ready, row counts match

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.

velero CLI velero serverbackup controller db-0 · postgres containerpre hook pg_dump kube-apiserverlist all resources in namespace shop node-agent (on the node where db-0 runs)PodVolumeBackup · Kopia MinIO bucket veleroBSL default namespace shopDeleted / restored restorecontroller Backup: — · Restore: —
Ready. Click "Play".
$ velero backup create shop-b1 --include-namespaces shop --wait

Core commands

CommandPurposeKey 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 getBSL statusPHASE should be Available
velero backup create NAME --include-namespaces shop --waitBack up a namespace--snapshot-move-data, --ttl 72h, -l app=db
velero backup describe NAME --details / logsView results, volume backups, hooksPhase: Completed / PartiallyFailed
velero restore create --from-backup NAME --waitRestore--namespace-mappings shop:shop-restore, --include-resources
velero schedule create NAME --schedule="0 2 * * *" --include-namespaces shop --ttl 168hScheduled backupcron 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)

Important prerequisite: Velero file-system backup does not support hostPath volumes, and the default SC in kind (local-path) creates exactly hostPath PVs. So step 1 of this lab moves db to a CSI volume (hostpath-csi). This is itself a real "cross-StorageClass migration" exercise: logical export, rebuild on the new SC, then import.
Move db to hostpath-csi (pg_dump → rebuild → pg_restore):
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
Install the velero CLI and MinIO (MinIO uses the sample manifest included in the Velero repository, for the lab only):
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.

Install the Velero server:
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
Add a pre hook and back up (use the patch command from the "Commands" tab, then run it after db-0 has been rebuilt):
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.

Cause a disaster: delete the whole namespace. The PVCs and hostPath volumes are deleted along with it under the Delete policy.
kubectl delete ns shop --wait
kubectl get pv | grep shop/ || echo "all shop PVs have been deleted"
Restore and verify:
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".

Scheduled backup and cleanup:
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.

Command-line exercises
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
Scenario analysis
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

Video storyboard script

This course file cannot generate the video or MP3 directly, so a storyboard and narration script are provided instead.

Shot 1 · 0:00–0:20
Scene: A three-layer pyramid: etcd snapshots, volume snapshots, and application backups, each labeled with what it can restore.
Narration: A backup is not a single button. It is a combination of three methods.
Shot 2 · 0:20–0:55
Scene: The velero CLI creates a Backup. The server runs pg_dump in db-0, then packages the resources and uploads them to object storage.
Narration: First, the hook makes a transaction-consistent export. Then the resources and volumes are backed up.
Shot 3 · 0:55–1:25
Scene: node-agent reads data from the node's volume directory, and Kopia deduplicates and uploads it.
Narration: File-system backup is done by node-agent on each node. Remember that it does not support hostPath volumes.
Shot 4 · 1:25–2:00
Scene: kubectl delete ns shop, and everything disappears. After velero restore, the objects reappear one by one. Pods wait for restore-wait before they start. The row count of 1000 matches.
Narration: A backup only proves its value through a restore drill.
Or score ≥ 70% on the quiz

Module 8 · Storage troubleshooting

53:00 – 60:00 · A troubleshooting path through PVC → Pod events → VolumeAttachment → node → driver logs
7 minout-of-service taint GA v1.28Importance ★★★★★
Learning objectives
  • 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.
Prerequisites: Modules 1–7. Importance: ★★★★★

What: which layer a storage problem appears in

LayerTypical symptomFirst commandResponsible component
Provisioning / bindingPVC Pendingkubectl describe pvcPV controller, external-provisioner, scheduler
SchedulingPod Pending: volume node affinity conflict, exceed max volume count, RWOP conflictkubectl describe podkube-scheduler
AttachMulti-Attach error, FailedAttachVolume, AttachVolume.Attach failedkubectl get volumeattachmentAD controller, external-attacher, cloud API
MountFailedMount, timed out waiting for the condition, MountVolume.MountDevice failedPod events + kubelet logskubelet, CSI node plugin
RuntimePermission denied, No space left on device, Read-only file systemkubectl exec … df -h; ls -lnApplication, fsGroup, filesystem
Deletion / reclaimStuck in Terminating, stuck Released (can't rebind), orphaned cloud diskskubectl get pvc,pv -o yaml | grep -A3 finalizersprotection 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:

  1. 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.
  2. 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.
  3. 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-timeout can turn this off. Check the official docs for details.
  4. 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:NoExecute taint 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=0 when 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

DockerKubernetes
Mounts in docker inspectPod volumes + PVC/PV/VolumeAttachment chain
bind source path does not existFailedMount / hostPath type check failed
Accidental deletion with docker volume prunereclaimPolicy Delete + deleting the PVC
Common misconceptions① “A Pending PVC means the storage is broken.” First check whether WFFC is waiting normally. ② “For Multi-Attach, you have to force a detach in the Azure portal.” First confirm the state of the old node, then use the out-of-service taint to let the control plane finish the job. ③ “If the volume is full, just expand it.” local-path and similar drivers do not support expansion, and you need to find out what filled the volume (WAL buildup, logs). ④ “Deleting the claimRef lets any PVC bind a Released PV.” The SC, capacity and access modes must also match, and the old data is still there, so watch for data leaks.

Architecture diagram: troubleshooting object chain

PVCPending? Events? PVphase · nodeAffinity PodScheduling / mount events VolumeAttachmentattached · attachError CSINodeDriver registered? Limit Logssidecar · driver · kubelet No default SCWFFC waitingQuota / provisioning failure ReleasedLostZone mismatch FailedSchedulingFailedMountPermission denied Multi-AttachFailedAttachVolumeCloud API throttling driver not foundmax volume count gRPC error codesmkfs / mount output
Figure 8-1: Check each object from left to right. Below each object is its most common failure.

Flowchart: detach timeline for an RWO volume after a node failure

t=0 node lost ~40s NotReady ~5m eviction (Terminating) New Pod: Multi-Attach error Another ~6m: forced detach → attach to the new node Shortcut: after you confirm the shutdown, add the out-of-service taint → force-delete the Pod and detach immediately
Figure 8-2: The default path can take more than 10 minutes. A StatefulSet does not create a Pod with the same name until the old Pod is confirmed deleted.

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.

Node n1 (zone 1)Ready · Pod api-7c… RunningLUN0: pvc-3c1e… Node n2 (zone 2)Ready · idleZRS disk can attach here node lifecycle controller AD controller · VolumeAttachment Status: all good
Ready. Click “Play.”
$ kubectl get nodes -w

Troubleshooting command cheat sheet

CommandPurposeWhen to use
kubectl get events -A --field-selector reason=FailedMountCluster-wide mount failure eventsWidespread failure
kubectl get events -A --field-selector reason=FailedAttachVolumeAttach failureMulti-Attach / cloud API
kubectl get pv -o json | jq -r '.items[] | select(.status.phase=="Released") | .metadata.name'List Released PVsCost cleanup, rebinding
kubectl patch pv PV --type json -p '[{"op":"remove","path":"/spec/claimRef"}]'Clear the claimRef so the PV returns to AvailableRebind a Released PV
kubectl taint nodes N node.kubernetes.io/out-of-service=nodeshutdown:NoExecuteAfter you confirm the shutdown, force-reclaim the Pod and volumePermanent node failure
kubectl get --raw /api/v1/nodes/N/proxy/metrics | grep kubelet_volume_stats_used_bytesVolume usage metricsVolume full alert
kubectl debug node/N -it --image=busybox:1.37Enter 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)

Failure 1: no default SC:
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 nodefault
Failure 2: topology mismatch (local-path pinned to a node): Bind the PVC to one node, then cordon that node and recreate the Pod.
cat <<'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.

Failure 3: Permission denied: The container runs as non-root, uses a hostPath volume, and the ownership was never corrected.
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.

Failure 4: deletion stuck (pvc-protection):

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
Interactive troubleshooting tree: Switch to the “Troubleshooting” tab and use the decision tree to review the 4 failures above.

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.

Command-line exercise
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
Scenario analysis
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

Video storyboard script

This course material cannot generate a video or MP3 directly, so a storyboard and narration script are provided instead.

Shot 1 · 0:00–0:20
Visual: A chain: PVC → PV → Pod → VolumeAttachment → CSINode → logs. A magnifying glass moves along the chain.
Narration: To troubleshoot storage, follow the object chain and check the events one at a time.
Shot 2 · 0:20–0:50
Visual: A green check mark appears next to the PVC Pending label, reading “WaitForFirstConsumer.”
Narration: Step one: first decide whether this is normal waiting.
Shot 3 · 0:50–1:30
Visual: Node n1 is smoking. The timeline moves to five minutes, then eleven minutes. An SRE applies the out-of-service label, and the disk moves to n2 instantly.
Narration: After you confirm a node is shut down, use the out-of-service taint so the control plane can force-reclaim safely.
Shot 4 · 1:30–2:00
Visual: The PVC is Terminating. A pvc-protection lock hangs on it, with a chain linking to the Pod that is still running.
Narration: When a deletion is stuck, the protection mechanism is usually doing its job. Don't delete the finalizer casually.
Or score ≥ 70% on the quiz

Command cheat sheet

Kubernetes v1.37 storage · CSI · snapshots · StatefulSet · Velero · AKS — every code block can be copied with one click
After-class reference

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:.allowVolumeExpansion

PVC / 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 Beta

CSI 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

SymptomWhat to check firstCommon causes
PVC Pending, event WaitForFirstConsumerCheck whether a Pod uses it; check the Pod scheduling eventsNormal waiting, or the Pod failed to schedule
PVC Pending, no storage class is setkubectl get scNo default SC
ProvisioningFailedProvisioner logs, cloud quotaSKU unavailable, permissions, unsupported access mode
volume node affinity conflictPV nodeAffinity vs node labelsImmediate mode, local volume node unavailable
Multi-Attach errorVolumeAttachment, old node stateOld Pod not finished, surge update, node unreachable
exceed max volume countCSINode allocatableVM SKU data disk limit
Permission deniedid, ls -ln, fsGroupPolicyMissing fsGroup, hostPath, SMB
No space left on devicedf -h / df -iWAL / log buildup
PVC/PV Terminatingfinalizers, Pods using the PVCpvc-protection working as intended; driver failure
PV ReleasedclaimRefRetain 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: true
spec:
  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

shop db: StatefulSet + PVC + expansion + snapshot + Velero backup → delete namespace → restore → verify row count
After class ≈ 40 minutesCovers all modules
Scenario shop is about to launch. Audit requirements: database data must be recoverable after a Pod is deleted, scaled down, or the namespace is deleted by mistake. Storage must support online expansion. A snapshot must exist from before the upgrade. There must be an off-site (outside the cluster) backup, and a restore drill must have been completed. Complete this in kind (hostpath CSI route) or AKS (managed-csi route), and submit your evidence.
Choose a routekind: 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.
Deploy db (Module 6):
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"}'
Write business data (Module 6):
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
Expand online to 2Gi and sync the template (Modules 5, 6):
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.txt
Snapshot before the upgrade (Module 5):
kubectl -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.txt
Velero backup (with pg_dump pre hook) (Module 7):
velero 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.txt
Disaster: delete the namespace (Module 8 question: what happens to the snapshots?):
kubectl 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
Restore and verify (Module 7):
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
Cleanup: Keep the kind environment for hour 5, which hardens shop with RBAC and PSS. AKS: 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.
Acceptance checklist

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

Sources for the technical facts in this hour (Verified on: 2026-11-15)
TopicVerified findingSource
Kubernetes version1.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 conditionv1.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)
VolumesImage 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 VolumesReadWriteOncePod: 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)
StatefulSetpersistentVolumeClaimRetentionPolicy: 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)
VolumeGroupSnapshotGA in v1.36, groupsnapshot.storage.k8s.io/v1. Alpha in v1.27, Beta in v1.32.v1.36 VGS GA (2026-05-08)
Volume populatorsGA in v1.33. AnyVolumeDataSource is always enabled and uses dataSourceRef.v1.33 Volume Populators GA (2025-05-08)
external-snapshotterLatest v8.7.0 (10-13). v8.6.0 promoted the VolumeGroupSnapshot API to v1.GitHub releases (accessed 2026-11)
csi-driver-host-pathInstall 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-provisionerLatest v0.0.37 (08-05). The kind default SC standard uses it (WFFC, Delete, no expansion support).GitHub releases (accessed 2026-11)
AKS storage classesdefault = 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 driversIn-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 PVSC 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)
VeleroLatest 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)
CloudNativePGLatest 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.