sajad torkamani

What is StatefulSet?

A StatefulSet in Kubernetes is a workload resource that’s used to manage stateful pods.

Examples of a stateful pod can be:

  • A pod that needs a unique and stable network identity (e.g., a name like pod-1 or pod-2) that persists even if the pod is deleted or restarted.
  • A pod that needs its own persistent volume that needs to persist even if the pod is deleted or restarted.

A StatefulSet object can be used to run database pods like a MySQL application though in practice, databases are hosted outside the K8s cluster in something like AWS RDS.

Example StatefulSet config

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: web
spec:
  serviceName: "web"
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.25
        ports:
        - containerPort: 80
        volumeMounts:
        - name: www
          mountPath: /usr/share/nginx/html
  volumeClaimTemplates:
  - metadata:
      name: www
    spec:
      accessModes: ["ReadWriteOnce"]
      resources:
        requests:
          storage: 1Gi

With the above definition, K8s will:

  • Create 3 pods named web-0, web-1, web-2 (3 because spec.replicas is set to 3).
  • Each pod will get its own unique DNS name (e.g., web-0.web.default.svc.cluster.local).
  • Each pod will have its own 1Gi PersistentVolume (separate from other pods).
  • The pods will start in order and can be addressed by their name.
Tagged: Kubernetes