Skip to main content
Running workloadsLesson 12 of 14

StatefulSets and databases

Apps like databases, where each pod has its own identity and data, are hard to run with a Deployment. Here we follow how a StatefulSet pins down names, order and storage. How a PVC becomes real storage is covered in How Storage Gets Attached (PVC·PV).

Pods0 / 3
PVCs0
Claimed capacity0Gi
StatefulSetdb · 3 replicasServiceheadless · dbOrder appconnects to DBdb-0ordinal 0db-1ordinal 1db-2ordinal 2data-db-020Gidata-db-120Gidata-db-220Gicreate db-0
RequestResponse / reportAppears in a later step

What you will learn

  • Pod names are fixed ordinals, started one by one from 0
  • A headless Service gives each pod a stable DNS name
  • A pod that comes back reattaches to the same PVC
  • PVCs remain after scaling down or deleting

Results by action​

ActionPodsPVCsWhat to check
CreateCreated in order from db-0A data-db-N per podIf an earlier pod never becomes Ready, the next one is not created
Delete db-1Recreated with the same nameReattached to the same data-db-1The data is intact
Scale 3 → 2db-2 is deleteddata-db-2 remainsScaling back up returns that data
Delete the StatefulSetAll deletedAll remain by defaultLeftover PVCs take up space

Check the pods with kubectl get pods -l <selector> and PVCs with kubectl get pvc. Whether PVCs are deleted on scale-down or delete can be set with persistentVolumeClaimRetentionPolicy.

Try it yourself​

kubectl get statefulset -A # StatefulSets and ready counts
kubectl get pods -o wide # Ordinal names db-0, db-1, db-2
kubectl get pvc # data-db-N, still there after scale-down
kubectl get svc <service> -o jsonpath='{.spec.clusterIP}' # None means headless
kubectl get sts <name> -o jsonpath='{.spec.persistentVolumeClaimRetentionPolicy}' # What happens to PVCs
kubectl run dns-test --rm -it --image=busybox:1.36 --restart=Never -- nslookup <pod>.<service> # Fixed DNS name (removed on exit)

Check yourself

  1. The db-1 pod of a StatefulSet is deleted. What comes back?
  2. You create a StatefulSet with 3 replicas, but only db-0 exists and db-1 is never created. What is most likely?
  3. After scaling a StatefulSet from 3 to 2 and later deleting it, storage use stays high. Why?

Further reading: StatefulSets · Persistent volumes · Finding Services by Name (Service·DNS)