# Persistent Volumes and StatefulSets — Kubernetes

Source: https://www.skillbyai.com/en/kubernetes/p-storage

> Data that outlives pods.

## PVCs, StorageClasses, stable identities

Container filesystems vanish with the pod. A **PersistentVolumeClaim (PVC)** requests durable storage of a size and access mode; a **StorageClass** provisions the actual **PersistentVolume** (a cloud disk, for example) dynamically. A **StatefulSet** gives each replica a stable name (`db-0`, `db-1`), its own PVC via `volumeClaimTemplates`, and ordered startup, which databases and queues need. Running databases on Kubernetes is possible but demanding; many teams use managed databases instead.

## State and environments

Persistent volumes and StatefulSets handle state; Kustomize and Helm manage manifests per environment.

![Three ideas: storage, Kustomize, Helm.](assets/figures/kubernetes/section-7-map.svg) — Figure 7.1 — Storage, Kustomize and Helm.

## A StatefulSet with per-replica storage

Not applied to a live cluster in this course; check field names against the API reference for your version.

```yaml
apiVersion: apps/v1
kind: StatefulSet
metadata: {name: db}
spec:
  serviceName: db            # headless Service for stable DNS (db-0.db)
  replicas: 3
  selector: {matchLabels: {app: db}}
  template:
    metadata: {labels: {app: db}}
    spec:
      containers:
      - name: postgres
        image: postgres:17
        volumeMounts: [{name: data, mountPath: /var/lib/postgresql/data}]
  volumeClaimTemplates:
  - metadata: {name: data}
    spec:
      accessModes: [ReadWriteOnce]
      storageClassName: standard
      resources: {requests: {storage: 20Gi}}
```

## Test restores, not just backups

Volume snapshots are only useful if you have practised restoring them.

**Quiz:** What does a StatefulSet provide that a Deployment does not?

- [ ] Faster image pulls
- [x] Stable pod identities and a dedicated volume per replica
- [ ] Automatic autoscaling
- [ ] Public IP addresses

*Answer:* Stable pod identities and a dedicated volume per replica. Identity and storage per replica.
