Cloud Native › Kubernetes

Kubernetes PV, PVC, StorageClass, and StatefulSet storage

Verify WaitForFirstConsumer PVC binding, ReadWriteOnce scheduling and attach conflicts, and StatefulSet per-Pod PVCs on a three-node kind cluster.

Kubernetes PV, PVC, StorageClass, and StatefulSet storage

Mounting a single ReadWriteOnce PVC across a multi-replica Deployment blocks pods on other nodes from starting. On a three-node kind cluster, I verified WaitForFirstConsumer delayed binding, ReadWriteOnce scheduling failures, and StatefulSet per-Pod PVCs with stable DNS, then mapped out when to pick each storage model.

Every kubectl command and output below ran on a local three-node kind v0.33.0 cluster (Kubernetes v1.37.0, kubectl v1.36.1, nodes k8s-lab-control-plane, k8s-lab-worker, and k8s-lab-worker2, arm64, containerd://2.3.4) with busybox:1.36. The CSI Multi-Attach error comparison for cloud block volumes such as AWS EBS or GCP Persistent Disk follows official Kubernetes storage architecture rather than live cloud provisioning.

How PV, PVC, and StorageClass separate storage concerns

On a single host, mounting a host directory or named volume—as covered in Docker volumes vs. bind mounts and permissions—is enough. Across multiple cluster nodes, you don’t know where a Pod will land until the scheduler places it. As I verified in Stateful services in Docker Swarm with placement constraints, moving a stateful container without storage-aware scheduling leaves it with an empty local volume on the new node.

Kubernetes splits storage into three objects so workloads stay decoupled from the backing infrastructure:

  • PersistentVolume (PV): An actual storage piece provisioned in the cluster (local disk, AWS EBS, NFS, etc.).
  • PersistentVolumeClaim (PVC): A workload’s request for capacity and an access mode such as ReadWriteOnce.
  • StorageClass: A template defining the provisioner, reclaimPolicy, and volumeBindingMode used to create a PV dynamically when a PVC appears.

I inspected the default standard StorageClass in kind and created a standalone 100Mi ReadWriteOnce PVC.

1
2
3
4
5
6
7
8
9
10
11
12
13
# shared-rwo-pvc.yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: shared-rwo-pvc
  namespace: lab-d4-storage
spec:
  accessModes:
    - ReadWriteOnce
  storageClassName: standard
  resources:
    requests:
      storage: 100Mi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
$ kubectl get storageclass standard \
  -o custom-columns=NAME:.metadata.name,PROVISIONER:.provisioner,RECLAIM:.reclaimPolicy,BINDING:.volumeBindingMode
NAME       PROVISIONER             RECLAIM   BINDING
standard   rancher.io/local-path   Delete    WaitForFirstConsumer

$ kubectl get pvc -n lab-d4-storage
NAME             STATUS    VOLUME   CAPACITY   ACCESS MODES   STORAGECLASS   AGE
shared-rwo-pvc   Pending                                      standard       3s

$ kubectl describe pvc shared-rwo-pvc -n lab-d4-storage
Events:
  Type    Reason                Age              From                         Message
  ----    ------                ----             ----                         -------
  Normal  WaitForFirstConsumer  0s (x2 over 3s)  persistentvolume-controller  waiting for first consumer to be created before binding

The PVC stays Pending instead of binding right away because volumeBindingMode is WaitForFirstConsumer. With Immediate, Kubernetes provisions the PV before any Pod exists, which can place the volume in a node or availability zone where the Pod cannot run due to CPU limits or affinity rules. Delaying provisioning until the first consumer Pod is scheduled prevents that topology mismatch.

What breaks when multiple Pods share one ReadWriteOnce PVC

Next, I attached shared-rwo-pvc to a two-replica Deployment and added podAntiAffinity on kubernetes.io/hostname to force the two replicas onto separate worker nodes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# rwo-deploy.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: rwo-deploy
  namespace: lab-d4-storage
spec:
  replicas: 2
  selector:
    matchLabels:
      app: rwo-deploy
  template:
    metadata:
      labels:
        app: rwo-deploy
    spec:
      affinity:
        podAntiAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            - labelSelector:
                matchLabels:
                  app: rwo-deploy
              topologyKey: kubernetes.io/hostname
      containers:
        - name: app
          image: busybox:1.36
          command: ["sh", "-c", "echo \"started on $(hostname)\" >> /data/boot.log; sleep 3600"]
          volumeMounts:
            - name: shared-vol
              mountPath: /data
      volumes:
        - name: shared-vol
          persistentVolumeClaim:
            claimName: shared-rwo-pvc

Here is what happened to the PVC, the generated PV’s nodeAffinity, and the two Pods:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
$ kubectl get pvc -n lab-d4-storage
NAME             STATUS   VOLUME                                     CAPACITY   ACCESS MODES   STORAGECLASS   AGE
shared-rwo-pvc   Bound    pvc-7d238d37-756d-4244-9205-feee56a94f71   100Mi      RWO            standard       16s

# Excerpt from the dynamically provisioned PV
spec:
  accessModes:
  - ReadWriteOnce
  hostPath:
    path: /var/local-path-provisioner/pvc-7d238d37-756d-4244-9205-feee56a94f71_lab-d4-storage_shared-rwo-pvc
    type: DirectoryOrCreate
  nodeAffinity:
    required:
      nodeSelectorTerms:
      - matchExpressions:
        - key: kubernetes.io/hostname
          operator: In
          values:
          - k8s-lab-worker

$ kubectl get pods -n lab-d4-storage -l app=rwo-deploy -o wide
NAME                         READY   STATUS    RESTARTS   AGE   IP           NODE
rwo-deploy-b964fd646-f6zqc   1/1     Running   0          13s   10.244.2.9   k8s-lab-worker
rwo-deploy-b964fd646-s5xjq   0/1     Pending   0          13s   <none>       <none>

$ kubectl describe pod rwo-deploy-b964fd646-s5xjq -n lab-d4-storage
Events:
  Type     Reason            Age                From               Message
  ----     ------            ----               ----               -------
  Warning  FailedScheduling  11s (x3 over 11s)  default-scheduler  0/3 nodes are available: 1 node(s) didn't match PersistentVolume's node affinity, 1 node(s) didn't match pod anti-affinity rules, 1 node(s) had untolerated taint(s).

When the first Pod (rwo-deploy-b964fd646-f6zqc) landed on k8s-lab-worker, rancher.io/local-path created a hostPath PV and pinned its nodeAffinity to k8s-lab-worker. That left zero valid nodes for the second Pod (rwo-deploy-b964fd646-s5xjq): the control plane had an untolerated taint, k8s-lab-worker violated podAntiAffinity, and k8s-lab-worker2 failed the PV’s nodeAffinity.

Notice the difference in when the failure happens depending on the storage driver:

  • Local provisioners (rancher.io/local-path): The PV is pinned to one node via nodeAffinity, so the second Pod stalls in Pending during scheduling (FailedScheduling).
  • Cloud network block storage (AWS EBS, GCP Persistent Disk CSI): The PV is scoped to an availability zone rather than a single node, so the scheduler can place the second Pod on another node in the same zone. The failure then hits later during volume attachment (AttachDetachController), leaving the Pod stuck in ContainerCreating with FailedAttachVolume: Multi-Attach error for volume.

Also keep in mind that ReadWriteOnce restricts read/write mounts to a single node, not a single Pod. Without podAntiAffinity, two replicas can land on the same node and write to the same RWO volume simultaneously, corrupting uncoordinated files. If you need strict single-Pod access, use ReadWriteOncePod.

Giving each Pod its own PVC and DNS with StatefulSet

Stateful replicas shouldn’t fight over one shared PVC. Each replica needs its own volume and a stable network identity.

flowchart TD
    D["Deployment (2 replicas)"] --> D0["Pod A (mounted)"]
    D --> D1["Pod B (blocked)"]
    D0 --> P0["Shared RWO PVC"]
    D1 -.->|"Node affinity / Multi-Attach"| P0

    S["StatefulSet (2 replicas)"] --> S0["stateful-app-0"]
    S --> S1["stateful-app-1"]
    S0 --> PV0["data-stateful-app-0"]
    S1 --> PV1["data-stateful-app-1"]

To verify this, I paired a Headless Service (clusterIP: None) with a two-replica StatefulSet using volumeClaimTemplates.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# statefulset.yaml
apiVersion: v1
kind: Service
metadata:
  name: db-headless
  namespace: lab-d4-storage
spec:
  clusterIP: None
  selector:
    app: stateful-app
  ports:
    - name: web
      port: 80
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: stateful-app
  namespace: lab-d4-storage
spec:
  serviceName: db-headless
  replicas: 2
  selector:
    matchLabels:
      app: stateful-app
  template:
    metadata:
      labels:
        app: stateful-app
    spec:
      containers:
        - name: app
          image: busybox:1.36
          command: ["sh", "-c", "sleep 3600"]
          volumeMounts:
            - name: data
              mountPath: /data
  volumeClaimTemplates:
    - metadata:
        name: data
      spec:
        accessModes:
          - ReadWriteOnce
        storageClassName: standard
        resources:
          requests:
            storage: 100Mi

Checking the resulting Pods, PVCs, Headless Service, and CoreDNS records shows clean isolation across both workers:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
$ kubectl get pods,pvc,svc -n lab-d4-storage -o wide
NAME                 READY   STATUS    RESTARTS   AGE   IP            NODE
pod/stateful-app-0   1/1     Running   0          11s   10.244.1.10   k8s-lab-worker2
pod/stateful-app-1   1/1     Running   0          3s    10.244.2.13   k8s-lab-worker

NAME                                        STATUS   VOLUME                                     CAPACITY   ACCESS MODES   STORAGECLASS
persistentvolumeclaim/data-stateful-app-0   Bound    pvc-6b3f882a-0fee-42da-b07f-df8aa7ece59e   100Mi      RWO            standard
persistentvolumeclaim/data-stateful-app-1   Bound    pvc-578a79dc-cd86-4b4f-868e-067fb126b438   100Mi      RWO            standard

NAME                  TYPE        CLUSTER-IP   PORT(S)
service/db-headless   ClusterIP   None         80/TCP

$ kubectl exec -n lab-d4-storage stateful-app-0 -- nslookup stateful-app-0.db-headless.lab-d4-storage.svc.cluster.local
Server:   10.96.0.10
Address:  10.96.0.10:53
Name:     stateful-app-0.db-headless.lab-d4-storage.svc.cluster.local
Address:  10.244.1.10

$ kubectl exec -n lab-d4-storage stateful-app-0 -- nslookup stateful-app-1.db-headless.lab-d4-storage.svc.cluster.local
Name:     stateful-app-1.db-headless.lab-d4-storage.svc.cluster.local
Address:  10.244.2.13

Each ordinal Pod received its own <template>-<pod> PVC (data-stateful-app-0 and data-stateful-app-1), and CoreDNS resolved each peer’s stable FQDN (<pod>.<service>.<namespace>.svc.cluster.local) directly to its Pod IP.

To confirm persistence across Pod replacement, I wrote a record to /data/record.txt inside stateful-app-0, deleted the Pod, and read the file again after recreation.

1
2
3
4
5
6
7
8
9
10
# Write data, delete stateful-app-0, and verify after recreation
BEFORE DELETE:  name=stateful-app-0 uid=df40579f-c820-4e9c-99d5-fd59b919d53d ip=10.244.1.10 node=k8s-lab-worker2

$ kubectl delete pod stateful-app-0 -n lab-d4-storage
pod "stateful-app-0" deleted from lab-d4-storage namespace

AFTER RECREATE: name=stateful-app-0 uid=4240e2ff-ce83-4460-bb60-08d24993f816 ip=10.244.1.14 node=k8s-lab-worker2

$ kubectl exec -n lab-d4-storage stateful-app-0 -- cat /data/record.txt
stateful-record-from-pod-0

The replacement stateful-app-0 got a new UID (df40579f... -> 4240e2ff...) and a new IP (10.244.1.10 -> 10.244.1.14), but reattached the exact same data-stateful-app-0 PVC on k8s-lab-worker2 with /data/record.txt intact.

Comparing AccessModes and choosing a storage architecture

Start by matching the volume accessModes to how many nodes or Pods need concurrent writes.

AccessModeShortConcurrent mount scopeTypical backendsBest fit and limits
ReadWriteOnceRWOSingle node read/write (multiple Pods on the same node can share it)AWS EBS, GCP PD, local-pathSingle-replica apps, per-Pod StatefulSet disks
ReadWriteOncePodRWOPSingle Pod read/write cluster-wideSupported CSI drivers (Kubernetes 1.29 GA)Blocks same-node multi-Pod write corruption
ReadWriteManyRWXMultiple nodes read/writeNFS, AWS EFS, CephFS, Azure FilesShared uploads or build artifacts (poor fit for database files)
ReadOnlyManyROXMultiple nodes read-onlyNFS, snapshot-backed read volumesShared ML weights, static lookup dictionaries

Next, decide whether the stateful workload belongs in a Deployment, a StatefulSet, or a managed service outside the cluster.

FactorDeployment + PVCStatefulSet + volumeClaimTemplatesManaged external DB (RDS, Cloud SQL)
Pod identity & DNSRandom hash names, no per-Pod DNSOrdered names (-0, -1), stable Headless DNSFixed external endpoint
Storage topologyAll replicas share one PVC1:1 dedicated PVC per PodManaged block storage and snapshots
Scaling with RWOBreaks across nodes (scheduling or attach error)Auto-provisions a new PVC per replicaBuilt-in read replicas and storage scaling
Backup & failoverManualRequires an Operator (e.g., CloudNativePG) or custom automationAutomated backups, PITR, Multi-AZ failover
Best fitSingle-replica tools, RWX shared file appsReplicated systems (Kafka, Redis Cluster, Zookeeper, Operator-managed DBs)Most production OLTP relational databases

When not to run a StatefulSet: skip self-hosting primary relational databases (PostgreSQL, MySQL) in a StatefulSet if your team doesn’t have the bandwidth to maintain automated backups, point-in-time recovery (PITR), major upgrades, and split-brain recovery. A StatefulSet only guarantees stable storage and DNS—it does not configure replication or promote a primary after a failure. Likewise, if stateless web Pods need shared file uploads, push them to object storage (S3 or GCS) instead of introducing an RWX network filesystem just to keep a Deployment stateless.

Production pitfalls and checklist

Three failure modes show up repeatedly once stateful workloads hit production:

Pitfall 1 — reclaimPolicy: Delete vs. retained StatefulSet PVCs: When a StorageClass uses reclaimPolicy: Delete, deleting a PVC wipes the backing PV and disk immediately. Conversely, StatefulSet intentionally leaves generated PVCs behind when you scale down or delete the StatefulSet. Use Retain for production data StorageClass definitions, and configure persistentVolumeClaimRetentionPolicy on ephemeral caches so orphaned disks don’t pile up.

Pitfall 2 — Deployment RollingUpdate deadlocks on RWO volumes: Even with replicas: 1, a Deployment defaults to RollingUpdate (maxSurge: 25%), which tries to start the replacement Pod before terminating the old one. If the new Pod lands on another node, it collides with the RWO volume still attached to the old Pod and stalls the rollout. For single-replica Deployment workloads backed by RWO storage, set strategy.type: Recreate and accept the brief restart gap.

Finally, local PVs (local-path or bare-metal NVMe) tie your data to one physical host. If that node fails permanently, the disk goes with it—only use local PVs when the application layer replicates data across nodes (Kafka, Cassandra, or Raft-based stores).

Before deploying stateful workloads to a cluster, run through these checks:

  • Confirm your StorageClass uses volumeBindingMode: WaitForFirstConsumer to avoid node or AZ scheduling mismatches.
  • Set reclaimPolicy: Retain on production data StorageClass resources and verify an off-cluster backup path.
  • Audit every Deployment referencing a ReadWriteOnce PVC—either switch to strategy.type: Recreate (for replicas: 1) or move to a StatefulSet.
  • Decide upfront whether your team will operate a database Operator in-cluster or offload persistence to a managed database and object storage.

References

This document describes persistent volumes in Kubernetes. Familiarity with volumes, StorageClasses and VolumeAttributesClasses is suggested. IntroductionManaging storage is a distinct problem from managing compute instances. The PersistentVolume subsystem provides an API for users and administrators that abstracts details of how storage is provided from how it is consumed. To do this, we introduce two new API resources: PersistentVolume and PersistentVolumeClaim. A PersistentVolume (PV) is a piece of storage in the cluster that has been provisioned by an administrator or dynamically provisioned using Storage Classes. It is a resource in the cluster just like a node is a cluster resource. PVs are volume plugins like Volumes, but have a lifecycle independent of any individual Pod that uses the PV. This API object captures the details of the implementation of the storage, be that NFS, iSCSI, or a cloud-provider-specific storage system.
This document describes the concept of a StorageClass in Kubernetes. Familiarity with volumes and persistent volumes is suggested. A StorageClass provides a way for administrators to describe the classes of storage they offer. Different classes might map to quality-of-service levels, or to backup policies, or to arbitrary policies determined by the cluster administrators. Kubernetes itself is unopinionated about what classes represent. The Kubernetes concept of a storage class is similar to “profiles” in some other storage system designs.
A StatefulSet runs a group of Pods, and maintains a sticky identity for each of those Pods. This is useful for managing applications that need persistent storage or a stable, unique network identity.
This post is licensed under CC BY 4.0 by the author.