Try Sailor Cloud - 25% off!

Claim Now
Back to all posts

Kubernetes StatefulSets: Managing Stateful Applications

Kubernetes StatefulSets: Managing Stateful Applications

StatefulSets are designed for applications that need stable identities and persistent storage.

StatefulSet vs Deployment

FeatureDeploymentStatefulSet
Pod namesRandom suffixOrdered (app-0, app-1)
ScalingParallelSequential
StorageSharedPer-pod PVC
DeletionAny orderReverse order
NetworkVia ServiceStable DNS

When to Use StatefulSets

  • Databases (MySQL, PostgreSQL, MongoDB)
  • Distributed systems (Kafka, Elasticsearch, ZooKeeper)
  • Applications needing stable network identity
  • Applications needing persistent per-pod storage

StatefulSet Components

1. Headless Service

apiVersion: v1
kind: Service
metadata:
  name: mysql
spec:
  clusterIP: None  # Headless
  selector:
    app: mysql
  ports:
  - port: 3306

2. StatefulSet

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

Stable Network Identity

Pods get predictable DNS names:

mysql-0.mysql.default.svc.cluster.local
mysql-1.mysql.default.svc.cluster.local
mysql-2.mysql.default.svc.cluster.local

Ordered Operations

Scaling Up

mysql-0 → mysql-1 → mysql-2

Scaling Down

mysql-2 → mysql-1 → mysql-0

Pod Management Policies

spec:
  podManagementPolicy: OrderedReady  # Default
  # or
  podManagementPolicy: Parallel

Update Strategies

spec:
  updateStrategy:
    type: RollingUpdate  # Default
    rollingUpdate:
      partition: 2  # Only update pods >= 2

Volume Claim Templates

Each pod gets its own PVC:

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

PVCs persist after pod deletion, ensuring data survives rescheduling.

Common Commands

# Get StatefulSet
kubectl get statefulset

# Scale StatefulSet
kubectl scale statefulset mysql --replicas=5

# Delete without deleting PVCs
kubectl delete statefulset mysql --cascade=orphan

Practice StatefulSets

StatefulSets appear in CKA and CKAD exams. Practice at Sailor.sh.

Start Free Practice