Skip to content
LF Cert Trainer

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

1/10Volumes
0:00 / 3:54

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.

A volume is declared in the Pod and mounted in containersPodmountsmountstype decides where the data isContainer writermountPath: /dataVolume htmlspec.volumesContainer webmountPath: /usr/share/…What backs itemptyDir, hostPath, NFS, PVC
A volume is declared in the Pod and mounted in containers. The volume belongs to the Pod. Each container that wants it adds a volumeMount with its own path, so two containers can see the same files at different paths.

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
FieldLevelMeaning
volumes[].namePodThe name containers refer to. Unique in the Pod
volumes[].<type>PodExactly one type per volume, for example emptyDir, hostPath, nfs, persistentVolumeClaim
volumeMounts[].nameContainerMust equal a volume name of the Pod
volumeMounts[].mountPathContainerWhere the volume appears inside this container
volumeMounts[].readOnlyContainerMount read-only in this container. Default false
volumeMounts[].subPathContainerMount 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 ContainerCreating and the events show FailedMount.
  • A volume lives at the Pod level, so a restarting container finds the volume exactly as it left it.
How long the data liveslost atlost atlost atlostContainer layerno volumeemptyDirtied to the PodhostPathtied to one nodeNFS, PVCoutside the cluster nodesContainer restartdata is gonePod deleted or evicteddata is gonePod moves to another nodedata stays behindOnly when you delete itsurvives Pods and nodes
How long the data lives. The volume type decides what the data is tied to. Pick the type by asking which event must not destroy the data.

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

TypeWhere the data isLives as long asUse it for
emptyDirA directory on the node, or memoryThe PodScratch space, caches, sharing files between containers
configMap, secret, downwardAPI, projectedFiles written by the kubeletThe Pod (the source object lives on)Configuration and credentials as files
imageA read-only OCI image or artifact pulled by the nodeThe PodShipping data files or models separately from the application image
hostPathA path of the node's own file systemThe nodeSystem Pods that need the node's files or sockets
nfsAn NFS serverThe serverA network share mounted without any PersistentVolume
persistentVolumeClaimWhatever the bound PersistentVolume describesThe PersistentVolumeApplication data
ephemeral, csiA volume created by a driver for this PodThe PodPer-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
FieldMeaning
mediumEmpty (default): the node's disk, where the kubelet keeps its data. Memory: a tmpfs in RAM
sizeLimitThe 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-storage limit is evicted when the sum exceeds it.
  • medium: Memory counts 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
typeThe kubelet checks before the Pod starts
Empty (default)Nothing
DirectoryOrCreateCreates an empty directory with mode 0755, owned by the kubelet's user, if nothing is there
DirectoryA directory must exist
FileOrCreateCreates an empty file with mode 0644 if nothing is there. The parent directory must exist
FileA file must exist
Socket, CharDevice, BlockDeviceA 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.

hostPath on a cluster with more than one nodenode-1node-2hostPathmovedhostPathPod web, first runwrites orders.txt/data on node-1orders.txtPod web, recreatedreads /data/data on node-2empty
hostPath on a cluster with more than one node. A hostPath volume is a directory of whichever node the Pod runs on. When the Pod is recreated on another node, it finds that node's directory, not its old data.

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/kubelet or the container runtime's socket can take over the node. The baseline Pod Security Standard forbids hostPath volumes for this reason.
  • Permissions surprise. A directory created by DirectoryOrCreate belongs 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 subPath mount of a configMap or secret volume does not receive updates when the object changes. A whole-volume mount is refreshed by the kubelet. A subPath mount stays as it was when the container started.
  • subPathExpr builds the subdirectory name from environment variables, for example subPathExpr: $(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 volumes and volumeMounts. The API rejects the Pod with volumeMounts[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 subPath to 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 nfs volume is mounted by the node, so the node needs the client tools. The symptom is FailedMount with bad option or mount: 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 under containers[].volumeMounts (same name and mountPath).
  • emptyDir is created with the Pod and deleted with it. Use it for scratch space and for sharing files between containers.
  • hostPath is 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.