Skip to main content

Configuring Kubernetes Persistent Volumes

Configure PersistentVolumes, PersistentVolumeClaims, and StorageClasses in Kubernetes to provide durable storage for stateful workloads in production.

52 Terms

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.

flowchart TD SC[StorageClass
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
Bash
kubectl get storageclass
kubectl describe storageclass gp2

Look 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:

YAML
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
name: gp3-encrypted
provisioner: ebs.csi.aws.com
parameters:
type: gp3
iops: "6000"
throughput: "250"
encrypted: "true"
kmsKeyId: "arn:aws:kms:ap-south-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab"
reclaimPolicy: Retain
allowVolumeExpansion: true
volumeBindingMode: WaitForFirstConsumer

Create a shared file class for workloads that need many writers, using EFS:

YAML
# efs-shared.yaml
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
name: efs-shared
provisioner: efs.csi.aws.com
parameters:
provisioningMode: efs-ap
fileSystemId: fs-0a1b2c3d4e5f6789
directoryPerms: "700"
reclaimPolicy: Retain
volumeBindingMode: Immediate
Bash
kubectl apply -f gp3-encrypted.yaml -f efs-shared.yaml

The 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:

YAML
# redis-data-pvc.yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: redis-data-pvc
namespace: storage-lab
labels:
app: redis
team: platform
spec:
accessModes:
- ReadWriteOnce
storageClassName: gp3-encrypted
resources:
requests:
storage: 20Gi

A shared media volume uses ReadWriteMany on EFS. EFS is elastic, so the requested size is required by the API but not enforced:

YAML
# video-assets-pvc.yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: video-assets-pvc
namespace: storage-lab
spec:
accessModes:
- ReadWriteMany
storageClassName: efs-shared
resources:
requests:
storage: 5Ti
Bash
kubectl create namespace storage-lab
kubectl apply -f redis-data-pvc.yaml -f video-assets-pvc.yaml
kubectl get pvc -n storage-lab

The 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:

Bash
read -s -p "Postgres password: " PGPASS
kubectl create secret generic postgres-credentials \
--from-literal=password="$PGPASS" -n storage-lab
YAML
# postgres-statefulset.yaml
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: postgres
namespace: storage-lab
spec:
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: 100Gi
Bash
kubectl apply -f postgres-statefulset.yaml
kubectl 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/data
Security

Set securityContext.fsGroup to 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:

Bash
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-lab
kubectl 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 there
Step 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:

Bash
kubectl get storageclass gp3-encrypted -o jsonpath='{.allowVolumeExpansion}'
YAML
# resize.yaml
spec:
resources:
requests:
storage: 200Gi
Bash
kubectl patch pvc data-postgres-0 -n storage-lab --patch-file resize.yaml
kubectl get pvc data-postgres-0 -n storage-lab -w

You 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
Bash
kubectl get pvc -n storage-lab
kubectl describe pvc PVC-NAME -n storage-lab
kubectl get events -n storage-lab --field-selector reason=ProvisioningFailed

Read 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:

Bash
kubectl get pods -n kube-system | grep ebs-csi
kubectl logs -n kube-system -l app=ebs-csi-controller -c csi-provisioner --tail=50
Step 8 - Snapshot and Restore

Snapshots need the snapshot CRDs and controller installed, and a VolumeSnapshotClass for your driver:

YAML
# volumesnapshotclass.yaml
apiVersion: snapshot.storage.k8s.io/v1
kind: VolumeSnapshotClass
metadata:
name: csi-aws-vsc
driver: ebs.csi.aws.com
deletionPolicy: Retain
YAML
# volume-snapshot.yaml
apiVersion: snapshot.storage.k8s.io/v1
kind: VolumeSnapshot
metadata:
name: postgres-snapshot-20261014
namespace: storage-lab
spec:
volumeSnapshotClassName: csi-aws-vsc
source:
persistentVolumeClaimName: data-postgres-0
Bash
kubectl apply -f volumesnapshotclass.yaml -f volume-snapshot.yaml
kubectl get volumesnapshot -n storage-lab
# READYTOUSE should become true

Restore into a new claim by pointing dataSource at the snapshot:

YAML
# postgres-data-restored.yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: postgres-data-restored
namespace: storage-lab
spec:
accessModes:
- ReadWriteOnce
storageClassName: gp3-encrypted
resources:
requests:
storage: 100Gi
dataSource:
name: postgres-snapshot-20261014
kind: VolumeSnapshot
apiGroup: snapshot.storage.k8s.io
Bash
kubectl apply -f postgres-data-restored.yaml
Remember

Volume snapshots are crash-consistent, not application-consistent. For PostgreSQL, also take logical or base backups with pg_dump or pg_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:

Bash
kubectl delete statefulset postgres -n storage-lab
kubectl delete pvc --all -n storage-lab
kubectl get pv
# Retained volumes show Released: delete each PV, then the cloud disk in the console or CLI
kubectl delete pv PV-NAME
kubectl delete namespace storage-lab

Production Best Practices & Common Pitfalls

Common Mistake

Using reclaimPolicy: Delete for production database storage. One accidental kubectl delete pvc then destroys the cloud disk and its data within seconds. Use Retain for anything holding production data, and restrict who can delete claims.

Tip

Volume expansion only goes one way, so start with a sensible size and set allowVolumeExpansion: true on 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 PGDATA to a subdirectory avoids the lost+found directory 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_bytes and kubelet_volume_stats_capacity_bytes metrics.
  • 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 persistentVolumeClaimRetentionPolicy field 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

Resources

Velero vs etcd Snapshot: Which Do You Need?

Velero vs etcd Snapshot: Which Do You Need?

Velero and etcd snapshots protect different layers of a Kubernetes cluster. See what each backs up, what each misses, and why most DR needs both.

11 min read•Aug 2026
Istio Ambient vs Linkerd in 2026: Which Mesh?

Istio Ambient vs Linkerd in 2026: Which Mesh?

Istio Ambient cuts the sidecar tax at L4, but L7 adds waypoint hops, and Linkerd stable builds now come from Buoyant. Choose with tests.

11 min read•Aug 2026
Nginx Ingress vs Traefik vs Gateway API in 2026

Nginx Ingress vs Traefik vs Gateway API in 2026

Ingress-NGINX is retired. Compare Traefik and Gateway API controllers as replacements, plus a safe migration plan that avoids outages.

10 min read•Aug 2026
OPA Gatekeeper vs Kyverno: Policy Engine in 2026

OPA Gatekeeper vs Kyverno: Policy Engine in 2026

OPA Gatekeeper vs Kyverno compared for 2026: Rego vs YAML, mutation, reporting, and operations, plus how to pick a Kubernetes policy engine.

10 min read•Aug 2026
Helm vs Kustomize in 2026: Templating vs Patching

Helm vs Kustomize in 2026: Templating vs Patching

Helm vs Kustomize compared for 2026 - templating vs patching, Helm 4's new features, and why most production teams end up running both.

5 min read•Aug 2026
Prometheus vs Datadog vs New Relic: Real Costs

Prometheus vs Datadog vs New Relic: Real Costs

Prometheus, Datadog, and New Relic compared for 2026 - real pricing at scale, hidden cost drivers, and which fits a Kubernetes-heavy stack.

5 min read•Aug 2026
Cluster Autoscaler vs Karpenter for EKS in 2026

Cluster Autoscaler vs Karpenter for EKS in 2026

Cluster Autoscaler vs Karpenter on EKS: scale-up speed, bin-packing, Spot handling, Auto Mode limits and a safe migration path, with v1 NodePool YAML.

11 min read•Aug 2026
GKE vs EKS vs AKS in 2026: Which Fits Your Team?

GKE vs EKS vs AKS in 2026: Which Fits Your Team?

GKE, EKS, and AKS compared for 2026 - control plane pricing, Autopilot vs Karpenter vs Node Auto Provisioning, and which platform actually fits your team.

5 min read•Aug 2026
K3s vs K8s vs MicroK8s: Which Distro in 2026?

K3s vs K8s vs MicroK8s: Which Distro in 2026?

Compare K3s, upstream Kubernetes and MicroK8s on footprint, datastores, HA and updates, and pick the right fit for edge, dev or production.

10 min read•Aug 2026
Canary Deployments with Argo Rollouts & Flagger

Canary Deployments with Argo Rollouts & Flagger

Ship to 5% of users first and auto-rollback on bad metrics: canary deployments on Kubernetes with Argo Rollouts, Flagger, and Gateway API.

11 min read•Jun 2026
OpenTelemetry Explained: Metrics, Logs, Traces

OpenTelemetry Explained: Metrics, Logs, Traces

OpenTelemetry in practice: instrument a Node.js service, run a production Collector, sample traces and link metrics, logs and traces in Grafana.

11 min read•Jun 2026
Kubernetes Cost Optimization Without SLO Risk

Kubernetes Cost Optimization Without SLO Risk

Kubernetes clusters average about 8% CPU use. Cut waste safely with request rightsizing, autoscaling, spot, and OpenCost, keeping SLOs.

11 min read•Jun 2026
ArgoCD vs FluxCD: GitOps for Kubernetes in 2026

ArgoCD vs FluxCD: GitOps for Kubernetes in 2026

ArgoCD vs FluxCD compared for 2026: UI, multi-tenancy, Helm, image automation and pruning risks, with a clear guide to picking your GitOps engine.

10 min read•Jun 2026

Explore More in Kubernetes Workload Management

All 6 Topics

Frequently Asked Questions

Is Configuring Kubernetes Persistent Volumes free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Configuring Kubernetes Persistent Volumes topic cover?

Configure PersistentVolumes, PersistentVolumeClaims, and StorageClasses in Kubernetes to provide durable storage for stateful workloads in production.

Found a mistake, an outdated step or a broken link?