Storage: Volumes, PVs, PVCs and StorageClasses

Topics Covered

Volumes Inside the Pod

The volume and mount pair

emptyDir

hostPath

configMap, secret, projected and downwardAPI

Generic ephemeral volumes

Verifying a mount

Choosing the right volume type

Init containers and volumes

subPath mounts

Storage tasks are worth real points on both exams, and they follow a small number of patterns: give a pod some scratch space, mount a PersistentVolumeClaim, create a PV and PVC that bind to each other, write a StorageClass, fix a claim stuck in Pending, reuse a retained volume, expand a claim, and give a StatefulSet per pod storage. This lesson works through each pattern with the YAML you will type, the field that usually goes wrong, and the commands that prove it worked. The containers course covered why persistent storage is hard; here the goal is speed and correctness.

The first section covers volumes that live inside the pod spec itself. They need no extra objects, and they appear in many tasks that are not really about storage, such as sidecars sharing log files.

The volume and mount pair

Every volume has two halves. The pod spec declares it under spec.volumes with a name and a source. Each container that uses it lists a volumeMounts entry with the same name and a mountPath.

yaml
1apiVersion: v1
2kind: Pod
3metadata:
4  name: shared
5  namespace: data
6spec:
7  volumes:
8  - name: scratch
9    emptyDir: {}
10  containers:
11  - name: writer
12    image: busybox:1.36
13    command: ["sh", "-c", "while true; do date >> /out/log.txt; sleep 5; done"]
14    volumeMounts:
15    - name: scratch
16      mountPath: /out
17  - name: reader
18    image: busybox:1.36
19    command: ["sh", "-c", "touch /in/log.txt; tail -f /in/log.txt"]
20    volumeMounts:
21    - name: scratch
22      mountPath: /in
23      readOnly: true

The same volume can be mounted at different paths in different containers, and one container can mount it read only while another writes. The names must match exactly. A volumeMounts entry that names a volume not declared in spec.volumes is rejected by the API server with a clear error, which is at least easy to spot. A declared volume that no container mounts is accepted silently and does nothing, which is harder to spot.

emptyDir

An emptyDir is created empty when the pod is assigned to a node and deleted when the pod is removed from that node. It survives container restarts, because it belongs to the pod, not the container. It does not survive the pod being deleted, evicted or rescheduled.

An emptyDir lives as long as the pod and is shared by every container that mounts it.

By default it lives on the node's disk, in the kubelet's directory. Two options change that:

yaml
1  volumes:
2  - name: cache
3    emptyDir:
4      medium: Memory      # tmpfs in RAM
5      sizeLimit: 256Mi

medium: Memory puts it in tmpfs, which is fast and is counted against the container's memory limit, so a full memory backed emptyDir can get the pod OOM killed. sizeLimit caps usage; if a pod writes past it, the kubelet evicts the pod. Use emptyDir for caches, scratch space for sorting or processing, and sharing files between containers, such as a log file that a sidecar ships.

hostPath

A hostPath volume mounts a file or directory from the node's own filesystem into the pod.

yaml
1  volumes:
2  - name: node-logs
3    hostPath:
4      path: /var/log
5      type: Directory

The type field validates what exists at the path: Directory and File require it to exist, DirectoryOrCreate and FileOrCreate create it if missing, and Socket, CharDevice and BlockDevice check for special files. An empty type does no check at all.

hostPath is powerful and risky. The data is tied to one node, so a pod rescheduled elsewhere sees a different directory. Writing to host paths can let a container modify the node, which is why Pod Security's baseline level forbids hostPath. Legitimate uses are node agents such as log collectors and monitoring daemons, usually run as DaemonSets. On the exam, hostPath appears mostly as the backing for a simple PersistentVolume in a single node practice cluster, which the next section uses.

configMap, secret, projected and downwardAPI

You met configMap, secret and projected volumes in lesson five. The downwardAPI volume exposes the pod's own metadata, such as labels, annotations and resource limits, as files:

yaml
1  volumes:
2  - name: podinfo
3    downwardAPI:
4      items:
5      - path: labels
6        fieldRef:
7          fieldPath: metadata.labels
8      - path: mem_limit
9        resourceFieldRef:
10          containerName: app
11          resource: limits.memory

Labels and annotations exposed this way update in place when they change. The same information is available as environment variables through env.valueFrom.fieldRef, for example status.podIP or spec.nodeName, but environment variables do not update. A task that asks a container to know "its own pod name and namespace" is answered with fieldRef to metadata.name and metadata.namespace.

Generic ephemeral volumes

A generic ephemeral volume is a PVC created for the pod and deleted with it. It gives you the features of a real storage class, such as a particular disk type, a larger size than node scratch space or snapshots, with the lifetime of an emptyDir.

yaml
1  volumes:
2  - name: work
3    ephemeral:
4      volumeClaimTemplate:
5        spec:
6          accessModes: ["ReadWriteOnce"]
7          storageClassName: fast
8          resources:
9            requests:
10              storage: 20Gi

The PVC is named PODNAME-VOLUMENAME and is owned by the pod, so garbage collection removes it when the pod goes. This is a newer and less common pattern, but it is worth recognising when a task describes "per pod scratch storage from the fast class".

Verifying a mount

For any volume task, check from inside the container.

bash
1kubectl -n data exec shared -c reader -- ls -la /in
2kubectl -n data exec shared -c writer -- df -h /out
3kubectl -n data exec shared -c reader -- cat /in/log.txt
4kubectl -n data describe pod shared | sed -n '/Volumes:/,/QoS/p'

df -h shows what is mounted at the path and its size, which distinguishes an emptyDir on disk from tmpfs and from a network volume. describe lists each volume with its type and source. When a pod is stuck in ContainerCreating, the events at the bottom of describe almost always name the failing volume, with a FailedMount or FailedAttachVolume reason. Read them first; they save you from guessing.

Choosing the right volume type

Most volume questions come down to one decision: how long must the data live, and who must see it? Use this short guide when a task describes the need in words rather than naming the type.

NeedVolume typeLifetime
Share files between containers in one podemptyDirthe pod
Fast scratch space in memoryemptyDir with medium Memorythe pod
Read node files from a node agenthostPaththe node
Inject configuration or credentialsconfigMap, secret, projectedthe source object
Expose the pod's own labels or limitsdownwardAPIthe pod
Per pod scratch from a real storage classgeneric ephemeralthe pod
Data that must outlive the podpersistentVolumeClaimthe claim

The last row is the important boundary. Anything that must survive the pod being deleted, rescheduled or replaced belongs on a PersistentVolumeClaim, which the next four sections cover. If a task says "the data must still be there after the pod is recreated", an emptyDir answer is wrong even if every other field is right.

Init containers and volumes

Init containers can mount the same volumes as the main containers, and they run to completion before the main containers start. That makes them the standard way to prepare a volume: download a file, render a configuration template or set permissions.

yaml
1spec:
2  volumes:
3  - name: site
4    emptyDir: {}
5  initContainers:
6  - name: fetch
7    image: busybox:1.36
8    command: ["sh", "-c", "echo hello > /work/index.html"]
9    volumeMounts:
10    - name: site
11      mountPath: /work
12  containers:
13  - name: web
14    image: nginx:1.27
15    volumeMounts:
16    - name: site
17      mountPath: /usr/share/nginx/html

If the init container fails, the pod shows Init:Error or Init:CrashLoopBackOff, and kubectl logs POD -c fetch shows why. The main container never starts until every init container succeeds, so the web server above always finds the file in place.

subPath mounts

A subPath mounts a single file or subdirectory of a volume instead of its root, which lets you place one file into a directory that already has other content. Remember the trade off from lesson five: a subPath mount of a ConfigMap or Secret does not receive live updates. Use it when you need a single file in a crowded directory and do not need live updates.

Write the volume and the mount together

Type spec.volumes and the matching volumeMounts in the same edit and copy the name between them. A volume with no mount is accepted silently and is the most common reason a pod looks right but sees an empty directory.