A Deployment's Pods are interchangeable: random names, any order, nothing of their own. A database replica is not. It has a name the others know and a disk only it may write. A StatefulSet runs Pods that keep their identity.
What is stable
db-0data-db-0 · db-0.db.depths.svc.cluster.local
db-1data-db-1 · db-1.db.depths.svc.cluster.local
db-2data-db-2 · db-2.db.depths.svc.cluster.local
| Stable | How |
|---|---|
| Name | <statefulset>-<ordinal>; a replaced db-1 is again db-1 |
| DNS | <pod>.<service>.<namespace>.svc.cluster.local, through a headless Service named in spec.serviceName |
| Storage | One claim per Pod from volumeClaimTemplates, named <template>-<statefulset>-<ordinal> |
The manifest
yaml
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: postgres
image: postgres:16
volumeMounts:
- name: data
mountPath: /var/lib/postgresql/data
volumeClaimTemplates:
- metadata:
name: data
spec:
accessModes: [ReadWriteOnce]
resources:
requests:
storage: 1GiThe volumeMounts names the claim template; no volumes section is needed. The headless Service (clusterIP: None, Chapter 4) must exist with the name in serviceName. sts is the short name.
Order
text
create db-0 → Ready → db-1 → Ready → db-2
scale 3→1 delete db-2, then db-1. Claims data-db-1 and data-db-2 stay.
scale 1→3 db-1 re-attaches data-db-1, db-2 re-attaches data-db-2.