Kubernetes StatefulSets: Managing Stateful Applications
StatefulSets are designed for applications that need stable identities and persistent storage.
StatefulSet vs Deployment
| Feature | Deployment | StatefulSet |
|---|---|---|
| Pod names | Random suffix | Ordered (app-0, app-1) |
| Scaling | Parallel | Sequential |
| Storage | Shared | Per-pod PVC |
| Deletion | Any order | Reverse order |
| Network | Via Service | Stable DNS |
When to Use StatefulSets
- Databases (MySQL, PostgreSQL, MongoDB)
- Distributed systems (Kafka, Elasticsearch, ZooKeeper)
- Applications needing stable network identity
- Applications needing persistent per-pod storage
StatefulSet Components
1. Headless Service
apiVersion: v1
kind: Service
metadata:
name: mysql
spec:
clusterIP: None # Headless
selector:
app: mysql
ports:
- port: 33062. StatefulSet
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: mysql
spec:
serviceName: mysql # Must match headless service
replicas: 3
selector:
matchLabels:
app: mysql
template:
metadata:
labels:
app: mysql
spec:
containers:
- name: mysql
image: mysql:8.0
ports:
- containerPort: 3306
volumeMounts:
- name: data
mountPath: /var/lib/mysql
volumeClaimTemplates:
- metadata:
name: data
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 10GiStable Network Identity
Pods get predictable DNS names:
mysql-0.mysql.default.svc.cluster.local
mysql-1.mysql.default.svc.cluster.local
mysql-2.mysql.default.svc.cluster.localOrdered Operations
Scaling Up
mysql-0 → mysql-1 → mysql-2Scaling Down
mysql-2 → mysql-1 → mysql-0Pod Management Policies
spec:
podManagementPolicy: OrderedReady # Default
# or
podManagementPolicy: ParallelUpdate Strategies
spec:
updateStrategy:
type: RollingUpdate # Default
rollingUpdate:
partition: 2 # Only update pods >= 2Volume Claim Templates
Each pod gets its own PVC:
data-mysql-0
data-mysql-1
data-mysql-2PVCs persist after pod deletion, ensuring data survives rescheduling.
Common Commands
# Get StatefulSet
kubectl get statefulset
# Scale StatefulSet
kubectl scale statefulset mysql --replicas=5
# Delete without deleting PVCs
kubectl delete statefulset mysql --cascade=orphanPractice StatefulSets
StatefulSets appear in CKA and CKAD exams. Practice at Sailor.sh.