Lesson 96 · Section 8: Storage
Lesson 96: Volumes: giving a Pod storage that outlives its containers
How a Pod gets storage: a volume declared once in the Pod and mounted into its containers. What emptyDir and hostPath really do, how long each kind of volume lives, and why node-local volumes are not enough for real data. · 17 min read · 4 min video
Official competencies this lesson covers
Narrated by the local narrator voice. Keys: Space plays and pauses, J and L step, C captions, F full screen.
What this lesson is about
You saw in the lesson Storage in Docker that a container has a thin writable layer that is deleted with the container, and that a mount is the way to keep data outside it. Kubernetes has the same problem in a sharper form: the kubelet replaces a container on every restart, so a crashed process is enough to lose everything it wrote.
A volume is the Kubernetes answer. This lesson covers the volume mechanism itself and the types that need no
other objects: emptyDir, hostPath and direct network mounts such as nfs. PersistentVolumes, claims and
storage classes build on the same mechanism and follow in the next lessons.
Why it exists
Two problems of a bare container:
- Files are lost on restart. The kubelet does not restart a container in place. It creates a new one from the image, with a new empty writable layer.
- Containers of a Pod cannot see each other's files. Each has its own root file system, even though they share the network.
kubectl run web --image=nginx:1.29-alpine
kubectl exec web -- sh -c 'echo order-42 > /tmp/orders.txt'
kubectl exec web -- nginx -s stop # the main process exits, the kubelet restarts the container
kubectl get pod web
kubectl exec web -- cat /tmp/orders.txt
NAME READY STATUS RESTARTS AGE
web 1/1 Running 1 (5s ago) 3m
cat: /tmp/orders.txt: No such file or directory
The Pod is the same Pod, with the same name and IP address. Only the container was replaced, and that was enough.
What it is
A volume always has two parts in the manifest.
Parts:
- Container writer (mountPath: /data), in Pod
- Volume html (spec.volumes), in Pod
- Container web (mountPath: /usr/share/…), in Pod
- What backs it (emptyDir, hostPath, NFS, PVC)
Connections:
- Container writer to Volume html: mounts
- Container web to Volume html: mounts
- Volume html to What backs it: type decides where the data is
apiVersion: v1
kind: Pod
metadata:
name: web
spec:
volumes: # 1. the Pod declares the volume: a name and a type
- name: html
emptyDir: {}
containers:
- name: writer
image: busybox:1.37
command: ["sh", "-c", "while true; do date > /data/index.html; sleep 5; done"]
volumeMounts: # 2. a container mounts it: the same name and a path
- name: html
mountPath: /data
- name: web
image: nginx:1.29-alpine
volumeMounts:
- name: html
mountPath: /usr/share/nginx/html
readOnly: true
| Field | Level | Meaning |
|---|---|---|
volumes[].name | Pod | The name containers refer to. Unique in the Pod |
volumes[].<type> | Pod | Exactly one type per volume, for example emptyDir, hostPath, nfs, persistentVolumeClaim |
volumeMounts[].name | Container | Must equal a volume name of the Pod |
volumeMounts[].mountPath | Container | Where the volume appears inside this container |
volumeMounts[].readOnly | Container | Mount read-only in this container. Default false |
volumeMounts[].subPath | Container | Mount only one file or subdirectory of the volume |
The split has a purpose. The Pod decides what storage exists. Each container decides whether and where
it sees it. In the example, writer sees the volume at /data and may write, and web sees the same files at
/usr/share/nginx/html read-only. Init containers can mount volumes too, which is the usual way to prepare
files before the application starts.
How it works
The kubelet sets up every volume of a Pod before it starts any container. For each Pod it keeps a directory on the node:
/var/lib/kubelet/pods/<pod-uid>/volumes/kubernetes.io~empty-dir/html/
/var/lib/kubelet/pods/<pod-uid>/volumes/kubernetes.io~nfs/reports/
/var/lib/kubelet/pods/<pod-uid>/volumes/kubernetes.io~csi/pvc-8d1c04e2/mount/
Depending on the type, the kubelet creates an empty directory there (emptyDir), writes files into it
(configMap, secret), mounts a network share on it (nfs), or asks a CSI driver to mount a disk on it. A
hostPath needs no such directory, because the path on the node is used directly. Then the kubelet tells the
container runtime to bind-mount the directory into each container at its mountPath. This is the same bind
mount you made by hand with docker run -v.
Two consequences follow:
- If a volume cannot be set up, no container starts. The Pod stays in
ContainerCreatingand the events showFailedMount. - A volume lives at the Pod level, so a restarting container finds the volume exactly as it left it.
Parts:
- Container layer (no volume)
- emptyDir (tied to the Pod)
- hostPath (tied to one node)
- NFS, PVC (outside the cluster nodes)
- Container restart (data is gone)
- Pod deleted or evicted (data is gone)
- Pod moves to another node (data stays behind)
- Only when you delete it (survives Pods and nodes)
Connections:
- Container layer to Container restart: lost at
- emptyDir to Pod deleted or evicted: lost at
- hostPath to Pod moves to another node: lost at
- NFS, PVC to Only when you delete it: lost
The volume types
| Type | Where the data is | Lives as long as | Use it for |
|---|---|---|---|
emptyDir | A directory on the node, or memory | The Pod | Scratch space, caches, sharing files between containers |
configMap, secret, downwardAPI, projected | Files written by the kubelet | The Pod (the source object lives on) | Configuration and credentials as files |
image | A read-only OCI image or artifact pulled by the node | The Pod | Shipping data files or models separately from the application image |
hostPath | A path of the node's own file system | The node | System Pods that need the node's files or sockets |
nfs | An NFS server | The server | A network share mounted without any PersistentVolume |
persistentVolumeClaim | Whatever the bound PersistentVolume describes | The PersistentVolume | Application data |
ephemeral, csi | A volume created by a driver for this Pod | The Pod | Per-Pod volumes from a storage driver |
Cloud-specific types that you may see in old manifests, such as awsElasticBlockStore, gcePersistentDisk or
azureDisk, are deprecated. Their work is done by CSI drivers today, and you reach those through a
persistentVolumeClaim. The gitRepo type has been removed: use an init container that clones into an
emptyDir.
emptyDir
The kubelet creates an empty directory when the Pod is assigned to a node and deletes it when the Pod is removed from the node for any reason: deletion, eviction, a finished Job, node drain.
volumes:
- name: cache
emptyDir:
sizeLimit: 500Mi
- name: scratch
emptyDir:
medium: Memory
sizeLimit: 64Mi
| Field | Meaning |
|---|---|
medium | Empty (default): the node's disk, where the kubelet keeps its data. Memory: a tmpfs in RAM |
sizeLimit | The most the volume may hold. If the Pod writes more, the kubelet evicts the Pod |
Things to know:
- It survives container restarts, not Pod deletion. A Deployment that replaces a Pod gives the new Pod a new, empty directory.
- It counts as ephemeral storage of the node, together with container layers and logs. A Pod with an
ephemeral-storagelimit is evicted when the sum exceeds it. medium: Memorycounts as memory of the containers that write to it. Files there use up the container's memory limit, and the data is gone when the node reboots.
hostPath
A hostPath volume mounts a file or directory of the node into the Pod.
volumes:
- name: data
hostPath:
path: /data
type: DirectoryOrCreate
type | The kubelet checks before the Pod starts |
|---|---|
| Empty (default) | Nothing |
DirectoryOrCreate | Creates an empty directory with mode 0755, owned by the kubelet's user, if nothing is there |
Directory | A directory must exist |
FileOrCreate | Creates an empty file with mode 0644 if nothing is there. The parent directory must exist |
File | A file must exist |
Socket, CharDevice, BlockDevice | A socket or device of that kind must exist |
On a one-node cluster a hostPath looks like persistent storage, and many tutorials use it that way. On a
cluster with several nodes it is not.
Parts:
- Pod web, first run (writes orders.txt), in node-1
- /data on node-1 (orders.txt), in node-1
- Pod web, recreated (reads /data), in node-2
- /data on node-2 (empty), in node-2
Connections:
- Pod web, first run to /data on node-1: hostPath
- Pod web, first run to Pod web, recreated: moved
- Pod web, recreated to /data on node-2: hostPath
- The data does not follow the Pod. Each node has its own
/data. A Pod recreated on another node starts with that node's directory. - Replicas do not share it. Three replicas on three nodes write to three different directories.
- It is a security risk. A Pod that may mount
/or/var/lib/kubeletor the container runtime's socket can take over the node. The baseline Pod Security Standard forbidshostPathvolumes for this reason. - Permissions surprise. A directory created by
DirectoryOrCreatebelongs to root. A container that runs as another user cannot write to it.
Legitimate users are node-level agents, normally DaemonSets: a log collector reading /var/log, a monitoring
agent reading /proc and /sys, a CNI or CSI plugin installing files on the node. The control plane's static
Pods use hostPath too, for example for /etc/kubernetes/pki. Mount it readOnly whenever reading is enough.
Network storage directly in the Pod
To keep data when a Pod moves between nodes, the data must be outside the nodes. The most direct way is to name the storage in the Pod itself:
volumes:
- name: reports
nfs:
server: 10.0.0.10
path: /exports/reports
readOnly: false
Every node that runs this Pod mounts the same share, so the Pod finds its data anywhere, and many Pods can use it at once. The nodes need the NFS client tools installed.
This works, but look at what the Pod author must know: the server's address and the exported path. Every manifest repeats them, and a change of the storage means editing every workload. In a large cluster the people who write Pods are not the people who run the storage. That separation is the reason for PersistentVolumes and PersistentVolumeClaims: the administrator describes the storage once, and the Pod only names a claim.
volumes:
- name: reports
persistentVolumeClaim:
claimName: reports-claim
Under the hood · subPath, and when a mount stops updating
subPath mounts one file or directory inside the volume instead of its root. Two common uses:
volumeMounts:
- name: config
mountPath: /etc/nginx/conf.d/site.conf # add one file without hiding the rest of conf.d
subPath: site.conf
- name: shared
mountPath: /var/lib/mysql # two apps, two folders in one volume
subPath: mysql
Two details catch people out:
- A
subPathmount of aconfigMaporsecretvolume does not receive updates when the object changes. A whole-volume mount is refreshed by the kubelet. AsubPathmount stays as it was when the container started. subPathExprbuilds the subdirectory name from environment variables, for examplesubPathExpr: $(POD_NAME)with a variable from the downward API, so every Pod writes to its own folder of a shared volume.
A third mount option, mountPropagation, controls whether mounts made inside the volume by the container
become visible on the host (Bidirectional) or the other way round (HostToContainer). Only node-level
plugins such as CSI drivers need it.
Using it
Example · Share files between two containers with emptyDir
Apply the Pod from the section What it is, then:
kubectl exec web -c web -- cat /usr/share/nginx/html/index.html
kubectl exec web -c web -- sh -c 'echo x > /usr/share/nginx/html/test'
Wed Dec 2 10:31:15 UTC 2026
sh: can't create /usr/share/nginx/html/test: Read-only file system
The web container reads what writer produces, at another path, and cannot write because its mount is
readOnly. Now restart one container and check that the volume survives:
kubectl exec web -c web -- nginx -s stop
kubectl get pod web # RESTARTS 1
kubectl exec web -c web -- cat /usr/share/nginx/html/index.html
The page is still there, with a fresh date from writer.
Example · Add a volume to a Pod in the exam
Task: "Create a Pod cache with image redis:8-alpine and an emptyDir volume data mounted at /data."
kubectl run cannot add volumes, so generate and edit:
kubectl run cache --image=redis:8-alpine --dry-run=client -o yaml > cache.yaml
Add the two blocks:
apiVersion: v1
kind: Pod
metadata:
name: cache
labels:
run: cache
spec:
volumes:
- name: data
emptyDir: {}
containers:
- name: cache
image: redis:8-alpine
volumeMounts:
- name: data
mountPath: /data
kubectl apply -f cache.yaml
kubectl describe pod cache | grep -A 4 -E '^Volumes|Mounts:'
Mounts:
/data from data (rw)
/var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-7xk2p (ro)
--
Volumes:
data:
Type: EmptyDir (a temporary directory that shares a pod's lifetime)
Medium:
SizeLimit: <unset>
Example · Read a node's logs with a read-only hostPath
apiVersion: v1
kind: Pod
metadata:
name: log-reader
spec:
nodeName: node-1
volumes:
- name: varlog
hostPath:
path: /var/log
type: Directory
containers:
- name: reader
image: busybox:1.37
command: ["sh", "-c", "tail -n 3 /host/var/log/syslog; sleep 3600"]
volumeMounts:
- name: varlog
mountPath: /host/var/log
readOnly: true
type: Directory makes the Pod fail early with a clear event if the path is missing, instead of mounting
something unexpected. nodeName pins the Pod, because a hostPath only makes sense when you know which node you
are reading. A real log collector would be a DaemonSet, one Pod per node.
Example · Find a Pod's volume on the node
kubectl get pod web -o jsonpath='{.metadata.uid}{"\n"}{.spec.nodeName}{"\n"}'
5d1e7c0a-93b4-4f0e-8a67-2b1c9d4e6f30
node-1
On node-1:
sudo ls /var/lib/kubelet/pods/5d1e7c0a-93b4-4f0e-8a67-2b1c9d4e6f30/volumes/kubernetes.io~empty-dir/html
index.html
The emptyDir is an ordinary directory under the kubelet's data directory, named after the Pod's UID. That is why it disappears with the Pod, and why a full node disk and emptyDir usage are connected.
Tricks
Common mistakes
- Different names in
volumesandvolumeMounts. The API rejects the Pod withvolumeMounts[0].name: Not found. The names must be identical. - Declaring a volume and forgetting to mount it. The Pod runs, and the container still writes to its own layer.
- Expecting emptyDir to keep data across Pods. It survives a container restart only. A new Pod, even with the same name, gets a new directory.
- Using hostPath for application data on a multi-node cluster. The data stays on one node, and the next Pod may run elsewhere.
- Mounting over a directory the image needs. The mount hides the image's files. Use
subPathto add a single file. - Filling an in-memory emptyDir. The files count against the container's memory limit, and the container is killed for running out of memory.
- Forgetting the NFS client on the nodes. An
nfsvolume is mounted by the node, so the node needs the client tools. The symptom isFailedMountwithbad optionormount: wrong fs type.
Recap
- A container's own files are lost at every container restart. A volume is storage owned by the Pod and mounted into containers.
- Declare under
spec.volumes(name and type), mount undercontainers[].volumeMounts(same name andmountPath). emptyDiris created with the Pod and deleted with it. Use it for scratch space and for sharing files between containers.hostPathis a path of one node. It is for node-level system Pods, not for application data.- Data that must survive Pods and nodes needs storage outside the node: a network volume in the Pod, or better a PersistentVolumeClaim, which the next lessons introduce.
Official docs
Quiz: check what you learned
5 questions on this lesson · about 3 min · instant feedback. Missed questions come back in your review queue.
Sign in to take the quiz and keep your score.
Practise: try it on a real cluster
A hands-on lab for this lesson. You get goals, not steps: any solution that reaches them passes.
Share a directory between two containers of a pod so that it outlives a container restart, and give a pod a read-only view of a directory on the node.
Build · Level 1 · warm-up · target 15 min
Discussion
Learners ask and answer questions here. Sign in to read and join the discussion.