This playbook provides a step-by-step guide to deploying, managing, and recovering stateful workloads in Kubernetes using StatefulSets. It covers Persistent Volumes (PVs) and Persistent Volume Claims (PVCs) for storage, Pod Disruption Budgets (PDBs) for availability during disruptions, and rollouts/rollbacks for safe updates.
Why StatefulSets? They provide stable network identities (e.g., pod-0.my-svc), ordered scaling/deployment, and built-in PVC management via volumeClaimTemplates.
Sample App: We'll use a simple Nginx-based stateful app that writes pod identity to its PVC-mounted volume for demonstration (verifiable via kubectl exec).
Prerequisites:
Kubernetes cluster (e.g., kind/minikube for testing).
kubectl configured.
Create a namespace: kubectl create ns stateful-demo.
Switch to it: kubectl config set-context --current --namespace=stateful-demo.
StorageClass available (use standard or default; for local testing, use local-path or hostPath).
Step 1: Persistent Volumes and Claims (Storage Setup)
StatefulSets use volumeClaimTemplates to auto-provision PVCs per pod replica (e.g., data-myapp-0, data-myapp-1).
1.1 Create a StorageClass (if needed)
yaml
# storageclass.yaml (optional; skip if default exists)
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
name: stateful-sc
provisioner: kubernetes.io/no-provisioner # Use hostPath for demo; replace with CSI (e.g., ebs.csi.aws.com)
volumeBindingMode: WaitForFirstConsumer
Apply: kubectl apply -f storageclass.yaml
1.2 Deploy StatefulSet with PVCs
yaml
# statefulset-initial.yaml
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: myapp
spec:
serviceName: myapp-svc # Headless service for stable DNS
replicas: 3
selector:
matchLabels:
app: myapp
template:
metadata:
labels:
app: myapp
spec:
containers:
- name: nginx
image: nginx:1.21
ports:
- containerPort: 80
name: web
volumeMounts:
- name: data
mountPath: /usr/share/nginx/html # Persistent data dir
lifecycle:
postStart:
exec:
command: ["/bin/sh", "-c", "echo 'Hello from $(hostname)' > /usr/share/nginx/html/index.html"]
volumeClaimTemplates:
- metadata:
name: data
spec:
accessModes: ["ReadWriteOnce"]
storageClassName: stateful-sc # Or your default
resources:
requests:
storage: 1Gi
---
apiVersion: v1
kind: Service
metadata:
name: myapp-svc
spec:
clusterIP: None # Headless for StatefulSet DNS
selector:
app: myapp
ports:
- port: 80
targetPort: 80
Apply: kubectl apply -f statefulset-initial.yaml
Verify:
Pods: kubectl get sts myapp (shows 3/3 ready).
PVCs: kubectl get pvc (shows data-myapp-0, etc.).
Data persistence: kubectl exec myapp-0 -- cat /usr/share/nginx/html/index.html (shows "Hello from myapp-0").
Step 2: Pod Disruption Budgets (Availability During Disruptions)
# pdb.yaml
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: myapp-pdb
spec:
minAvailable: 2 # At least 2 pods available (good for 3 replicas)
# OR maxUnavailable: 1 # At most 1 pod unavailable
selector:
matchLabels:
app: myapp
Apply: kubectl apply -f pdb.yaml
Verify:
kubectl get pdb
Test disruption: kubectl drain node1 --ignore-daemonsets (won't evict if it violates PDB).
Best Practices:
minAvailable: 66% for odd replicas.
Pair with kubectl rollout status sts/myapp for updates.
Step 3: Rolling Updates (Safe Deployments)
StatefulSets default to RollingUpdate with partition for phased rollouts.
3.1 Update Image (e.g., to nginx:1.25)
yaml
# statefulset-v2.yaml (patch image)
# Same as initial, but change image: nginx:1.25
spec:
template:
spec:
containers:
- name: nginx
image: nginx:1.25 # Updated
updateStrategy:
type: RollingUpdate
rollingUpdate:
partition: 0 # Starts with pod-0 (default full rollout)
Apply: kubectl apply -f statefulset-v2.yaml
Monitor:
code
kubectl rollout status sts/myapp
kubectl get sts myapp -o jsonpath='{.status.updateRevision}'
kubectl get pods -l app=myapp -w # Watch ordered rollout (0->1->2)
Phased Rollout (Canary):
Set partition: 1 → Updates only pod-1+ (pod-0 stable).
Increment partition for full rollout.
Step 4: Rollbacks (Recovery)
StatefulSets track revision history. Rollback by:
Reverting spec (e.g., image).
Using partition to pause/reverse.
kubectl rollout undo (Kubernetes 1.22+ with server-side apply).
4.1 Manual Rollback (Revert Spec)
Edit back to nginx:1.21: kubectl edit sts myapp or re-apply statefulset-initial.yaml.
Monitor: kubectl rollout status sts/myapp (rolls back in reverse order).
4.2 Partition-Based Rollback
If partial rollout failed:
code
kubectl patch sts myapp -p '{"spec":{"updateStrategy":{"rollingUpdate":{"partition":0}}}}' # Pause at partition 0
# Fix issue, then increment partition
4.3 kubectl Rollout Undo (if enabled)
code
kubectl rollout undo sts/myapp
Verify Rollback:
Pods revert images: kubectl get pods -o jsonpath='{.items[*].spec.containers[*].image}'.
kubectl scale sts myapp --replicas=2 # Ordered scale-down (2->1->0)
kubectl delete -f . # Deletes PVCs if not retained
5.2 Best Practices
Aspect
Recommendation
Storage
Use ReadWriteOnce for databases; volumeClaimTemplates for auto-PVCs. Retention: reclaimPolicy: Retain.
PDB
Always pair with StatefulSets; test with kubectl drain.
Updates
Use maxUnavailable: 1 in strategy; partition for blue-green.
Rollbacks
Enable revision history (revisionHistoryLimit: 10); monitor with Prometheus.
Monitoring
kubectl get events; integrate ArgoCD/Flux for GitOps rollbacks.
HA
3+ replicas; AntiAffinity for spread.
Real Apps
MySQL/Postgres: Use operators (e.g., CrunchyData) for advanced features.
5.3 Full Cleanup
code
kubectl delete ns stateful-demo
This playbook ensures zero-downtime updates, data durability, and safe recoveries. Test in a staging cluster! For production, add RBAC, NetworkPolicies, and monitoring.
Troubleshooting:
Stuck rollout: kubectl describe sts myapp.
PVC issues: kubectl describe pvc data-myapp-0.
PDB blocks: kubectl describe pdb.
Need customizations (e.g., MySQL example)? Let me know! 🕵️