Kubernetes Tutorial · Workloads · Lesson 10 of 26

StatefulSets

Stable names, ordered startup and per-replica storage for databases and clustered systems.

Create a free account to save this page, take notes and track your progress. Sign in

When pods need identity

Deployment pods are interchangeable. StatefulSet pods get:

  • Stable names: db-0, db-1, db-2, kept across rescheduling.
  • Stable DNS through a headless Service: db-0.db.<namespace>.svc.cluster.local.
  • Per-pod storage from volumeClaimTemplates: each replica keeps its own PersistentVolumeClaim.
  • Ordered startup, scaling and updates (by default).

Running databases on Kubernetes is possible but demanding (backups, failover, upgrades); operators (CloudNativePG, Strimzi) or managed databases are often the better choice.

Stable names, DNS and per-pod volumes
kubectl create namespace demo-sts > /dev/null
trap 'kubectl delete namespace demo-sts --wait=false > /dev/null' EXIT
cat > sts.yaml <<'EOF'
apiVersion: v1
kind: Service
metadata:
  name: kv
spec:
  clusterIP: None
  selector: {app: kv}
  ports: [{port: 6379}]
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: kv
spec:
  serviceName: kv
  replicas: 2
  selector:
    matchLabels: {app: kv}
  template:
    metadata:
      labels: {app: kv}
    spec:
      containers:
        - name: redis
          image: redis:8-alpine
          volumeMounts: [{name: data, mountPath: /data}]
  volumeClaimTemplates:
    - metadata:
        name: data
      spec:
        accessModes: [ReadWriteOnce]
        resources:
          requests:
            storage: 100Mi
EOF
kubectl -n demo-sts apply -f sts.yaml > /dev/null
kubectl -n demo-sts rollout status statefulset/kv --timeout=180s > /dev/null
echo "pods: $(kubectl -n demo-sts get pods -l app=kv -o name | sort | tr '\n' ' ')"
echo "claims: $(kubectl -n demo-sts get pvc -o custom-columns=NAME:.metadata.name,STATUS:.status.phase --no-headers | tr -s ' ' | tr '\n' ';')"
kubectl -n demo-sts run probe --rm -i --restart=Never --image=redis:8-alpine -- redis-cli -h kv-1.kv ping 2>/dev/null | head -1

Output

pods: pod/kv-0 pod/kv-1 
claims: data-kv-0 Bound;data-kv-1 Bound;
PONG

Run this on your computer — see “Get Started” for setup.

Test yourself

What does a StatefulSet give a pod that a Deployment doesn't?

  1. More CPU
  2. A stable name and DNS identity, plus its own persistent volume claim
  3. Faster startup
  4. A public IP
Show answer

Answer: A stable name and DNS identity, plus its own persistent volume claim

That's what clustered stateful systems need to find and keep their data.

Was this page helpful?