Course contents · Lesson 14 of 22

Kubernetes Volumes and PersistentVolumes Explained

Kubernetes Concepts · Lesson 14 of 22 · 11 min Engineer

Your app on Kubernetes saves uploaded photos to a folder. One night its pod is replaced, and every photo is gone. In lesson 5 a Docker volume solved this on one machine; a cluster needs storage that a replacement pod, perhaps on another node, can find again. This lesson explains Kubernetes volumes: storage that dies with a pod, and PersistentVolumes that outlive it.

emptyDir: scratch space that dies with the pod

A volume in Kubernetes is a directory that a pod declares under volumes and containers attach with volumeMounts, as the ConfigMap files did in lesson 13. Ephemeral volume types live exactly as long as their pod.

The simplest is emptyDir, an empty directory created when the pod is placed on a node. All the pod's containers can read and write it, each at its own path. A container crash leaves it alone; removing the pod from the node deletes it for good. In share.yaml, one container writes a file for the other:

apiVersion: v1
kind: Pod
metadata:
  name: share
spec:
  containers:
    - name: writer
      image: busybox:1.36
      command: ["sh", "-c", "echo hi from writer > /out/msg.txt; sleep 3600"]
      volumeMounts:
        - name: scratch
          mountPath: /out
    - name: reader
      image: busybox:1.36
      command: ["sleep", "3600"]
      volumeMounts:
        - name: scratch
          mountPath: /in
  volumes:
    - name: scratch
      emptyDir: {}

You create a cluster in lesson 17, so read along for now. Apply the file, then use kubectl exec, which runs a command in a running container, to read the file; -c picks the reader:

kubectl apply -f share.yaml
kubectl exec share -c reader -- cat /in/msg.txt

You should see the writer's message, read through the reader's own path:

pod/share created
hi from writer

If kubectl says the container is not running yet, or cat reports No such file or directory, wait a few seconds and retry. Deleting the pod deletes the directory too. For RAM-backed space, add medium: Memory; sizeLimit caps the size.

The persistent trio: PV, PVC and StorageClass

Kubernetes splits lasting storage into three objects, so whoever deploys an app need not know which disk is behind it.

A PersistentVolume (PV) is a piece of real storage in the cluster, such as a cloud disk, with a lifetime independent of any pod. An administrator can create PVs by hand, called static provisioning, or Kubernetes can create them on demand.

A PersistentVolumeClaim (PVC) is a request for storage, such as "1Gi that one node can write to". It lives in your namespace, and a pod mounts the claim, never the PV directly. Kubernetes binds each claim to exactly one PV.

A StorageClass describes a kind of storage the cluster offers, such as fast SSDs. It names a provisioner, the program that creates that storage, often a CSI driver: a storage plugin built to the Container Storage Interface standard. In the diagram, notice that the pod only knows the claim's name.

Diagram of four boxes in a row. A pod named notes-…, drawn dashed because pods come and go, mounts its storage at /data. It mounts the PVC notes-data, the request, for 1Gi with RWO. The PVC binds one to one to the PV pvc-3f6d…, the volume, which is Bound. The PV is stored on real storage: a cloud disk, or on kind a folder on the node. Below, the StorageClass standard: the PVC asks its class, and the class's provisioner creates the PV and makes the disk. Footer: without a StorageClass, an admin creates PVs by hand, called static provisioning
The pod only names a claim; claim, volume and disk outlive it.

Dynamic provisioning, step by step

With dynamic provisioning, you create only the claim: its StorageClass's provisioner makes a matching disk and PV, and Kubernetes binds them. A claim that names no class gets the cluster's default StorageClass. On kind that is standard, whose provisioner, rancher.io/local-path, makes a folder on the node instead of a cloud disk.

kind's class also uses WaitForFirstConsumer: provisioning waits until a pod using the claim is created, so the storage is made where the scheduler places that pod. The default mode, Immediate, provisions at once.

Now notes.yaml holds a claim and a one-replica Deployment that mounts it; --- separates the two objects. Each time a pod starts, it appends its own name, printed by hostname, to /data/who.txt:

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: notes-data
spec:
  accessModes: ["ReadWriteOnce"]
  resources:
    requests:
      storage: 1Gi
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: notes
spec:
  replicas: 1
  selector:
    matchLabels:
      app: notes
  template:
    metadata:
      labels:
        app: notes
    spec:
      containers:
        - name: notes
          image: busybox:1.36
          command: ["sh", "-c", "hostname >> /data/who.txt; sleep 3600"]
          volumeMounts:
            - name: data
              mountPath: /data
      volumes:
        - name: data
          persistentVolumeClaim:
            claimName: notes-data

Under volumes, persistentVolumeClaim names the claim, where lesson 13 named a ConfigMap. Apply the file, then list the claim to check that it got a volume:

kubectl apply -f notes.yaml
kubectl get pvc notes-data

Within a few seconds the claim should be Bound to a new PV, named pvc- plus the claim's unique ID; yours will differ:

persistentvolumeclaim/notes-data created
deployment.apps/notes created
NAME         STATUS   VOLUME                                     CAPACITY   ACCESS MODES   STORAGECLASS   VOLUMEATTRIBUTESCLASS   AGE
notes-data   Bound    pvc-3f6d2a8e-1c4b-4a57-9e0f-2b7d8c91a6e4   1Gi        RWO            standard       <unset>                 9s

Pending at first is normal; run it again. If it stays Pending, run kubectl describe pvc notes-data and read the Events: a misspelt storageClassName is a common cause. Its pod then stays Pending too, which lesson 20 debugs.

Now replace the pod, as a node failure or an update would. -l app=notes picks pods by their label:

kubectl delete pod -l app=notes
kubectl exec deploy/notes -- cat /data/who.txt

The Deployment starts a new pod, which mounts the same claim. After the delete line, you should see two pod names, the old one's and the new one's; yours will differ:

notes-6b7f9d8c4d-2xkqp
notes-6b7f9d8c4d-m8wzt

If exec fails because the new container is not running yet, wait a few seconds and repeat it. The diagram sums up the sequence.

Step-by-step flowchart in six numbered boxes. Left column, setting up the storage: 1, you create a PVC, notes-data asks for 1Gi RWO, STATUS Pending. 2, the provisioner makes a disk, as the StorageClass standard says: a cloud disk, or a folder on kind. 3, a PV is bound to the claim, pvc-3f6d… holds the storage, STATUS Bound. Right column, a pod uses it and is replaced: 4, the pod mounts the claim, /data is the PV, and it writes its name to who.txt. 5, the pod is deleted and the Deployment creates a new pod on a node that can reach the disk. 6, same claim, same data: who.txt still has the old line. Footer: on kind, with WaitForFirstConsumer, step 2 waits until a pod uses the claim
Pods come and go; the claim and its data stay.

Access modes and reclaim policies

Every claim asks for access modes: how many nodes may mount the volume, and whether they may write. A claim binds only to a PV that offers those modes, and what a PV offers depends on its storage. kubectl prints the short form:

ModeShortWho can mount it
ReadWriteOnceRWOOne node, read-write; pods on that node can share it
ReadOnlyManyROXMany nodes, read-only
ReadWriteManyRWXMany nodes, read-write; usually file storage such as NFS
ReadWriteOncePodRWOPOne pod, read-write; CSI volumes only

RWO limits nodes, not pods. Cloud block disks usually offer RWO, not RWX, so replicas sharing one RWO claim work on one node and break across several. The flowchart sums it up.

Flowchart. Start: a pod needs to keep files. Question: must the data outlive the pod, when it is deleted, replaced or moved? No leads to emptyDir, for scratch space, caches and files shared inside the pod, deleted with the pod; a note adds that a container restart keeps emptyDir data. Yes leads to: use a PVC, then a second question: must pods on several nodes write to it at the same time? No leads to ReadWriteOnce, RWO, where one node mounts it, the usual choice, for example one database pod. Yes leads to ReadWriteMany, RWX, usually file storage such as NFS, so check your StorageClass. Footer: if each replica needs its own volume, like a database, use a StatefulSet
Outlive the pod? Then a PVC, and the number of writing nodes picks its mode.

The reclaim policy says what happens to a PV when its claim is deleted. With Delete, Kubernetes removes the PV and the real disk, so the data is gone. A dynamically provisioned PV takes its StorageClass's policy, which defaults to Delete, as kind's does.

With Retain, the PV and its data stay, marked Released, and no new claim gets it while the old data is there; an administrator recovers or cleans it by hand. Use a class with reclaimPolicy: Retain for data you cannot lose. A third policy, Recycle, is deprecated.

StatefulSets: a volume for each pod

A Deployment's pods share one template, so they all mount the same claim, but each copy of a replicated database needs its own data. A StatefulSet is a controller like a Deployment, but each pod gets a stable name, such as db-0 and db-1, and its own PVC from a volumeClaimTemplates entry. A replacement db-1 mounts the old db-1 claim. Deleting or scaling down a StatefulSet keeps those claims by default, and it needs a headless Service, one without a ClusterIP, to give each pod its own DNS name.

Check yourself

A container in a pod crashes and the kubelet restarts it. Is the data in the pod's emptyDir lost?

No. An emptyDir belongs to the pod, and a container restart keeps the pod on its node; only removing the pod deletes the data.

You test with a claim from the default StorageClass, then delete the claim to tidy up. Can you still recover its data?

Usually not. A dynamic PV takes its class's reclaim policy, by default Delete, so the PV and disk went with the claim. With Retain, the PV would have stayed, Released, for an administrator to recover.

On a three-node cloud cluster, three replicas of a Deployment share one ReadWriteOnce claim. Pods on one node run, but the others never start. Why?

RWO lets only one node mount the volume, so pods on other nodes cannot attach it. Use a StatefulSet for a volume each, or ReadWriteMany storage if they must share files.