StatefulSet project

Published: (January 18, 2026 at 04:05 PM EST)
2 min read
Source: Dev.to

Source: Dev.to

Prerequisites

A StatefulSet requires the following components:

  • Headless Service – provides stable DNS for each pod.
  • StatefulSet manifest – defines the pods and their identity.
  • PersistentVolume / StorageClass – usually already exists in the cluster.

Without these, a StatefulSet will not function correctly.

Headless Service

apiVersion: v1
kind: Service
metadata:
  name: mysql-headless
spec:
  clusterIP: None        # <- makes the service headless
  selector:
    app: mysql
  ports:
    - port: 3306

Apply the service:

kubectl apply -f service.yaml

Why this matters

  • No load balancing; each pod gets its own DNS entry.
  • Required for databases and clustering scenarios.

StatefulSet Manifest

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: mysql
spec:
  serviceName: mysql-headless   # MUST match the headless service name
  replicas: 3
  selector:
    matchLabels:
      app: mysql
  template:
    metadata:
      labels:
        app: mysql
    spec:
      containers:
        - name: mysql
          image: mysql:8.0
          ports:
            - containerPort: 3306
          env:
            - name: MYSQL_ROOT_PASSWORD
              value: root
          volumeMounts:
            - name: data
              mountPath: /var/lib/mysql
  volumeClaimTemplates:
    - metadata:
        name: data
      spec:
        accessModes: ["ReadWriteOnce"]
        resources:
          requests:
            storage: 5Gi

Apply the StatefulSet:

kubectl apply -f statefulset.yaml

Verifying the Deployment

List the pods:

kubectl get pods

You should see:

mysql-0
mysql-1
mysql-2

List the PersistentVolumeClaims:

kubectl get pvc

You should see:

data-mysql-0
data-mysql-1
data-mysql-2

Access a Pod

kubectl exec -it mysql-0 -- bash

Inside the pod you can test DNS resolution:

ping mysql-1.mysql-headless
ping mysql-2.mysql-headless

Each pod has its own stable hostname.

Scaling the StatefulSet

kubectl scale statefulset mysql --replicas=4

What happens

  • A new pod mysql-3 is created after mysql-2.
  • A new PVC data-mysql-3 is provisioned.
  • No data loss; the pod retains its stable name, DNS, and storage.
  • Pods start and stop in order, which is essential for many stateful applications.

Use Cases

StatefulSets are ideal for workloads that need stable identities and persistent storage, such as:

  • MySQL / PostgreSQL
  • MongoDB
  • Kafka
  • ZooKeeper
  • Elasticsearch

A StatefulSet creates pods with stable identity, DNS, and persistent storage, which are required for stateful workloads like databases.

Back to Blog

Related posts

Read more »