Configuration and StorageLesson 4.4
Kubernetes StatefulSets: deploying databases and stateful applications
StatefulSet vs Deployment, stable network identity, ordered pod startup, volumeClaimTemplates, persistent pod names, StatefulSet update strategy, headless service requirement
StatefulSets Provide Identity to Pods
Deployments treat Pods as interchangeable. StatefulSets give each Pod a stable identity: a persistent name (pod-0, pod-1), a stable DNS hostname, and its own dedicated PersistentVolume. Pods start and stop in order. This is essential for databases and clustered applications.
StatefulSet Manifest
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: postgres
spec:
serviceName: postgres-svc # must match a headless service
replicas: 3
selector:
matchLabels:
app: postgres
template:
metadata:
labels:
app: postgres
spec:
containers:
- name: postgres
image: postgres:15
env:
- name: POSTGRES_PASSWORD
valueFrom:
secretKeyRef:
name: pg-secret
key: password
volumeMounts:
- name: pgdata
mountPath: /var/lib/postgresql/data
volumeClaimTemplates: # each pod gets its own PVC
- metadata:
name: pgdata
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 20GiEach Pod gets a PVC named pgdata-postgres-0, pgdata-postgres-1 etc. These PVCs persist even if the StatefulSet is deleted โ you must delete them manually to free storage.
