StatefulSets

Kubernetes · Practical · 10 min

Databases, queues and clustered systems need identity and storage that survive rescheduling.

A StatefulSet is like a Deployment, but each replica has an identity:

  • Stable names: db-0, db-1, db-2. A replacement for db-1 is again db-1.
  • Stable DNS through a headless Service named in serviceName: db-0.db.<ns>.svc.cluster.local.
  • Stable storage through volumeClaimTemplates: each replica gets its own PVC (data-db-0, data-db-1) that follows it when it is rescheduled.
  • Ordering: by default pods are created one at a time in order (0, 1, 2) and removed in reverse; podManagementPolicy: Parallel relaxes this.

Updates roll from the highest ordinal down. updateStrategy.rollingUpdate.partition: N updates only pods with ordinal at or above N, a simple way to canary one replica.

Scaling down does not delete the PVCs by default, so data survives a mistaken scale-down; persistentVolumeClaimRetentionPolicy can change that.

A StatefulSet gives identity, not clustering: the application still has to handle replication, leader election and failover. Running production databases on Kubernetes is very doable, usually through an operator (CloudNativePG, Strimzi for Kafka) that knows the database's procedures, or simply by using a managed database.

Example

apiVersion: apps/v1
kind: StatefulSet
metadata: {name: db}
spec:
  serviceName: db            # headless Service (clusterIP: None) named db
  replicas: 3
  selector: {matchLabels: {app: db}}
  template:
    metadata: {labels: {app: db}}
    spec:
      containers:
        - name: postgres
          image: postgres:17
          env: [{name: POSTGRES_PASSWORD, valueFrom: {secretKeyRef: {name: db, key: password}}}]
          volumeMounts: [{name: data, mountPath: /var/lib/postgresql/data}]
  volumeClaimTemplates:
    - metadata: {name: data}
      spec:
        accessModes: [ReadWriteOnce]
        resources: {requests: {storage: 20Gi}}
# pods: db-0, db-1, db-2   PVCs: data-db-0, data-db-1, data-db-2

Remember

  • Stable ordinal names, DNS and per-replica PVCs
  • Needs a headless Service named in serviceName
  • PVCs survive scale-down; replication logic is still the app's job

Watch out for

  • Expecting three StatefulSet replicas of Postgres to replicate data automatically.

Check yourself

  1. Pod db-1 of a StatefulSet is deleted. What does its replacement get?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: kubernetes.io/docs/concepts/workloads/controllers/statefulset/

Builds on

Unlocks

Nothing builds on this yet.