StatefulSets vs Deployments

Kubernetes · lesson 14 of 32 · 4 min read

Know when stable identity, ordering and per-pod disks push you off Deployments and onto StatefulSets.

Open this lesson in the learning hub

Key points

  • Deployment pods are interchangeable with random names. StatefulSet pods are db-0, db-1, stable and ordered.
  • volumeClaimTemplates gives each pod its own PVC that follows it across restarts and reschedules.
  • Pair it with a headless Service so db-0.db.prod.svc.cluster.local resolves to that exact pod.
  • Rollouts go one pod at a time, highest ordinal first, and halt if a pod never becomes Ready.
  • Deleting a StatefulSet does not delete its PVCs. That is a safety feature and a cleanup chore.
  • For real databases prefer a managed service or a proper Operator. A bare StatefulSet does not do backups or failover.

Example

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: db
spec:
  serviceName: db          # must be a headless Service (clusterIP: None)
  replicas: 3
  selector:
    matchLabels:
      app: db
  template:
    metadata:
      labels:
        app: db
    spec:
      containers:
        - name: postgres
          image: postgres:16
          ports:
            - containerPort: 5432
          volumeMounts:
            - name: data
              mountPath: /var/lib/postgresql/data
  volumeClaimTemplates:
    - metadata:
        name: data
      spec:
        accessModes: ["ReadWriteOnce"]
        resources:
          requests:
            storage: 50Gi

Stateless goes in a Deployment. Anything that needs a name and a disk goes in a StatefulSet.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Kubernetes course, and every lesson in it is listed on the Kubernetes contents page.