Skip to content
LF Cert Trainer

Lesson 105 · Section 8: Storage

Lesson 105: StatefulSets: stable names and storage for each Pod

Why databases need more than a Deployment, how a StatefulSet gives each Pod a fixed name, DNS record and PersistentVolumeClaim, how ordered start, scaling and rolling updates with partitions work, what happens to the volumes on delete, and how to build and debug one in the exam. · 20 min read · 3 min video

1/9StatefulSets
0:00 / 3:09

Narrated by the local narrator voice. Keys: Space plays and pauses, J and L step, C captions, F full screen.

Why StatefulSets exist

A Deployment is built for stateless applications: every Pod is the same, any Pod can answer any request, and a Pod that dies is replaced by a new one with a new random name somewhere else. Nobody cares which Pod is which.

Some applications care a lot. Think of a database with one primary and two replicas, a Kafka cluster, ZooKeeper, etcd or Elasticsearch. Each member:

NeedsWhyWhat a Deployment gives
A stable nameOther members are configured with its name; a primary is "member 0"A random suffix that changes with every new Pod
A stable network addressReplicas connect to the primary by name; clients connect to a chosen memberOne Service IP that load-balances over all Pods
Its own storage, kept across restartsEach member holds its own copy or share of the dataOne PersistentVolumeClaim shared by all Pods, or none
A predictable orderThe first member must start and form the cluster before the others joinAll Pods at once, in any order

A StatefulSet provides all four. It is still a controller that keeps N Pods running from a template, so most of what you know from ReplicaSets and Deployments applies. What changes is that its Pods are not interchangeable: each has an identity that sticks to it.

Each Pod has its own name, address and volumecreatesmountsmountsmountsDNS per PodStatefulSet dbreplicas: 3Service dbclusterIP: NonePod db-0db-0.dbPod db-1db-1.dbPod db-2db-2.dbPVC data-db-0BoundPVC data-db-1BoundPVC data-db-2Bound
Each Pod has its own name, address and volume. The StatefulSet names its Pods db-0, db-1, db-2. The headless Service gives each one a DNS name, and each Pod gets its own PersistentVolumeClaim from the claim template. A replaced db-1 keeps the name, the DNS record and the volume.

Parts:

  • StatefulSet db (replicas: 3)
  • Service db (clusterIP: None)
  • Pod db-0 (db-0.db)
  • Pod db-1 (db-1.db)
  • Pod db-2 (db-2.db)
  • PVC data-db-0 (Bound)
  • PVC data-db-1 (Bound)
  • PVC data-db-2 (Bound)

Connections:

  • StatefulSet db to Pod db-0
  • StatefulSet db to Pod db-1: creates
  • StatefulSet db to Pod db-2
  • Pod db-0 to PVC data-db-0: mounts
  • Pod db-1 to PVC data-db-1: mounts
  • Pod db-2 to PVC data-db-2: mounts
  • Service db to Pod db-2: DNS per Pod

What a StatefulSet is made of

A StatefulSet comes with a headless Service. Write them in one file:

apiVersion: v1
kind: Service
metadata:
  name: db
spec:
  clusterIP: None              # headless: DNS returns the Pod IPs, no virtual IP
  selector:
    app: db
  ports:
    - port: 6379
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: db
spec:
  serviceName: db              # the headless Service above: gives the Pods their DNS names
  replicas: 3
  selector:
    matchLabels:
      app: db
  template:
    metadata:
      labels:
        app: db
    spec:
      containers:
        - name: db
          image: redis:7.4
          ports:
            - containerPort: 6379
          volumeMounts:
            - name: data
              mountPath: /data
  volumeClaimTemplates:        # one PVC per Pod, per entry
    - metadata:
        name: data
      spec:
        accessModes: ["ReadWriteOnce"]
        storageClassName: standard     # or leave out for the default class
        resources:
          requests:
            storage: 1Gi

The fields that make it different from a Deployment:

FieldDefaultMeaning
serviceNamenoneName of the headless Service that governs the Pods' DNS names. You create that Service yourself.
volumeClaimTemplatesnoneClaims to create per Pod. A Pod's volume with the same name as a template uses its own claim.
podManagementPolicyOrderedReadyOrderedReady creates and deletes Pods one at a time in order; Parallel does them all at once
updateStrategyRollingUpdateRollingUpdate (with optional partition and maxUnavailable) or OnDelete
persistentVolumeClaimRetentionPolicyboth RetainWhether the claims are deleted when the StatefulSet is deleted (whenDeleted) or scaled down (whenScaled)
ordinals.start0The first number, if the Pods should be numbered from something else
minReadySeconds, revisionHistoryLimit0, 10As in a Deployment

How it works: identity from a number

The StatefulSet controller in kube-controller-manager works like the ReplicaSet controller with one rule added: it manages Pods by number. For replicas: 3 it wants exactly the Pods db-0, db-1 and db-2, and it creates the missing ones and deletes the extra ones by name.

Everything else hangs off the number:

IdentityValue for Pod 1 of StatefulSet dbWhere it comes from
Pod name and hostnamedb-1<statefulset name>-<number>
DNS namedb-1.db.default.svc.cluster.local<pod>.<serviceName>.<namespace>.svc.<cluster domain>
PVC namedata-db-1<template name>-<statefulset name>-<number>
Labelsstatefulset.kubernetes.io/pod-name: db-1, apps.kubernetes.io/pod-index: "1"Added by the controller

Storage that follows the number

When the controller creates db-1, it first checks for a PVC called data-db-1. If none exists, it creates one from the template, and the StorageClass's provisioner makes a PersistentVolume for it, exactly as you saw in the Storage Class lesson. If the claim already exists, it is reused. That is the whole trick: a replacement db-1 finds data-db-1 waiting and mounts the same data. The same holds when you scale down from 3 to 2 and back to 3: db-2 comes back with its old volume.

Names on the network: the headless Service

A normal Service has one virtual IP and spreads connections over its Pods. A database replica that must reach the primary cannot use that. A headless Service (clusterIP: None) has no virtual IP; its DNS name returns the Pod IPs. When it is the StatefulSet's serviceName, each Pod also gets a DNS record of its own:

db.default.svc.cluster.local          -> all ready Pod IPs (10.244.1.12, 10.244.2.7, 10.244.1.13)
db-0.db.default.svc.cluster.local     -> 10.244.1.12, only db-0
db-1.db.default.svc.cluster.local     -> 10.244.2.7, only db-1

Inside the same namespace db-0.db is enough. The IP behind db-0.db changes when the Pod is recreated, but the name stays, so configuration that uses names keeps working. Clients that do not care which member they reach can still use a normal ClusterIP Service with the same selector, next to the headless one.

Under the hood · Why the Service is not created for you

serviceName only tells the StatefulSet which Service's domain to put in the Pods' hostnames (spec.subdomain on each Pod). The DNS records exist only if a headless Service with that name and a matching selector exists in the namespace. Forget it, and the Pods run fine but db-0.db does not resolve.

Also note that by default the per-Pod record appears only once the Pod is Ready. A database that needs to find its peers while it is still starting (before its readiness probe passes) sets publishNotReadyAddresses: true on the headless Service.

Order: starting, scaling and stopping

OrderedReady: one at a time, in orderthenthendb-0Readydb-1startingdb-2waits
OrderedReady: one at a time, in order. With the default policy, db-1 is created only when db-0 is Running and Ready, and db-2 only when db-1 is. Scaling down removes the highest number first. A Pod that never becomes Ready stops everything after it.

Parts:

  • db-0 (Ready)
  • db-1 (starting)
  • db-2 (waits)

Connections:

  • db-0 to db-1: then
  • db-1 to db-2: then

With the default podManagementPolicy: OrderedReady:

OperationOrder
Create or scale updb-0, then db-1, then db-2; each is created only when all lower Pods are Running and Ready
Scale downHighest number first: db-2, then db-1; each is removed only when the one before is fully gone
A Pod failsOnly that Pod is recreated, with the same name

This order lets a cluster bootstrap safely: db-0 initialises the cluster, and every later member can join an existing member. The price is that a Pod that never becomes Ready blocks the rest. If db-1 fails its readiness probe, db-2 is never created, and a scale-down waits as well.

podManagementPolicy: Parallel drops the ordering for scaling: all Pods are created or deleted at once, without waiting for readiness. Use it when the members do not depend on each other and you only want stable names and storage. The field cannot be changed after creation.

Updates

A rolling update goes from the highest number downupdatedkeptkeptStatefulSet dbpartition: 2db-2new versiondb-1old, below partitiondb-0old, below partition
A rolling update goes from the highest number down. Pods are replaced one at a time, from db-2 down to db-0, each only after the one before is Ready again. With partition: 2, only Pods numbered 2 or higher are updated: a canary.

Parts:

  • StatefulSet db (partition: 2)
  • db-2 (new version)
  • db-1 (old, below partition)
  • db-0 (old, below partition)

Connections:

  • StatefulSet db to db-2: updated
  • StatefulSet db to db-1: kept
  • StatefulSet db to db-0: kept

Changing the Pod template (a new image, an environment variable) starts an update. With updateStrategy: RollingUpdate, the default:

  • Pods are replaced one at a time, from the highest number down: db-2, then db-1, then db-0.
  • Each Pod is deleted first and recreated with the same name; it reattaches its own PVC.
  • The controller waits until the new Pod is Running and Ready before it moves to the next lower number.

The lowest numbers usually hold the most important members (the primary is often db-0), so they are updated last, after the new version has proved itself on the others.

Partitions: canaries and staged rollouts

rollingUpdate.partition: N updates only the Pods whose number is N or higher. The others keep the old template, even when they are deleted and recreated.

kubectl patch sts db -p '{"spec":{"updateStrategy":{"type":"RollingUpdate","rollingUpdate":{"partition":2}}}}'
kubectl set image sts/db db=redis:7.4.1          # only db-2 is updated
kubectl get pods -l app=db -L controller-revision-hash
kubectl patch sts db -p '{"spec":{"updateStrategy":{"rollingUpdate":{"partition":0}}}}'   # now db-1 and db-0

The other strategy, OnDelete, never replaces a Pod by itself. A Pod gets the new template only when you delete it. That gives you full control, node by node or member by member, at the price of doing it all by hand.

kubectl rollout status, history and undo work on StatefulSets; like DaemonSets, they keep their history in ControllerRevisions.

Under the hood · A broken update can get stuck

With OrderedReady and the default rolling update, suppose the new image crashes. db-2 is replaced, never becomes Ready, and the update stops there: good, the damage is limited to one member. Now you roll back with kubectl rollout undo sts/db. The template goes back to the old version, but the controller still waits for db-2 to become Ready before it does anything, and db-2 is still the broken Pod.

The documented way out: after reverting the template, delete the broken Pod (kubectl delete pod db-2). It is recreated from the restored template and the StatefulSet carries on. This is called a forced rollback, and it is a classic exam trap: the rollback "does not work" until you delete the Pod.

When a node fails

A Deployment replaces the Pods of a lost node within minutes. A StatefulSet is deliberately more careful. Two Pods named db-1 must never run at the same time, because both would write to the same volume or claim the same role. As long as the old db-1 exists in the API (it shows Terminating or Unknown because its kubelet cannot confirm it stopped), the controller does not create a new one.

The Pod is released when the node comes back, when the Node object is deleted, or when an administrator confirms that the node is really off: by adding the taint node.kubernetes.io/out-of-service=nodeshutdown:NoExecute to the node (non-graceful node shutdown), or as a last resort with kubectl delete pod db-1 --force --grace-period=0. Force deletion only removes the API object; if the old container is in fact still running on a partitioned node, two db-1 may now run. Do it only when you are sure the node is down.

StatefulSet or something else?

You wantUse
Members with fixed names, own disks, ordered start (databases, queues, consensus systems)StatefulSet
Interchangeable copies, even if they share one volumeDeployment
One Pod per nodeDaemonSet
A single database Pod that just needs its data to surviveA Deployment with replicas: 1, strategy: Recreate and one PVC works; a StatefulSet with 1 replica is the more common choice, because it also gives a stable name and never runs two copies

For real production databases, an operator (see the Operator Framework lesson) usually manages the StatefulSet for you and adds backups, failover and upgrades. Underneath, it is almost always a StatefulSet.

Using it

Example · Create a StatefulSet with its headless Service

The task: "create a StatefulSet web with 2 replicas of nginx:1.27 in namespace shop, with its own 500Mi volume mounted at /usr/share/nginx/html in each Pod, and a headless Service web".

There is no kubectl create statefulset. The fastest route is to generate a Deployment and change it:

kubectl -n shop create deployment web --image=nginx:1.27 --replicas=2 \
  --dry-run=client -o yaml > web.yaml
kubectl -n shop create service clusterip web --clusterip=None --tcp=80:80 \
  --dry-run=client -o yaml >> web.yaml

In web.yaml: add --- between the two objects, change kind: Deployment to kind: StatefulSet, delete strategy: {}, add serviceName: web under spec, add a volumeMounts entry named www to the container, and add a volumeClaimTemplates entry named www (500Mi, ReadWriteOnce) at the level of template. The Service's selector from create service is app: web, which matches the labels from create deployment.

kubectl apply -f web.yaml
kubectl -n shop get sts,pods,pvc
# statefulset.apps/web   2/2
# pod/web-0  pod/web-1
# persistentvolumeclaim/www-web-0  www-web-1   Bound

Example · Prove that the data and name survive

kubectl -n shop exec web-0 -- sh -c 'echo hello from web-0 > /usr/share/nginx/html/index.html'
kubectl -n shop delete pod web-0
kubectl -n shop get pods -w                       # web-0 comes back, same name
kubectl -n shop exec web-0 -- cat /usr/share/nginx/html/index.html   # hello from web-0
kubectl -n shop run t --rm -it --image=busybox:1.36 --restart=Never -- wget -qO- web-0.web

Example · A StatefulSet that stops at web-0

kubectl get pods shows web-0 0/1 Pending and no web-1.

kubectl -n shop describe pod web-0 | tail -n 5
# Warning  FailedScheduling  0/3 nodes are available: pod has unbound immediate PersistentVolumeClaims.
kubectl -n shop get pvc
# www-web-0   Pending                                      fast    2m
kubectl -n shop describe pvc www-web-0 | tail -n 3
# Warning  ProvisioningFailed  storageclass.storage.k8s.io "fast" not found

The chain is: the claim template names a StorageClass that does not exist, so the claim stays Pending, so web-0 cannot be scheduled, so OrderedReady never creates web-1. volumeClaimTemplates cannot be edited on an existing StatefulSet, so fix the file, delete the StatefulSet and the Pending claim, and apply again. Deleting only the StatefulSet would leave www-web-0 behind with the wrong class, and the new web-0 would reuse it.

Example · Scale down and back up

kubectl -n shop scale sts web --replicas=1        # web-1 is removed, www-web-1 stays
kubectl -n shop get pvc                           # both claims still Bound
kubectl -n shop scale sts web --replicas=2        # web-1 returns and mounts www-web-1 again

Tricks

Common mistakes

  • Forgetting the headless Service. The Pods run, but db-0.db does not resolve. Its name must equal serviceName and it needs clusterIP: None.
  • Expecting the PVCs to go away. Deleting the StatefulSet or scaling down keeps them, unless the retention policy says Delete.
  • Adding a volumes: entry for the claim template. The template already provides the volume named data; a second volumes entry with that name conflicts. Only the volumeMounts refer to it.
  • Using ReadWriteOnce and expecting all Pods to share one disk. Each Pod gets its own claim. If you want one shared volume, that is a normal persistentVolumeClaim volume in the Pod template, and probably a Deployment.
  • Rolling back and waiting forever. After rollout undo of a broken update, delete the Pod that is stuck.
  • Force-deleting Pods on an unreachable node without thinking. It can leave two copies writing to one volume.
  • Deleting the StatefulSet to stop the app in order. Scale to 0 first; delete does not keep the order.

Recap

  • A StatefulSet runs Pods numbered 0 to N-1 with stable names (db-0), stable DNS names through a headless Service named in serviceName (db-0.db), and one PVC per Pod from volumeClaimTemplates (data-db-0).
  • A replacement Pod keeps its number, so it gets the same name and reuses its claim. Claims are kept on scale-down and delete unless persistentVolumeClaimRetentionPolicy says Delete.
  • OrderedReady (default) starts Pods one at a time in order, each after the lower ones are Ready, and removes them in reverse. Parallel does it all at once.
  • Rolling updates go from the highest number down, one at a time; partition: N updates only numbers N and up. OnDelete waits for you. A stuck rollback needs the broken Pod deleted.
  • In the exam: no kubectl create sts; convert a Deployment, add serviceName and volumeClaimTemplates, create the headless Service, and check the PVCs and StorageClass when Pods are Pending.

Official docs

Quiz: check what you learned

6 questions on this lesson · about 3 min · instant feedback. Missed questions come back in your review queue.

Sign in to take the quiz and keep your score.

Practise: try it on a real cluster

A hands-on lab for this lesson. You get goals, not steps: any solution that reaches them passes.

  • Run a replicated app as a StatefulSet with a headless Service, so each copy has its own name and its own volume.

    Build · Level 2 · standard · target 20 min

Discussion

Learners ask and answer questions here. Sign in to read and join the discussion.