Room 14
STATEFULSETS
The Database Dungeon
- StatefulSets provide guarantees about the ordering and uniqueness of pods - essential for databases.
- Deploy a StatefulSet and use the stable network identity to find the password.
📜 Mission Briefing
- Apply
statefulset.yaml- creates a StatefulSet with 3 ordered replicas. - Notice pods are created in order:
db-0,db-1,db-2. - Each pod has a stable hostname. Exec into
db-0and resolvedb-1.db-headless: - The headless service
db-headlessprovides DNS for each pod. - Exec into
db-2and read the file/data/password. - The password is
stateful7.
Key Commands
| Command | Purpose |
|---|---|
kubectl get sts |
List StatefulSets |
kubectl describe sts NAME |
StatefulSet details |
kubectl get pvc |
List PVCs (auto-created by STS) |
kubectl scale sts NAME --replicas=N |
Scale StatefulSet |
kubectl rollout status sts/NAME |
Check rollout |
How StatefulSets Work
apiVersion: v1
kind: Service
metadata:
name: db-headless
spec:
clusterIP: None # Headless service (no load balancing)
selector:
app: database
ports:
- port: 5432
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: db
spec:
serviceName: db-headless # Must reference headless service
replicas: 3
selector:
matchLabels:
app: database
template:
metadata:
labels:
app: database
spec:
containers:
- name: postgres
image: postgres:15
ports:
- containerPort: 5432
volumeMounts:
- name: data
mountPath: /var/lib/postgresql/data
volumeClaimTemplates: # Auto-creates PVC per pod
- metadata:
name: data
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 1Gi
# StatefulSet guarantees:
# 1. Ordered deployment: pod-0 → pod-1 → pod-2
# 2. Ordered termination: pod-2 → pod-1 → pod-0
# 3. Stable network identity: pod-0.service-name
# 4. Stable storage: each pod keeps its PVC across restarts
# DNS format: <pod-name>.<service-name>.<namespace>.svc.cluster.local
# Example: db-0.db-headless.default.svc.cluster.local
# Scale StatefulSet
kubectl scale sts db --replicas=5
# Delete pods (they get recreated with same identity)
kubectl delete pod db-1 # db-1 is recreated, not db-3
Hints
Hint 3
The password is stateful7.