Kubernetes cookbook · Advanced
Run a stateful service with stable identities
Pods of a clustered system need stable names and their own storage.
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
volumeClaimTemplatesisn't allowed in place.
Variations
- Use an operator (CloudNativePG, Strimzi) for databases and Kafka instead of raw StatefulSets.
persistentVolumeClaimRetentionPolicyto control PVC deletion.
Further reading: StatefulSets
Reference: https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/
More Kubernetes recipes
- Autoscale a Deployment on CPU and memory
- Debug a distroless pod with an ephemeral container
- Default-deny network policies that keep DNS working
- Enforce the restricted Pod Security Standard
- Expose a service over HTTPS with automatic certificates
- Give a CI pipeline least-privilege deploy access
- Handle SIGTERM in your application for Kubernetes
- Manage dev, staging and prod with Kustomize overlays