Skip to content
BytePatterns

Storage: PV, PVC & StatefulSet

Docker & Kubernetes for Interviews: lesson 11 of 12

Replicas with names that stick and disks that follow them.

Lesson 11 of 12 · 7 min

Storage: PV, PVC & StatefulSet

Step 1 of 11

A database's replicas are not interchangeable: each needs its own name and its own data.

The Idea

A PersistentVolume is storage whose life does not depend on any Pod. A Pod asks for storage with a PersistentVolumeClaim — a size and an access mode — and a StorageClass can provision a matching volume on demand. A StatefulSet gives each replica a stable name (db-0, db-1) and its own claim from a volumeClaimTemplate.

Real-World Example

A three-replica database StatefulSet creates db-0, db-1 and db-2 in order, each bound to its own volume. When db-1's node fails, the replacement comes back as db-1 and mounts the same claim.

The Tradeoff

ReadWriteOnce means a single node mounts the volume read-write, so replicas do not share a disk — each gets its own. Scaling down keeps the claims by default, so cleanup is yours; and with reclaimPolicy: Delete, the default for dynamically provisioned volumes, deleting a claim deletes the data.

Hands-On

# illustrative — one claim per replica; serviceName is a headless Service
apiVersion: apps/v1
kind: StatefulSet
metadata: { name: db }
spec:
  serviceName: db
  replicas: 3
  selector: { matchLabels: { app: db } }
  template:
    metadata: { labels: { app: db } }
    spec:
      containers:
        - name: db
          image: registry.example.com/db:1.0
          volumeMounts: [{ name: data, mountPath: /data }]
  volumeClaimTemplates:
    - metadata: { name: data }
      spec: { accessModes: [ReadWriteOnce], resources: { requests: { storage: 10Gi } } }

Your turn

Put the steps in the right order.

  1. A StorageClass provisions a volume and binds it to the claim
  2. db-1's node fails; the new db-1 mounts data-db-1 again
  3. The StatefulSet creates db-0 and its claim data-db-0
  4. db-0 is Running and Ready, so db-1 is created next

Mini quiz

1 / 3

A PersistentVolumeClaim is:

Sources

New lessons land every few weeks

Leave an address and we will tell you when the next one is up. That is the only reason we will use it.

One address, stored so we can email you. Nothing else, ever.