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 fordb-1is againdb-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: Parallelrelaxes 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-2Remember
- 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.