Course contentsShow
← Docker, Kubernetes & CI/CD
Lesson 339 of 8025. Advanced Kubernetes ConfigurationFree lesson

Provisioning Persistent Volume Claims for StatefulSets

Define VolumeClaimTemplates to automatically provision unique storage volumes for every replica generated by a StatefulSet controller.

In this lesson, you will learn how to use volumeClaimTemplates to automatically provision unique, persistent storage for each replica in a StatefulSet.

The Challenge of State

When you run a standard Deployment, every replica is ephemeral and interchangeable; if a pod dies, the new one doesn't care about the old one's data. However, in a StatefulSet, every pod has a unique identity (like myapp-0, myapp-1). If myapp-0 crashes, it must re-attach to its specific disk when it restarts.

Manually creating a unique PersistentVolumeClaim (PVC) for every single pod replica would be tedious and error-prone. Kubernetes solves this with volumeClaimTemplates.

How VolumeClaimTemplates Work

Instead of defining a PVC manually, you define a volumeClaimTemplate inside your StatefulSet manifest. Think of this as a "cookie cutter" for storage. Every time the StatefulSet controller spins up a new pod index, it automatically triggers the creation of a PVC tailored specifically for that pod.

spec:
  volumeClaimTemplates:
  - metadata:
      name: my-storage
    spec:
      accessModes: [ "ReadWriteOnce" ]
      storageClassName: "standard"
      resources:
        requests:
          storage: 10Gi

When you deploy this, Kubernetes will generate individual PVCs named following the pattern [template-name]-[pod-name] (e.g., my-storage-myapp-0 and my-storage-myapp-1).

Why This Matters

  1. Automated Provisioning: You don't need to manually create 10 different PVCs for 10 replicas.
  2. Sticky Identity: Because the PVC name is tied to the pod index, if myapp-0 is rescheduled, the controller ensures it reconnects to my-storage-myapp-0, preserving your database or application state seamlessly.
  3. Dynamic Scaling: If you scale your StatefulSet from 3 to 5 replicas, the controller automatically provisions two new, unique PVCs for the new pods, ensuring they are ready to store data immediately.

Key Takeaway: The volumeClaimTemplates field acts as an automated factory that ensures every StatefulSet replica is paired with its own exclusive, persistent storage volume upon creation.