Skip to content

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

  1. Apply statefulset.yaml - creates a StatefulSet with 3 ordered replicas.
  2. Notice pods are created in order: db-0, db-1, db-2.
  3. Each pod has a stable hostname. Exec into db-0 and resolve db-1.db-headless:
    kubectl exec db-0 -- nslookup db-1.db-headless
    
  4. The headless service db-headless provides DNS for each pod.
  5. Exec into db-2 and read the file /data/password.
  6. 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 1

Watch pods come up in order:

kubectl get pods --watch -l app=database

Hint 2

Exec into the last pod:

kubectl exec -it db-2 -- cat /data/password

Hint 3

The password is stateful7.


🔓 Unlock Room 15

openssl enc -aes-256-cbc -d -a -pbkdf2 \
        -in ../room_15/README             \
        -out ../room_15/README.txt        \
        -pass pass:PASSWORD
cat ../room_15/README.txt