Kubernetes cookbook · Advanced

Run a stateful service with stable identities

Pods of a clustered system need stable names and their own storage.

Create a free account to save this page, take notes and track your progress. Sign in

Approach

Use a StatefulSet with a headless Service for stable DNS names and volumeClaimTemplates for per-pod volumes. Combine with a PDB and spread across zones.

Solution

apiVersion: v1
kind: Service
metadata: {name: kv}
spec:
  clusterIP: None
  selector: {app: kv}
  ports: [{name: client, port: 6379}]
---
apiVersion: apps/v1
kind: StatefulSet
metadata: {name: kv}
spec:
  serviceName: kv
  replicas: 3
  selector: {matchLabels: {app: kv}}
  template:
    metadata: {labels: {app: kv}}
    spec:
      containers:
        - name: kv
          image: redis:8-alpine
          ports: [{name: client, containerPort: 6379}]
          volumeMounts: [{name: data, mountPath: /data}]
  volumeClaimTemplates:
    - metadata: {name: data}
      spec:
        accessModes: [ReadWriteOnce]
        resources: {requests: {storage: 10Gi}}

Pitfalls

  • Deleting a StatefulSet doesn't delete its PVCs; plan cleanup and retention.
  • Changing volumeClaimTemplates isn't allowed in place.

Variations

  • Use an operator (CloudNativePG, Strimzi) for databases and Kafka instead of raw StatefulSets.
  • persistentVolumeClaimRetentionPolicy to control PVC deletion.

Further reading: StatefulSets

Reference: https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/

More Kubernetes recipes

Was this page helpful?