Browse topics

PersistentVolumeClaims

Version
1.37
Review
Draft

Summary#

A PersistentVolumeClaim (PVC) requests storage with a size and access mode. Kubernetes binds it to a PersistentVolume, often one provisioned by a StorageClass. The claim outlives the Pods that mount it.

Syntax#

sh
kubectl get storageclass
kubectl get pvc
yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: data
spec:
  accessModes: ["ReadWriteOnce"]
  storageClassName: STORAGE_CLASS
  resources:
    requests:
      storage: 1Gi

Example#

Use a cluster with a default StorageClass that provisions volumes dynamically and has the Delete reclaim policy so cleanup removes the volume. A class using WaitForFirstConsumer binds the claim when Kubernetes schedules a Pod that uses it.

sh
(
  set -eu
  ns="ref-pvc-$$"
  kubectl create namespace "$ns" >/dev/null
  trap 'kubectl delete namespace "$ns" >/dev/null' EXIT
  kubectl wait -n "$ns" --for=create serviceaccount/default --timeout=60s >/dev/null

  run_pod() {
    kubectl apply -n "$ns" -f - >/dev/null <<EOF
apiVersion: v1
kind: Pod
metadata:
  name: $1
spec:
  restartPolicy: Never
  containers:
    - name: task
      image: busybox:1.37
      command: ["sh", "-c", "$2"]
      volumeMounts:
        - name: data
          mountPath: /data
  volumes:
    - name: data
      persistentVolumeClaim:
        claimName: data
EOF
    kubectl wait -n "$ns" --for=jsonpath='{.status.phase}'=Succeeded "pod/$1" --timeout=180s >/dev/null
    kubectl logs -n "$ns" "$1"
  }

  kubectl apply -n "$ns" -f - <<'EOF'
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: data
spec:
  accessModes: ["ReadWriteOnce"]
  resources:
    requests:
      storage: 16Mi
EOF
  run_pod writer 'echo saved by writer > /data/note; echo write complete'
  kubectl delete -n "$ns" pod writer >/dev/null
  run_pod reader 'cat /data/note'
  kubectl get -n "$ns" pvc data -o jsonpath='phase={.status.phase} accessModes={.status.accessModes[*]}{"\n"}'
)

Expected output#

Text
persistentvolumeclaim/data created
write complete
saved by writer
phase=Bound accessModes=ReadWriteOnce

Common mistakes#

ReadWriteOnce means read-write mounting by one node, not by one Pod. Several Pods on that node can use the volume. Request ReadWriteOncePod where the driver supports it and only a single Pod may access the data.

Version applicability#

The example targets Kubernetes 1.37. ReadWriteOncePod is stable since 1.29 and requires a CSI volume. Growing a claim is stable since 1.24 and needs a StorageClass with allowVolumeExpansion: true. Dynamically provisioned volumes inherit the class reclaim policy, Delete by default.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0