How to Deploy Stateful Applications with Kubernetes StatefulSets

Kubernetes StatefulSets are designed for applications that require stable network identities, persistent storage, and ordered deployment. Unlike Deployments, they ensure pods are created, scaled, and terminated in a predictable sequence. This tutorial walks you through using StatefulSets for stateful workloads like databases or message queues.

Before you begin, ensure you have a running Kubernetes cluster (minikube or cloud-based) and kubectl configured. You’ll also need a StorageClass for persistent volumes.

Article illustration

1. Define a StatefulSet YAML Manifest

Start by creating a file statefulset.yaml. The key fields are serviceName (a headless Service) and volumeClaimTemplates.

  • serviceName: Points to a headless Service that gives each pod a stable DNS name.
  • volumeClaimTemplates: Automatically provisions a PersistentVolumeClaim (PVC) for each pod.
  • podManagementPolicy: Use OrderedReady (default) for sequential startup.

Example YAML Snippet

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

2. Create the Headless Service

StatefulSets require a headless Service (cluster IP = None) for network identity.

apiVersion: v1
kind: Service
metadata:
  name: nginx
  labels:
    app: nginx
spec:
  ports:
  - port: 80
    name: web
  clusterIP: None
  selector:
    app: nginx

3. Deploy and Verify

Run kubectl apply -f service.yaml -f statefulset.yaml. Then check pod names – they will be web-0, web-1, web-2 in order.

  • Stable identity: Each pod gets a unique hostname like web-0.nginx.default.svc.cluster.local.
  • Persistent storage survives pod restarts because PVCs are not deleted.
  • Ordered rollout is ideal for databases that require leader election or sequential updates.

4. Scaling and Updates

Scale with kubectl scale sts web --replicas=5 – new pods are added in order. Rolling updates happen one by one, ensuring data consistency. Test with kubectl rollout status sts/web.

Conclusion: StatefulSets solve the identity and storage challenges of stateful apps on Kubernetes. With volumeClaimTemplates and a headless Service, you get reliable ordering and persistent volumes – all essential for production-grade databases or caches.

sarah antaboga
Author: sarah antaboga

Leave a Reply

Your email address will not be published. Required fields are marked *