🎓 A1Learner
🔍
0 of 51 lessons completed

Kubernetes: StatefulSets

A StatefulSet is a workload that gives each Pod a stable name and its own storage. A StatefulSet creates Pods in order, one at a time, and it removes them in reverse order.

Stable names and stable storage

serviceName links the Pods to a Service called web. volumeClaimTemplates asks for 1Gi of storage per Pod.

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: web
spec:
  serviceName: web
  replicas: 2
  selector:
    matchLabels:
      app: web
  template:
    metadata:
      labels:
        app: web
    spec:
      containers:
      - name: web
        image: nginx:1.27-alpine
        volumeMounts:
        - name: data
          mountPath: /data
  volumeClaimTemplates:
  - metadata:
      name: data
    spec:
      accessModes: ["ReadWriteOnce"]
      resources:
        requests:
          storage: 1Gi

Create the StatefulSet

apply creates the StatefulSet. It then creates web-0 first, and web-1 after it.

kubectl apply -f web-statefulset.yaml

Pods in order, with stable names

web-0 started before web-1. The names stay the same across restarts.

kubectl get pods

Each Pod owns its storage

Two claims exist, one per Pod. data-web-0 belongs to web-0, and data-web-1 belongs to web-1.

kubectl get pvc

Example

kubectl apply -f web-statefulset.yaml
kubectl get statefulsets
kubectl get pods

Key points

  • StatefulSet: a workload for apps where each copy keeps its own identity and data.
  • Use a StatefulSet for a database, where each copy must keep its own data.
  • A StatefulSet names its Pods web-0, web-1 and web-2, in order.
  • A StatefulSet needs a serviceName, which names the Service that groups its Pods.
  • A StatefulSet uses volumeClaimTemplates to give each Pod its own storage claim.
  • A Pod that restarts keeps its name and its storage, so its data survives.

In this example, apply creates a StatefulSet with two replicas. get statefulsets shows 2/2 ready. get pods shows web-0 and web-1 in order. Each Pod keeps its own name and its own storage. A restart brings back the same Pod with the same data.

Note

Stateless means an app where every copy is the same. A StatefulSet suits an app where each copy is different.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

What does a StatefulSet give each Pod that a Deployment does not?