Overview and What You Will Learn
Kubernetes separates storage into three objects: a StorageClass that says how to provision storage, a PersistentVolumeClaim (PVC) that requests it, and a PersistentVolume (PV) that is the real disk. Containers lose their filesystem when a pod restarts, so databases and queues must write to a PVC instead. In this lab you will create StorageClasses, claim storage for a PostgreSQL StatefulSet, prove the data survives a pod deletion, expand the volume, troubleshoot a stuck claim and take a snapshot. The manifests target AWS EKS with the EBS CSI driver. On another cloud, change the provisioner and parameters.
- Understanding how StorageClass, PVC and PV relate
- Creating StorageClasses for block and shared file storage
- Choosing access modes and reclaim policies
- Giving each StatefulSet replica its own volume with
volumeClaimTemplates - Expanding a volume and troubleshooting a PVC stuck in Pending
- Taking and restoring a volume snapshot
Why This Matters in Production
Without a persistent volume, a restarted database pod comes back empty. Imagine a brokerage team at a company like Zerodha running PostgreSQL on Kubernetes for trade records. A node failure that reschedules the pod would lose everything since the last external backup, which is both a regulatory problem and a loss of customer trust. A correctly configured PVC lets the pod restart or move nodes and reattach to the same data, and the right reclaim policy keeps an accidental kubectl delete from destroying the disk.
Core Principles
A StorageClass tells Kubernetes which provisioner and parameters to use. When a PVC requests storage from that class, the provisioner creates a PV automatically, which is dynamic provisioning, and the claim binds to it. A pod then mounts the PVC by name.
how to provision]:::slate -->|dynamic provisioning| PV[(PersistentVolume
the real disk)]:::tool PVC[PersistentVolumeClaim
what you request]:::soft -->|binds to| PV POD([Pod mounts the PVC]):::ok --> PVC classDef slate fill:#475569,color:#FFFFFF classDef tool fill:#326CE5,color:#FFFFFF classDef soft fill:#DBEAFE,color:#1E293B classDef ok fill:#10B981,color:#FFFFFF
Access modes decide how many nodes or pods can mount a volume, and they are the most misunderstood setting:
| Mode | Meaning | Typical backends |
|---|---|---|
| ReadWriteOnce (RWO) | Read-write by one node, though several pods on that node can share it | EBS, GCP Persistent Disk, Azure Disk |
| ReadWriteOncePod (RWOP) | Read-write by exactly one pod | CSI drivers that support it |
| ReadWriteMany (RWX) | Read-write by many nodes at once | EFS, Filestore, Azure Files, NFS |
| ReadOnlyMany (ROX) | Read-only by many nodes | Shared config and static assets |
The reclaim policy decides what happens to the disk when the PVC is deleted. Delete removes the cloud disk and its data, and Retain keeps the disk and moves the PV to a Released state for manual recovery. Dynamic classes default to Delete, so set Retain on anything holding production data.
Detailed Step-by-Step Practical Lab
Step 1 - Inspect the Available StorageClasses
kubectl get storageclasskubectl describe storageclass gp2Look at the RECLAIMPOLICY and VOLUMEBINDINGMODE columns. With WaitForFirstConsumer, the volume is created only when a pod is scheduled, so it lands in the same availability zone as the pod.
Step 2 - Create Production StorageClasses
Create a fast, encrypted block class for databases. The KMS key ARN below is a placeholder, so use your own:
apiVersion: storage.k8s.io/v1kind: StorageClassmetadata: name: gp3-encryptedprovisioner: ebs.csi.aws.comparameters: type: gp3 iops: "6000" throughput: "250" encrypted: "true" kmsKeyId: "arn:aws:kms:ap-south-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab"reclaimPolicy: RetainallowVolumeExpansion: truevolumeBindingMode: WaitForFirstConsumerCreate a shared file class for workloads that need many writers, using EFS:
# efs-shared.yamlapiVersion: storage.k8s.io/v1kind: StorageClassmetadata: name: efs-sharedprovisioner: efs.csi.aws.comparameters: provisioningMode: efs-ap fileSystemId: fs-0a1b2c3d4e5f6789 directoryPerms: "700"reclaimPolicy: RetainvolumeBindingMode: Immediatekubectl apply -f gp3-encrypted.yaml -f efs-shared.yamlThe fsGroup setting you will use in the next step controls ownership on block volumes, and EFS access points manage their own ownership.
Step 3 - Claim Storage
A standalone PVC suits a single Deployment, such as a small Redis cache:
# redis-data-pvc.yamlapiVersion: v1kind: PersistentVolumeClaimmetadata: name: redis-data-pvc namespace: storage-lab labels: app: redis team: platformspec: accessModes: - ReadWriteOnce storageClassName: gp3-encrypted resources: requests: storage: 20GiA shared media volume uses ReadWriteMany on EFS. EFS is elastic, so the requested size is required by the API but not enforced:
# video-assets-pvc.yamlapiVersion: v1kind: PersistentVolumeClaimmetadata: name: video-assets-pvc namespace: storage-labspec: accessModes: - ReadWriteMany storageClassName: efs-shared resources: requests: storage: 5Tikubectl create namespace storage-labkubectl apply -f redis-data-pvc.yaml -f video-assets-pvc.yamlkubectl get pvc -n storage-labThe Redis claim stays Pending until a pod uses it, because its class waits for the first consumer, and that is normal.
Step 4 - Run PostgreSQL with Its Own Volume
For StatefulSets, use volumeClaimTemplates so every replica gets its own PVC, instead of pointing replicas at one shared claim. First create the credentials secret without putting the password in your shell history:
read -s -p "Postgres password: " PGPASSkubectl create secret generic postgres-credentials \ --from-literal=password="$PGPASS" -n storage-lab# postgres-statefulset.yamlapiVersion: apps/v1kind: StatefulSetmetadata: name: postgres namespace: storage-labspec: serviceName: postgres replicas: 1 selector: matchLabels: app: postgres template: metadata: labels: app: postgres spec: securityContext: fsGroup: 999 fsGroupChangePolicy: OnRootMismatch containers: - name: postgres image: postgres:16 env: - name: POSTGRES_DB value: trading - name: POSTGRES_USER value: rahul - name: POSTGRES_PASSWORD valueFrom: secretKeyRef: name: postgres-credentials key: password - name: PGDATA value: /var/lib/postgresql/data/pgdata ports: - containerPort: 5432 resources: requests: cpu: 500m memory: 1Gi limits: memory: 4Gi volumeMounts: - name: data mountPath: /var/lib/postgresql/data volumeClaimTemplates: - metadata: name: data spec: accessModes: - ReadWriteOnce storageClassName: gp3-encrypted resources: requests: storage: 100Gikubectl apply -f postgres-statefulset.yamlkubectl get pvc -n storage-lab# A new claim named data-postgres-0 should be Bound kubectl exec -n storage-lab postgres-0 -- df -h /var/lib/postgresql/dataSecuritySet
securityContext.fsGroupto the group your database runs as. Without it, the mounted volume may be owned by root and the process cannot write to it, which looks like a storage failure but is a permissions problem.
Step 5 - Prove the Data Survives
Write a row, delete the pod, and read the row back from the replacement pod:
kubectl exec -n storage-lab postgres-0 -- psql -U rahul -d trading \ -c "CREATE TABLE orders (id int, note text); INSERT INTO orders VALUES (1, 'ORD-48214');" kubectl delete pod postgres-0 -n storage-labkubectl wait --for=condition=Ready pod/postgres-0 -n storage-lab --timeout=180s kubectl exec -n storage-lab postgres-0 -- psql -U rahul -d trading \ -c "SELECT * FROM orders;"# Expected: the row is still thereStep 6 - Expand the Volume
Check that the class allows expansion, then patch the claim from a YAML file. Make the change to the PVC itself, because the size in a StatefulSet's volumeClaimTemplates cannot be edited:
kubectl get storageclass gp3-encrypted -o jsonpath='{.allowVolumeExpansion}'# resize.yamlspec: resources: requests: storage: 200Gikubectl patch pvc data-postgres-0 -n storage-lab --patch-file resize.yamlkubectl get pvc data-postgres-0 -n storage-lab -wYou can only grow a volume, never shrink it. The EBS CSI driver expands online, so the pod normally does not need a restart, but a condition such as FileSystemResizePending tells you when the filesystem resize is still waiting. Cloud providers also limit how often a volume can be modified, and EBS allows one modification per volume about every six hours, so plan sizes with headroom.
Step 7 - Troubleshoot a PVC Stuck in Pending
kubectl get pvc -n storage-labkubectl describe pvc PVC-NAME -n storage-labkubectl get events -n storage-lab --field-selector reason=ProvisioningFailedRead the events at the bottom of describe and match them to a cause:
| Event or message | Meaning | Fix |
|---|---|---|
storageclass ... not found |
Wrong or missing class name | Correct storageClassName |
waiting for first consumer |
The class uses WaitForFirstConsumer |
Normal, create a pod that uses the claim |
| Provider parameter errors, such as an unsupported IOPS value | Parameters do not fit the volume type | Fix the StorageClass parameters |
volume node affinity conflict on the pod |
A zonal disk sits in a different zone than the node chosen for the pod | Schedule the pod in the disk's zone |
Also confirm that the CSI driver is healthy and read the provisioner's logs:
kubectl get pods -n kube-system | grep ebs-csikubectl logs -n kube-system -l app=ebs-csi-controller -c csi-provisioner --tail=50Step 8 - Snapshot and Restore
Snapshots need the snapshot CRDs and controller installed, and a VolumeSnapshotClass for your driver:
# volumesnapshotclass.yamlapiVersion: snapshot.storage.k8s.io/v1kind: VolumeSnapshotClassmetadata: name: csi-aws-vscdriver: ebs.csi.aws.comdeletionPolicy: Retain# volume-snapshot.yamlapiVersion: snapshot.storage.k8s.io/v1kind: VolumeSnapshotmetadata: name: postgres-snapshot-20261014 namespace: storage-labspec: volumeSnapshotClassName: csi-aws-vsc source: persistentVolumeClaimName: data-postgres-0kubectl apply -f volumesnapshotclass.yaml -f volume-snapshot.yamlkubectl get volumesnapshot -n storage-lab# READYTOUSE should become trueRestore into a new claim by pointing dataSource at the snapshot:
# postgres-data-restored.yamlapiVersion: v1kind: PersistentVolumeClaimmetadata: name: postgres-data-restored namespace: storage-labspec: accessModes: - ReadWriteOnce storageClassName: gp3-encrypted resources: requests: storage: 100Gi dataSource: name: postgres-snapshot-20261014 kind: VolumeSnapshot apiGroup: snapshot.storage.k8s.iokubectl apply -f postgres-data-restored.yamlRememberVolume snapshots are crash-consistent, not application-consistent. For PostgreSQL, also take logical or base backups with
pg_dumporpg_basebackup, and test a restore, because a snapshot is a fast recovery aid, not your only backup.
Step 9 - Clean Up
Because the class uses Retain, deleting the claims leaves the PVs and the cloud disks behind. Delete them deliberately to stop billing:
kubectl delete statefulset postgres -n storage-labkubectl delete pvc --all -n storage-labkubectl get pv# Retained volumes show Released: delete each PV, then the cloud disk in the console or CLIkubectl delete pv PV-NAMEkubectl delete namespace storage-labProduction Best Practices & Common Pitfalls
Common MistakeUsing
reclaimPolicy: Deletefor production database storage. One accidentalkubectl delete pvcthen destroys the cloud disk and its data within seconds. UseRetainfor anything holding production data, and restrict who can delete claims.
TipVolume expansion only goes one way, so start with a sensible size and set
allowVolumeExpansion: trueon the class. Growing a claim is easy, but shrinking one means a new volume and a data migration.
- Mount PostgreSQL data in a subdirectory. Setting
PGDATAto a subdirectory avoids thelost+founddirectory at the root of a fresh ext4 volume, which PostgreSQL refuses to initialize over. - Share an RWO claim with care. Several pods on the same node can mount one RWO volume, but a pod on another node cannot, and it stays in
ContainerCreating. Use RWX or one claim per replica instead. - Label claims by team and application. At scale, you cannot tell which claim belongs to which service without consistent labels.
- Alert on volume usage. Kubernetes does not grow volumes by itself, so alert at 80 percent using the
kubelet_volume_stats_used_bytesandkubelet_volume_stats_capacity_bytesmetrics. - Schedule snapshots. Use Velero or your provider's snapshot scheduler, since a 100 GiB database volume with no snapshots is a single point of failure.
- Know what deleting a StatefulSet does to claims. By default the PVCs are kept, and the
persistentVolumeClaimRetentionPolicyfield can change that, so check it before scaling down or deleting.
Quick Reference & Troubleshooting Commands
| Command | Description |
|---|---|
kubectl get pvc -n NS |
List claims and their binding status |
kubectl describe pvc NAME -n NS |
Show provisioning events for a claim |
kubectl get pv |
List PersistentVolumes cluster-wide |
kubectl get storageclass |
List available StorageClasses |
kubectl patch pvc NAME -n NS --patch-file resize.yaml |
Expand a claim from a YAML patch |
kubectl exec POD -n NS -- df -h |
Check disk usage inside a pod |
kubectl get volumesnapshot -n NS |
List volume snapshots |
kubectl get events -n NS --field-selector reason=ProvisioningFailed |
Find storage provisioning failures |