What is a StatefulSet?
- Docker & Kubernetes course
- Advanced
- Lesson 13/70
- 4 min
Learn that a StatefulSet manages stateful applications.
What is a StatefulSet?
A StatefulSet is the Deployment's counterpart for stateful applications: databases, message queues, Kafka, Elasticsearch. It differs from a Deployment in three ways:
- Stable identity: pod names are ordinal (
db-0,db-1) and get the same name when recreated. - Persistent storage: each pod has its own PersistentVolumeClaim and is attached to the same disk when recreated.
- Ordered operations: pods start in order and shut down in reverse.
$ kubectl get pods -l app=db
NAME READY STATUS RESTARTS AGE
db-0 1/1 Running 0 10m
db-1 1/1 Running 0 9m
db-2 1/1 Running 0 8mWhen to use a StatefulSet?
For applications whose replicas are interchangeable (web, API), a Deployment is used. A StatefulSet is needed where the replicas' identity matters: databases with a primary/replica distinction, nodes joining a cluster with their own identity (etcd, ZooKeeper), systems where each replica holds its own data.
Deployment: web-7c5b9f-abcde web-7c5b9f-fghij (interchangeable)
StatefulSet: db-0 (primary) db-1 (replica) (each different)In production, an operator (e.g. CloudNativePG) is often used instead of writing a StatefulSet by hand.
Practice Inspect the StatefulSet
Write three commands: list the StatefulSets; list the pods labelled app=db; show the db StatefulSet in detail.
Starter code
# buraya yazSample solution
kubectl get sts
kubectl get pods -l app=db
kubectl describe sts dbExpected output
NAME READY AGE db 3/3 10m NAME READY STATUS RESTARTS AGE db-0 1/1 Running 0 10m db-1 1/1 Running 0 9m db-2 1/1 Running 0 8m Name: db Replicas: 3 desired | 3 total Update Strategy: RollingUpdate
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What happens if the db-1 pod is deleted?
- db-3 is created
- Its data is deleted
- It is recreated with the same name (db-1) and attached to the same disk Correct answer
- A new pod with a random name is created
Explanation: The identity and storage are kept independently of the pod.
2 List the StatefulSets with the abbreviation.
kubectl get ____
kubectl get sts
Explanation: sts is the abbreviation of statefulsets.
3 Match.
| Term | Meaning |
|---|---|
db-0 |
Ordinal stable name |
a PVC per pod |
Persistent storage |
ordered startup |
db-0, then db-1 |
Deployment |
Interchangeable replicas |