CodeBlanks Logo Icon CodeBlanks

VolumeClaimTemplate

Learn persistent storage with volumeClaimTemplates.

VolumeClaimTemplate

volumeClaimTemplates is a template for a separate PersistentVolumeClaim (PVC) for each pod. A 3-replica StatefulSet creates the PVCs data-db-0, data-db-1, data-db-2. Even if a pod is deleted, the PVC remains and the new pod attaches to the same PVC:

spec:
  template:
    spec:
      containers:
        - name: postgres
          image: postgres:16
          volumeMounts:
            - name: data
              mountPath: /var/lib/postgresql/data
  volumeClaimTemplates:
    - metadata:
        name: data
      spec:
        accessModes: ["ReadWriteOnce"]
        resources:
          requests:
            storage: 10Gi

Seeing the PVCs

PVC names have the form template-name-pod-name. Each is bound to a PersistentVolume (Bound):

$ kubectl get pvc -l app=db
NAME        STATUS   VOLUME          CAPACITY   ACCESS MODES   STORAGECLASS
data-db-0   Bound    pvc-3f2a…       10Gi       RWO            standard
data-db-1   Bound    pvc-8d1e…       10Gi       RWO            standard
data-db-2   Bound    pvc-c4b7…       10Gi       RWO            standard

When scaled down (3 → 2), data-db-2 isn't deleted; when scaled up again, db-2 returns with the same data.

Practice Add persistent storage

Write a StatefulSet's volumeClaimTemplates section (starting with volumeClaimTemplates:): template name data; accessModes: ["ReadWriteOnce"]; resources.requests.storage: 10Gi.

Starter code

terminal
# buraya yaz

Sample solution

terminal
volumeClaimTemplates:
  - metadata:
      name: data
    spec:
      accessModes: ["ReadWriteOnce"]
      resources:
        requests:
          storage: 10Gi

Expected output

statefulset.apps/db created
$ kubectl get pvc
NAME        STATUS   CAPACITY   ACCESS MODES
data-db-0   Bound    10Gi       RWO

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 By default, what happens to the PVCs when the StatefulSet is deleted?

  • They are deleted immediately
  • They move to another StatefulSet
  • They are emptied
  • They stay; they must be deleted by hand, to protect the data Correct answer

Explanation: persistentVolumeClaimRetentionPolicy can change this behaviour.

2 Define the PVC template for each pod.

Question
spec:
  ____:
    - metadata:
        name: data
Answer
spec:
  volumeClaimTemplates:
    - metadata:
        name: data

Explanation: volumeClaimTemplates is specific to StatefulSets.

3 Match.

Term Meaning
volumeClaimTemplates PVC per pod
data-db-0 PVC name
ReadWriteOnce Single node writes
Bound Bound to a PV

All lessons in Advanced