When the CKA course covers workloads, it includes this line:
Additional topics such as StatefulSets are out of scope for the exam. However, if you wish to learn them, they are covered in the Certified Kubernetes Application Developer (CKAD) course.
It's not on the exam, but StatefulSets have already come up several times in earlier posts: the headless Service in the networking post exists for them, and MinIO in the storage post gets its disks through their volumeClaimTemplates. So, like Kubernetes Self-Healing, they get a post of their own.
Where Deployments Fall Short
A Deployment assumes every Pod is identical and can be replaced at any time. That makes sense for a stateless web service, but it breaks down for a database cluster:
| Need | What a Deployment does | Impact on a stateful service |
|---|---|---|
| Stable identity | Pod names carry a random suffix, e.g. web-7c79c4bf97-x2k8q, which changes on replacement |
Cluster members can't find each other by name |
| Stable address | Only the Service's ClusterIP; the Pod behind it is picked at random | Clients can't say "connect to the primary" |
| Separate data | All replicas share the same PVC from the template |
An RWO volume can only attach to one Node, so replicas conflict; even with RWX, everyone writing the same data causes trouble |
| Startup order | All Pods are created at once | Replicas start looking for the primary before it's up |
StatefulSets are designed around exactly these points. Like a Deployment, a StatefulSet creates replicas from a Pod template; the difference is that each replica has its own identity, and that identity survives Pod replacement.
| Deployment | StatefulSet | |
|---|---|---|
| Pod name | <rs name>-<random suffix> |
<statefulset name>-<ordinal>, starting at 0 |
| Network identity | Shares the Service's ClusterIP | Each Pod gets its own DNS name (requires a headless Service) |
| Storage | All Pods share one PVC | volumeClaimTemplates creates a dedicated PVC for each Pod |
| Scaling | All at once; scale-down deletes Pods at random | In order by default; scale-down starts from the highest ordinal |
| Rolling update | New Pod first, then delete the old one (maxSurge) |
Highest ordinal first, one at a time, delete before recreate |
| Middle layer | Manages Pods through a ReplicaSet | Manages Pods directly, no ReplicaSet |
Hands-on: Creating a StatefulSet
Headless Service
A StatefulSet needs a headless Service (clusterIP: None), and you have to create that Service yourself; the StatefulSet won't do it for you. A headless Service gets no ClusterIP, so DNS queries return Pod IPs directly, and each Pod gets its own <pod>.<service> record.
apiVersion: v1
kind: Service
metadata:
name: nginx
labels:
app: nginx
spec:
clusterIP: None
selector:
app: nginx
ports:
- name: web
port: 80
StatefulSet
kubectl create has no subcommand for StatefulSets, so the trick is the same as for DaemonSets: generate a Deployment's YAML, change the kind, delete strategy and status, and add serviceName and volumeClaimTemplates.
kubectl create deployment web --image=nginx:1.29 --replicas=3 --dry-run=client -o yaml > web.yaml
After editing:
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: web
spec:
serviceName: nginx # matches the headless Service above
replicas: 3
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.29
ports:
- name: web
containerPort: 80
volumeMounts:
- name: www
mountPath: /usr/share/nginx/html
volumeClaimTemplates: # each Pod gets its own PVC from this template
- metadata:
name: www
spec:
accessModes:
- ReadWriteOnce
storageClassName: topolvm-provisioner
resources:
requests:
storage: 100Mi
storageClassName points to the TopoLVM installed in the storage post; any StorageClass with dynamic provisioning in your cluster will do.
kubectl apply -f nginx-svc.yaml -f web.yaml
kubectl get pods -l app=nginx -w
NAME READY STATUS RESTARTS AGE
web-0 0/1 Pending 0 0s
web-0 0/1 ContainerCreating 0 2s
web-0 1/1 Running 0 5s
web-1 0/1 Pending 0 0s
web-1 0/1 ContainerCreating 0 2s
web-1 1/1 Running 0 5s
web-2 0/1 Pending 0 0s
...
The Pods are created one at a time: web-1 isn't created until web-0 is Running and Ready. The PVCs follow the naming pattern <template name>-<statefulset name>-<ordinal>:
kubectl get pvc
NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS AGE
www-web-0 Bound pvc-1b9e... 100Mi RWO topolvm-provisioner 40s
www-web-1 Bound pvc-5c2a... 100Mi RWO topolvm-provisioner 33s
www-web-2 Bound pvc-9f07... 100Mi RWO topolvm-provisioner 26s
Each Pod Has Its Own DNS Name
First write each Pod's hostname into its volume, so we can check later whether the data follows the Pod:
for i in 0 1 2; do
kubectl exec web-$i -- sh -c 'hostname > /usr/share/nginx/html/index.html'
done
Start a test Pod and query DNS:
kubectl run dnstest --image=busybox:1.28 --restart=Never -- sleep 3600
kubectl exec dnstest -- nslookup nginx
kubectl exec dnstest -- nslookup web-0.nginx
kubectl exec dnstest -- wget -qO- web-1.nginx
nslookup nginx: the headless Service has no ClusterIP, so it returns the IPs of all three Pods.nslookup web-0.nginx: returns onlyweb-0's IP; the full name isweb-0.nginx.default.svc.cluster.local.wget -qO- web-1.nginx: returnsweb-1, so you reach exactly the Pod you asked for.
Database clusters configure their members with stable names like these, for example by hard-coding db-0.db, db-1.db and db-2.db in the config file. No matter how many times the Pods are recreated or how their IPs change, the config stays the same.
Delete the Pods, Keep the Identity and Data
kubectl get pods -l app=nginx -o wide
kubectl delete pod web-0 web-1
kubectl get pods -l app=nginx -o wide -w
The replacement Pods are still named web-0 and web-1, though their IPs usually change. Query again:
kubectl exec dnstest -- nslookup web-0.nginx # returns the new IP
kubectl exec dnstest -- wget -qO- web-0.nginx # still web-0
The DNS record now points to the new IP, and index.html is still there because the new web-0 reattached the original www-web-0. This is what "stable" means for a StatefulSet: the IP isn't guaranteed to stay the same; what stays the same is the mapping between name, DNS record and PVC.
Don't let clients cache Pod IPs
DNS updates when a Pod is recreated, but an application that resolves the name only once at startup will keep connecting to the old IP. Connect to StatefulSet Pods by DNS name, and watch the client's DNS cache TTL.
Scaling Up and Down
kubectl scale statefulset web --replicas=5 # creates web-3, then web-4
kubectl scale statefulset web --replicas=2 # deletes web-4, then web-3, then web-2
kubectl get pvc
Scaling down starts with the highest ordinal and waits for each Pod to fully terminate before deleting the next. After scaling down, the www-web-2, www-web-3 and www-web-4 PVCs are kept by default, so the next time you scale to 5 replicas, the new web-2 to web-4 reattach their original data.
This is deliberate: data matters more than Pods, and Kubernetes won't delete your data just because you reduced the replica count. If you're sure you don't need it, set persistentVolumeClaimRetentionPolicy (GA in Kubernetes 1.32):
spec:
persistentVolumeClaimRetentionPolicy:
whenDeleted: Retain # when the StatefulSet is deleted
whenScaled: Delete # when replicas are scaled down
| Field | When it applies | Retain (default) |
Delete |
|---|---|---|---|
whenDeleted |
The whole StatefulSet is deleted | PVCs are kept | All PVCs are deleted |
whenScaled |
The replica count is reduced | PVCs are kept | PVCs of the removed Pods are deleted |
Whether the PV behind a deleted PVC is also deleted still depends on the StorageClass's reclaimPolicy.
podManagementPolicy
Creating Pods in order takes a while when there are many Pods and each starts slowly. If the application doesn't care about startup order and only needs stable identity and storage, you can switch to parallel:
| podManagementPolicy | Behavior |
|---|---|
OrderedReady (default) |
Create in order, each one after the previous is Running and Ready; scale down in reverse order |
Parallel |
Create and delete all at once, without waiting |
This setting only affects scaling; rolling updates still follow the rules below. It can't be changed after creation.
Rolling Updates
A StatefulSet's updateStrategy has two options:
| updateStrategy | Behavior |
|---|---|
RollingUpdate (default) |
Starting from the highest ordinal, delete then recreate each Pod, waiting for the new one to be Running and Ready before moving on |
OnDelete |
Changing the template doesn't trigger an update; you delete Pods yourself and the replacements use the new version |
The biggest difference from a Deployment: a Deployment creates the new Pod before deleting the old one, while a StatefulSet deletes first and then recreates. The new web-2 has to reuse the same name and the same PVC, so the two can't exist at the same time, which means one replica is missing at any point during the update.
kubectl set image statefulset/web nginx=nginx:1.30
kubectl rollout status statefulset/web
kubectl rollout history statefulset/web
kubectl rollout undo statefulset/web
The kubectl rollout commands work just as they do for Deployments, and kubectl rollout restart likewise recreates every Pod in order.
partition: Staged Updates
RollingUpdate accepts a partition. Only Pods with an ordinal greater than or equal to the partition are updated; the rest stay on the old version, and even if they're deleted they're recreated from the old template:
# Update only web-2 for now
kubectl patch statefulset web -p '{"spec":{"updateStrategy":{"type":"RollingUpdate","rollingUpdate":{"partition":2}}}}'
kubectl set image statefulset/web nginx=nginx:1.30
kubectl get pods -l app=nginx -o custom-columns=NAME:.metadata.name,IMAGE:.spec.containers[0].image
NAME IMAGE
web-0 nginx:1.29
web-1 nginx:1.29
web-2 nginx:1.30
Once web-2 looks good, lower the partition step by step to 0 and the remaining Pods are updated in order. This works as a simple canary, and it's a common way to upgrade one database replica first and watch it during an upgrade.
❗When an update gets stuck, reverting the template isn't enough
If the new version is broken and the Pod never becomes Ready, the StatefulSet waits there: it neither continues nor recovers on its own. After reverting the template, you also have to manually delete the Pod created from the broken template; only then does the StatefulSet recreate it from the old template. The official docs call this a forced rollback.
What Happens When a Node Fails
The self-healing post explained that once a Node has been unreachable for 300 seconds, its Pods are evicted and the ReplicaSet creates new Pods on other Nodes. StatefulSet Pods behave differently:
- The Node goes unreachable, and the evicted Pod sits in
Terminatingbecause the kubelet can't report that its containers have actually stopped. - A Deployment doesn't care; the new Pod just gets a different name. A StatefulSet, however, needs to create another Pod named
web-1, and it won't create the new one until the oldweb-1object is really gone. - As a result, that replica stays missing until the Node comes back or someone confirms the old Pod is no longer running.
This is by design: a StatefulSet guarantees at most one Pod per identity. If the Node merely lost its network and the containers on it are still alive, starting a second web-1 would have two Pods writing the same data, causing split brain.
Once you've confirmed the Node is really shut down or broken, there are a few ways to let the StatefulSet continue:
# Option 1: mark the Node out-of-service (GA in Kubernetes 1.28)
# Its Pods are force-deleted and volumes detached right away, so Pods can be recreated elsewhere
kubectl taint nodes k8s-w1 node.kubernetes.io/out-of-service=nodeshutdown:NoExecute
# Option 2: force-delete the Pod
kubectl delete pod web-1 --grace-period=0 --force
# Option 3: remove the Node object from the cluster
kubectl delete node k8s-w1
After the Node is repaired and rejoins, remember to remove the out-of-service taint.
❗Pods on local storage can't change Nodes
If the PVC uses local storage such as TopoLVM, the PV is bound to its original Node. Even after the old Pod is deleted, the new web-1 can only be scheduled onto that Node and stays Pending until it recovers. When running a StatefulSet on local storage, redundancy has to come from the application's own replication (database primary/replica, MinIO's erasure coding), not from Kubernetes moving the Pod.
Things to Watch Out For
- StatefulSets don't replicate data. They only give each Pod a stable identity and storage. Which Pod is the primary, how data is synchronized, and how failover works are up to the application. In practice databases are usually deployed with an operator or Helm chart, and many of them build on StatefulSets (MinIO Operator, Bitnami's PostgreSQL and Redis charts), though some, such as CloudNativePG, skip StatefulSets and manage Pods and PVCs directly.
- Deleting a StatefulSet doesn't guarantee Pod termination order. If you need an orderly shutdown, run
kubectl scale statefulset web --replicas=0, wait for all Pods to terminate, then delete the StatefulSet. - You must create the headless Service yourself. If it's missing or
serviceNameis wrong, the Pods still run, but their DNS names won't resolve. - Changes to
volumeClaimTemplatesdon't apply to existing PVCs. To expand storage, editspec.resources.requests.storageon each PVC directly (the StorageClass needsallowVolumeExpansion: true). - Use a readinessProbe to control ordering.
OrderedReadychecks for Ready, and without a readinessProbe a container counts as Ready as soon as it starts, which makes ordered startup mostly meaningless.
Summary
- A StatefulSet gives each Pod a stable ordinal name, DNS name and dedicated PVC. The mapping between them survives Pod replacement, but the IP changes.
- You create a headless Service yourself and reference it in
serviceName; Pod DNS names are<pod>.<service>.<namespace>.svc.cluster.local. - PVCs created from
volumeClaimTemplatesare kept on scale-down and deletion by default;persistentVolumeClaimRetentionPolicychanges that. - Pods are created in order and scaled down in reverse order by default;
Paralleldoes both at once. - Rolling updates start from the highest ordinal and delete before recreating;
partitionallows staged updates, andOnDeletemakes them fully manual. - When a Node fails, a StatefulSet won't automatically recreate the Pod elsewhere, to avoid two Pods with the same identity. Confirm the Node is really down, then use the
out-of-servicetaint or a force delete.