Kubernetes Tutorial · Configuration and Resources · Lesson 21 of 26

Persistent Volumes and Claims

Request durable storage with PersistentVolumeClaims and let StorageClasses provision it.

Create a free account to save this page, take notes and track your progress. Sign in

The pieces

  • A PersistentVolumeClaim (PVC) is a pod's request: size, access mode, storage class.
  • A StorageClass describes how to create volumes (cloud disks, network file systems, local disks).
  • A PersistentVolume (PV) is the actual storage, usually created dynamically for a claim.

Access modes: ReadWriteOnce (one node at a time, typical block disks), ReadWriteMany (many nodes, file storage), ReadWriteOncePod. The reclaim policy decides whether the volume is deleted with the claim; use Retain for data you can't lose, and back it up regardless.

Data outlives the pod that wrote it
kubectl create namespace demo-storage > /dev/null
trap 'kubectl delete namespace demo-storage --wait=false > /dev/null' EXIT
cat > storage.yaml <<'EOF'
apiVersion: v1
kind: PersistentVolumeClaim
metadata: {name: data}
spec:
  accessModes: [ReadWriteOnce]
  resources: {requests: {storage: 100Mi}}
---
apiVersion: v1
kind: Pod
metadata: {name: writer}
spec:
  restartPolicy: Never
  containers:
    - name: writer
      image: busybox:1.37
      command: ["sh", "-c", "echo 'saved at first run' > /data/state.txt"]
      volumeMounts: [{name: data, mountPath: /data}]
  volumes: [{name: data, persistentVolumeClaim: {claimName: data}}]
EOF
kubectl -n demo-storage apply -f storage.yaml > /dev/null
kubectl -n demo-storage wait --for=jsonpath='{.status.phase}'=Succeeded pod/writer --timeout=180s > /dev/null
kubectl -n demo-storage delete pod writer > /dev/null
kubectl -n demo-storage run reader --restart=Never --image=busybox:1.37 --overrides='{"spec":{"containers":[{"name":"reader","image":"busybox:1.37","command":["cat","/data/state.txt"],"volumeMounts":[{"name":"data","mountPath":"/data"}]}],"volumes":[{"name":"data","persistentVolumeClaim":{"claimName":"data"}}]}}' > /dev/null
kubectl -n demo-storage wait --for=jsonpath='{.status.phase}'=Succeeded pod/reader --timeout=120s > /dev/null
echo "a new pod reads: $(kubectl -n demo-storage logs reader)"
kubectl -n demo-storage get pvc data -o custom-columns=CLAIM:.metadata.name,STATUS:.status.phase,CLASS:.spec.storageClassName,SIZE:.status.capacity.storage

Output

a new pod reads: saved at first run
CLAIM   STATUS   CLASS      SIZE
data    Bound    standard   100Mi

Run this on your computer — see “Get Started” for setup.

Test yourself

What does a StorageClass do?

  1. Stores files
  2. Describes how volumes are provisioned dynamically for claims
  3. Backs up volumes
  4. Encrypts Secrets
Show answer

Answer: Describes how volumes are provisioned dynamically for claims

Claims reference a class; its provisioner creates the PersistentVolume.

Was this page helpful?