Feedback

Chat Icon

Cloud-Native Microservices With Kubernetes - 2nd Edition

A Comprehensive Guide to Building, Scaling, Deploying, Observing, and Managing Highly-Available Microservices in Kubernetes

Understanding and Using StatefulSets and Headless Services
29%

StatefulSet: A Slow but Safe Brain for Databases

A StatefulSet is like a Deployment with additional features that make it suitable for managing stateful applications like databases and message queues. These features make StatefulSets a "conservative" controller for stateful applications and can be summarized in 4 main points:

  • Stable network identity
  • Stable, persistent storage
  • Ordered, graceful deployment and scaling
  • Ordered, automated rolling updates

We will examine each of these features. In the following explanation, some concepts are simplified to focus on the main differences between StatefulSets and Deployments. Our goal is not to provide an in-depth explanation of how distributed databases work, but rather to highlight the key features of StatefulSets and how they fit into the architecture of stateful applications.

Stable Network Identity

Imagine you have a Pod created with a Deployment. If that Pod crashes or is deleted, Kubernetes will create a new Pod to replace it. However, the new Pod will have a different name. Here is a test:

# Create a test deployment
kubectl apply -f - <
apiVersion: apps/v1
kind: Deployment
metadata:
  name: test-deployment
spec:
  replicas: 1
  selector:
    matchLabels:
      app: test
  template:
    metadata:
      labels:
        app: test
    spec:
      containers:
      - name: test-container
        image: nginx
EOF

# Get the name of the Pod
POD_NAME=$(kubectl get pods -l app=test -o jsonpath="{.items[0].metadata.name}")

# Delete the Pod
kubectl delete pod $POD_NAME

# Get the name of the new Pod
NEW_POD_NAME=$(kubectl get pods -l app=test -o jsonpath="{.items[0].metadata.name}")

If you check the values of POD_NAME and NEW_POD_NAME, you will notice that they are different:

# Check if the names are different
if [ "$POD_NAME" != "$NEW_POD_NAME

Cloud-Native Microservices With Kubernetes - 2nd Edition

A Comprehensive Guide to Building, Scaling, Deploying, Observing, and Managing Highly-Available Microservices in Kubernetes

Enroll now to unlock all content and receive all future updates for free.