Volumes
Volumes give containers storage that outlives the container’s lifecycle. The modern flow: PersistentVolumeClaim + StorageClass; the cluster dynamically provisions a backing PersistentVolume on demand.
PVCs, StatefulSet templates, ephemeral
EXAMPLE
# 1) StorageClass — defines HOW volumes are provisioned
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata: { name: gp3 }
provisioner: ebs.csi.aws.com
parameters:
type: gp3
iops: 3000
throughput: 125
reclaimPolicy: Retain # don't delete the underlying EBS volume on PVC delete
allowVolumeExpansion: true
# 2) PVC — your app's request for storage
apiVersion: v1
kind: PersistentVolumeClaim
metadata: { name: db-data, namespace: ops }
spec:
accessModes: [ReadWriteOnce]
resources:
requests: { storage: 50Gi }
storageClassName: gp3
# 3) Mount it in a Pod
spec:
containers:
- name: db
image: postgres:16
volumeMounts:
- name: data
mountPath: /var/lib/postgresql/data
volumes:
- name: data
persistentVolumeClaim: { claimName: db-data }
# 4) StatefulSet — one PVC per replica via volumeClaimTemplates
apiVersion: apps/v1
kind: StatefulSet
metadata: { name: db }
spec:
serviceName: db-headless
replicas: 3
selector: { matchLabels: { app: db } }
template:
metadata: { labels: { app: db } }
spec:
containers:
- name: db
image: postgres:16
volumeMounts:
- name: data
mountPath: /var/lib/postgresql/data
volumeClaimTemplates:
- metadata: { name: data }
spec:
accessModes: [ReadWriteOnce]
resources: { requests: { storage: 100Gi } }
storageClassName: gp3
# 5) Ephemeral volumes — gone with the Pod, no PVC needed
spec:
volumes:
- name: scratch
emptyDir: { sizeLimit: 1Gi } # cleared on Pod restart
- name: in-mem
emptyDir: { medium: Memory, sizeLimit: 64Mi }
- name: cfg
configMap: { name: app-config }
- name: dl
downwardAPI:
items:
- path: pod-name
fieldRef: { fieldPath: metadata.name }
# 6) Inspect
kubectl get sc
kubectl get pvc -n ops
kubectl get pv
kubectl describe pvc db-data -n ops
Why it matters
PVCs survive Pod restarts; PVs survive PVC deletes (with Retain). Delete reclaim is friendly for dev clusters; Retain is mandatory for anything you don’t want to accidentally lose.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Discussion
Loading…