Overview of StatefulSets

StatefulSets are Kubernetes resources that manage stateful applications. Unlike Deployments, which are ideal for stateless applications, StatefulSets provide guarantees about the ordering and uniqueness of pods. They are useful for databases, cache systems, and other applications that require persistent state.

Differences between Deployments and StatefulSets

  • Ordering: StatefulSets start one pod at a time in a specific order, whereas Deployments can start multiple replicas simultaneously.

  • Stable Network ID: Pods in a StatefulSet have a stable hostname like web-0, web-1, whereas Deployment pods have hash-based IDs.

  • Persistent Storage: StatefulSets make it easier to work with persistent storage, which can be attached to specific pods.

  • Updates: StatefulSets allow updates to be rolled out in a particular order, ensuring data consistency.

Creating and Managing StatefulSets

To create a StatefulSet, you define a YAML file.

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: web
spec:
  serviceName: "web-service"
  replicas: 3
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx

To apply it:

kubectl apply -f statefulset.yaml

To list all StatefulSets:

kubectl get statefulsets

Scaling and Updating StatefulSets

To scale a StatefulSet:

kubectl scale statefulset web --replicas=4

To update:

  1. Update your YAML file.
  2. Apply the change:
kubectl apply -f updated-statefulset.yaml

Persistent Storage and StatefulSets

StatefulSets can use Persistent Volumes to store data. The volumeClaimTemplates allows each pod to have its own persistent volume.

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: web
spec:
  serviceName: "web-service"
  replicas: 3
  volumeClaimTemplates:
  - metadata:
      name: data
    spec:
      accessModes: [ "ReadWriteOnce" ]
      resources:
        requests:
          storage: 1Gi

Complete Exercise

Setup

  1. Create a YAML file named exercise-statefulset.yaml with above StatefulSet configurations.

Steps

  1. Apply the StatefulSet: kubectl apply -f exercise-statefulset.yaml
  2. Scale it to 4 replicas: kubectl scale statefulset web --replicas=4
  3. List StatefulSets: kubectl get statefulsets

Troubleshooting

  • Use kubectl describe statefulset <name> to debug.
  • Check the logs: kubectl logs <pod-name>

Solution

  1. If you followed all steps, you should have a StatefulSet running with 4 replicas.
  2. Each should have its own Persistent Volume.