Bird
Raised Fist0
Kubernetesdevops~7 mins

StatefulSets for stateful applications in Kubernetes - Commands & Configuration

Choose your learning style10 modes available
Introduction
StatefulSets help run applications that need to keep data or identity even if restarted. They make sure each app copy has its own storage and name, so data is safe and consistent.
When running a database that needs to keep its data even if the pod restarts or moves.
When deploying a messaging system like Kafka that requires stable network IDs.
When you want to run multiple copies of an app but each needs its own storage.
When you need to upgrade apps one by one without losing data or connections.
When you want to keep the order of app startup and shutdown for proper coordination.
Config File - statefulset.yaml
statefulset.yaml
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: example-statefulset
  namespace: default
spec:
  serviceName: "example-service"
  replicas: 3
  selector:
    matchLabels:
      app: example-app
  template:
    metadata:
      labels:
        app: example-app
    spec:
      containers:
      - name: example-container
        image: nginx:1.23.3
        ports:
        - containerPort: 80
          name: web
        volumeMounts:
        - name: data
          mountPath: /usr/share/nginx/html
  volumeClaimTemplates:
  - metadata:
      name: data
    spec:
      accessModes: ["ReadWriteOnce"]
      resources:
        requests:
          storage: 1Gi

serviceName: Links pods to a headless service for stable network IDs.

replicas: Number of pod copies to run.

selector: Matches pods managed by this StatefulSet.

template: Defines pod content like containers and labels.

volumeClaimTemplates: Creates persistent storage for each pod copy.

Commands
This command creates the StatefulSet and its pods with persistent storage as defined in the YAML file.
Terminal
kubectl apply -f statefulset.yaml
Expected OutputExpected
statefulset.apps/example-statefulset created
This command lists all pods created by the StatefulSet to verify they are running.
Terminal
kubectl get pods -l app=example-app
Expected OutputExpected
NAME READY STATUS RESTARTS AGE example-statefulset-0 1/1 Running 0 30s example-statefulset-1 1/1 Running 0 25s example-statefulset-2 1/1 Running 0 20s
→
-l app=example-app - Filters pods by label to show only those managed by the StatefulSet
This command shows detailed information about the first pod, including its storage and network identity.
Terminal
kubectl describe pod example-statefulset-0
Expected OutputExpected
Name: example-statefulset-0 Namespace: default Priority: 0 Node: node-1/192.168.1.10 Start Time: Thu, 01 Jun 2024 10:00:00 +0000 Labels: app=example-app Annotations: <none> Status: Running IP: 10.244.1.10 Containers: example-container: Image: nginx:1.23.3 Port: 80/TCP Mounts: /usr/share/nginx/html from data (rw) Volumes: data: Type: PersistentVolumeClaim (a reference to a PVC in the same namespace) ClaimName: data-example-statefulset-0 ReadOnly: false
Key Concept

StatefulSets give each pod a stable name and storage so stateful apps keep their data and identity across restarts.

Common Mistakes
Using a Deployment instead of a StatefulSet for stateful apps
Deployments do not provide stable network IDs or persistent storage per pod, causing data loss or conflicts.
Use StatefulSet to ensure each pod has its own persistent volume and stable identity.
Not creating a headless service matching the StatefulSet's serviceName
Without the headless service, pods won't get stable network identities needed for stateful communication.
Create a headless service with the same name as serviceName in the StatefulSet spec.
Sharing a single PersistentVolumeClaim among all pods
All pods would write to the same storage, causing data corruption and conflicts.
Use volumeClaimTemplates to create separate PersistentVolumeClaims for each pod.
Summary
Create a StatefulSet YAML with volumeClaimTemplates for persistent storage per pod.
Apply the StatefulSet with kubectl apply and verify pods with kubectl get pods.
Use kubectl describe pod to check each pod's storage and network identity.

Practice

(1/5)
1. What is the main purpose of a StatefulSet in Kubernetes?
easy
A. To scale stateless applications quickly without persistent storage
B. To provide load balancing for stateless services
C. To manage stateful applications with stable network IDs and persistent storage
D. To automatically update container images in deployments

Solution

  1. Step 1: Understand StatefulSet role

    StatefulSets manage pods that need stable identities and persistent storage, unlike Deployments for stateless apps.
  2. Step 2: Compare options

    Only To manage stateful applications with stable network IDs and persistent storage describes stable network IDs and persistent storage, key features of StatefulSets.
  3. Final Answer:

    To manage stateful applications with stable network IDs and persistent storage -> Option C
  4. Quick Check:

    StatefulSet = stable IDs + storage [OK]
Hint: StatefulSets = stable pod names + persistent storage [OK]
Common Mistakes:
  • Confusing StatefulSet with Deployment
  • Thinking StatefulSet is for stateless apps
  • Ignoring persistent storage role
2. Which of the following is the correct way to specify a volumeClaimTemplates section in a StatefulSet YAML?
easy
A. volumeClaimTemplates: - metadata: name: data spec: accessModes: ["ReadWriteOnce"] resources: requests: storage: 1Gi
B. volumeClaimTemplates: name: data spec: accessModes: ["ReadWriteMany"] resources: requests: storage: 1Gi
C. volumeClaimTemplates: - name: data spec: accessModes: ["ReadWriteOnce"] resources: limits: storage: 1Gi
D. volumeClaimTemplates: - metadata: name: data spec: accessModes: ["ReadOnlyMany"] resources: requests: storage: 1Gi

Solution

  1. Step 1: Check YAML structure for volumeClaimTemplates

    volumeClaimTemplates must be a list with items having metadata and spec sections.
  2. Step 2: Validate accessModes and resource requests

    Access mode "ReadWriteOnce" is typical for StatefulSet volumes; requests use storage size under resources.
  3. Final Answer:

    volumeClaimTemplates with metadata name, spec accessModes ReadWriteOnce, and storage requests -> Option A
  4. Quick Check:

    volumeClaimTemplates list with metadata + spec = A [OK]
Hint: volumeClaimTemplates is a list with metadata and spec [OK]
Common Mistakes:
  • Missing metadata block under volumeClaimTemplates
  • Using accessModes not supported for StatefulSets
  • Incorrect indentation or YAML structure
3. Given this StatefulSet pod name pattern: web-0, web-1, web-2, what will be the hostname of the pod web-1 inside the cluster?
medium
A. web-1
B. web-1.default.svc.cluster.local
C. web-1..default.svc.cluster.local
D. web-1..default.svc.cluster.local

Solution

  1. Step 1: Understand StatefulSet DNS naming

    Each pod gets a stable hostname: <podname>. within the namespace.
  2. Step 2: Identify full DNS format

    Full DNS is <podname>..<namespace>.svc.cluster.local, so pod web-1's hostname includes the service name.
  3. Final Answer:

    web-1.<service-name>.default.svc.cluster.local -> Option D
  4. Quick Check:

    Pod hostname = podname.service.namespace.svc.cluster.local [OK]
Hint: Pod hostname includes service name, not StatefulSet name [OK]
Common Mistakes:
  • Using StatefulSet name instead of service name in hostname
  • Ignoring full DNS suffix
  • Assuming hostname is just pod name
4. You created a StatefulSet but notice pods are stuck in Pending state. Which of these is the most likely cause?
medium
A. The volumeClaimTemplates request more storage than available in the cluster
B. The StatefulSet spec is missing the container image field
C. The StatefulSet replicas count is set to zero
D. The pod labels do not match the StatefulSet selector

Solution

  1. Step 1: Analyze Pending pod reason

    Pods stuck in Pending often mean resources like storage or compute are unavailable.
  2. Step 2: Check volumeClaimTemplates impact

    If requested storage exceeds cluster capacity, PersistentVolumeClaims remain unbound, blocking pod start.
  3. Final Answer:

    VolumeClaimTemplates request more storage than cluster can provide -> Option A
  4. Quick Check:

    Pending pods often mean storage or resource shortage [OK]
Hint: Pending pods often mean storage or resource shortage [OK]
Common Mistakes:
  • Assuming missing image causes Pending (it causes CrashLoopBackOff)
  • Thinking zero replicas create Pending pods (no pods created)
  • Ignoring label-selector mismatch effects
5. You want to update the container image of a StatefulSet without downtime, ensuring pods restart one by one in order. Which update strategy should you use?
hard
A. RollingUpdate with partition set to the last pod index
B. RollingUpdate with partition set to 0
C. OnDelete update strategy
D. Recreate update strategy

Solution

  1. Step 1: Understand StatefulSet update strategies

    RollingUpdate updates pods in order, respecting pod ordinal index; partition controls which pods update.
  2. Step 2: Use partition to control update order

    Setting partition to 0 (default) updates all pods sequentially from the highest ordinal index down to 0, one by one without downtime.
  3. Final Answer:

    RollingUpdate with partition set to 0 -> Option B
  4. Quick Check:

    Partition controls pod update order in RollingUpdate [OK]
Hint: Use RollingUpdate with partition to update pods one by one [OK]
Common Mistakes:
  • Using OnDelete causes manual pod restarts, not automatic
  • Recreate deletes all pods causing downtime
  • RollingUpdate with partition set to the last pod index only updates higher ordinal pods
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard