Volumes, PersistentVolumes and claims

Kubernetes · Practical · 12 min

Containers lose their filesystem on restart; anything that must survive needs a volume.

A pod's volumes list makes storage available to its containers through volumeMounts. Some volume types are temporary: emptyDir lives as long as the pod (scratch space, sharing files between containers), configMap/secret project config as files.

For durable data, Kubernetes separates request from supply:

  • A PersistentVolumeClaim (PVC, namespaced) asks for storage: size, accessModes, optional storageClassName.
  • A PersistentVolume (PV, cluster-wide) is an actual piece of storage: a cloud disk, an NFS share.
  • A StorageClass names a provisioner (the CSI driver for EBS, Persistent Disk, Azure Disk, Longhorn...) and its parameters. With dynamic provisioning, creating a PVC makes the driver create a disk and a PV, and binds them.

Access modes: ReadWriteOnce (one node at a time; typical block disks), ReadWriteOncePod (one pod), ReadOnlyMany, ReadWriteMany (shared filesystems like NFS or EFS).

reclaimPolicy decides what happens when the PVC is deleted: Delete (default for dynamic classes; the disk is gone) or Retain. volumeBindingMode: WaitForFirstConsumer delays creating the disk until a pod is scheduled, so it lands in the right zone.

PVCs can usually be expanded by increasing the size, if the class has allowVolumeExpansion: true; they can't shrink.

Example

apiVersion: v1
kind: PersistentVolumeClaim
metadata: {name: uploads}
spec:
  accessModes: [ReadWriteOnce]
  storageClassName: standard     # kubectl get storageclass
  resources:
    requests: {storage: 10Gi}
---
apiVersion: v1
kind: Pod
metadata: {name: uploader}
spec:
  containers:
    - name: app
      image: busybox:1.37
      command: ["sh", "-c", "date >> /data/log; sleep 3600"]
      volumeMounts: [{name: data, mountPath: /data}]
  volumes:
    - name: data
      persistentVolumeClaim: {claimName: uploads}
# kubectl get pvc uploads     # STATUS Bound, VOLUME pvc-3f1c...

Remember

  • PVC = request, PV = supply, StorageClass = how to provision
  • ReadWriteOnce disks attach to one node at a time
  • Default reclaimPolicy Delete removes the disk with the PVC

Watch out for

  • Scaling a Deployment with one ReadWriteOnce PVC to several replicas on different nodes: the extra pods can't mount it.

Check yourself

  1. Why is WaitForFirstConsumer useful for zonal cloud disks?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: kubernetes.io/docs/concepts/storage/persistent-volumes/