Skip to content
Visual explainer 2h to learn 3 steps

Volumes: emptyDir, hostPath, projected

Share data between containers and mount config into Pods.

By Invicly Tech, , in Kubernetes Administrator (CKA). About 9 minutes to read.

Topic 23 of 33

In short

Volumes give containers storage that outlives a container restart. emptyDir is scratch space shared by containers in one Pod, hostPath mounts a directory from the node, and projected volumes combine Secrets, ConfigMaps, downward API data and service account tokens into one mount.

Explained simply

A container's own filesystem is temporary. When the container crashes and restarts, everything it wrote is gone, because it starts again from the clean image. Volumes fix this by giving the Pod folders that live outside any single container.

You declare a volume once for the whole Pod, under spec.volumes. Then each container that needs it mounts it at a path of its choice with volumeMounts. Two containers mounting the same volume see the same files, which is how a helper container can read logs the main app writes.

There are many volume types. emptyDir is a blank scratch folder that lives as long as the Pod. hostPath opens a folder from the node itself. projected puts several small sources (Secrets, ConfigMaps, Pod details, tokens) together in one folder.

None of these keep data safe if the Pod is deleted or moves to another node. For real, long-lived data such as a database, you use PersistentVolumeClaims, covered next. Volumes in this topic are for sharing, scratch space and config.

Press Play on a diagram to walk through it one step at a time.

CompareCommon volume types
emptyDir
  • Created empty with the Pod
  • Deleted when Pod is removed
  • Shared between containers
  • medium: Memory for tmpfs
hostPath
  • Mounts a node path
  • Data tied to that node
  • Security risk on shared nodes
  • Used by static Pods and agents
projected
  • Merges several sources
  • Secret, ConfigMap, downwardAPI
  • Service account tokens
  • One mount directory
CompareHow long does the data live?
Container filesystem
  • Lost on container restart
  • Fresh copy of the image
  • Use for nothing important
emptyDir
  • Survives container restarts
  • Lost when Pod is deleted
  • Never moves between nodes
PVC-backed volume
  • Survives Pod deletion
  • Follows the Pod to new nodes
  • Lifetime set by reclaim policy

In depth

emptyDir under the hood

When a Pod with an emptyDir lands on a node, the kubelet creates a folder under /var/lib/kubelet/pods/POD_UID/volumes/kubernetes.io~empty-dir/NAME. It survives container restarts because it belongs to the Pod, not the container, and it is deleted when the Pod leaves the node for any reason.

By default it uses the node's disk and counts as ephemeral storage. Set sizeLimit to cap it; if the Pod writes more, the kubelet evicts the Pod. medium: Memory puts it in tmpfs (RAM), which is fast but counts toward the container's memory limit, so a big cache can get the container OOMKilled. Use emptyDir for caches, sorting space, and files passed between an init container and the app.

  • emptyDir: { sizeLimit: 500Mi }
  • emptyDir: { medium: Memory, sizeLimit: 64Mi }
  • A container restart keeps the files; a Pod deletion removes them

hostPath: power and danger

hostPath mounts a file or folder from the node into the Pod. Its type field adds a check: DirectoryOrCreate and FileOrCreate create the path if missing, while Directory, File and Socket require it to exist already, or the Pod fails to start. The default empty type does no check at all.

hostPath is how node agents read /var/log or reach the container runtime socket, and how kubeadm's static Pods mount certificates from /etc/kubernetes/pki. For normal apps it is risky: a Pod could read or change host files, and data stays on one node, so a rescheduled Pod finds an empty folder elsewhere. The Pod Security Standards forbid hostPath at the baseline level for that reason. If you must use it, mount it readOnly: true.

  • hostPath: { path: /var/log, type: Directory }
  • Files are created as root on the node
  • Fine for single-node labs; avoid for app data

Projected volumes and the downward API

A projected volume combines several sources into one folder: secret, configMap, downwardAPI and serviceAccountToken. You already use one in every Pod: the kube-api-access-xxxxx volume mounted at /var/run/secrets/kubernetes.io/serviceaccount, which holds a short-lived token, the cluster CA certificate and the namespace name.

The downward API exposes facts about the Pod itself: metadata.name, metadata.namespace, labels and annotations, and container resource values such as limits.memory. As files, labels and annotations are kept up to date; as env vars, values are fixed at start. A serviceAccountToken source can request a token with its own audience and lifetime (expirationSeconds, at least 600), which the kubelet refreshes before it expires.

MapOne projected volume at /etc/podinfo
projected
  • secret: db
    • password
  • configMap: app
    • app.properties
  • downwardAPI
    • labels
    • namespace
    • mem_limit
  • serviceAccountToken
    • token (audience vault, 1h)

Mount options that matter

readOnly: true on a volumeMount stops the container from writing. subPath mounts a single file or subfolder of the volume instead of the whole thing, which avoids hiding the rest of the target folder, but subPath mounts do not receive ConfigMap or Secret updates. subPathExpr can build that path from an env var, such as the Pod name, so each replica writes to its own subfolder of a shared volume.

When a volume is mounted over an existing folder in the image, the image's files there are hidden while the mount is active. Use a fresh path, or subPath, when the image already ships files in that folder.

Learn it in 3 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Share data with emptyDir~40m
  2. 2
    Mount host files with hostPath~40m
  3. 3
    Combine sources with projected volumes~40m

Key points

  • emptyDir survives container restarts but not Pod deletion.
  • Declare volumes under spec.volumes and mount them per container.
  • hostPath data stays on the node when the Pod moves elsewhere.
  • Use PersistentVolumeClaims for data that must survive Pods.

Key terms

Tap a card to flip it. 0/5 known

Examples

yaml
spec:
  containers:
    - name: writer
      image: busybox:1.36
      command: ["sh", "-c", "while true; do date >> /data/log; sleep 5; done"]
      volumeMounts: [{ name: shared, mountPath: /data }]
    - name: reader
      image: busybox:1.36
      command: ["sh", "-c", "tail -f /data/log"]
      volumeMounts: [{ name: shared, mountPath: /data }]
  volumes:
    - name: shared
      emptyDir: {}

Two containers share files through emptyDir.

An init container prepares files for the app

nginx should serve a page generated at start-up. Step 1: an init container writes index.html into an emptyDir. Step 2: the nginx container mounts the same emptyDir at its web root. Step 3: once the init container exits, nginx starts and serves the generated file. Step 4: test with port-forward.

yaml
spec:
  initContainers:
    - name: gen
      image: busybox:1.36
      command: [sh, -c, "echo built at $(date) > /work/index.html"]
      volumeMounts: [{ name: site, mountPath: /work }]
  containers:
    - name: web
      image: nginx:1.27
      volumeMounts: [{ name: site, mountPath: /usr/share/nginx/html }]
  volumes:
    - { name: site, emptyDir: { sizeLimit: 10Mi } }
# kubectl port-forward pod/NAME 8080:80 ; curl localhost:8080

Expose Pod details to the app as files

An app wants its own Pod name, namespace and memory limit without calling the API. Step 1: add a downwardAPI volume with three items. Step 2: mount it at /etc/podinfo. Step 3: read the files. Note that mem_limit is printed in bytes unless you set a divisor such as 1Mi.

yaml
volumes:
  - name: podinfo
    downwardAPI:
      items:
        - { path: name, fieldRef: { fieldPath: metadata.name } }
        - { path: namespace, fieldRef: { fieldPath: metadata.namespace } }
        - path: mem_limit
          resourceFieldRef: { containerName: app, resource: limits.memory, divisor: 1Mi }
# container: volumeMounts: [{ name: podinfo, mountPath: /etc/podinfo }]
# kubectl exec POD -- sh -c 'cat /etc/podinfo/*'

Quick reference

  • Declare in spec.volumes, mount per container in volumeMounts (names must match)
  • emptyDir lives on the node at /var/lib/kubelet/pods/UID/volumes/
  • emptyDir medium: Memory is tmpfs and counts against the memory limit
  • hostPath type DirectoryOrCreate creates the path; Directory requires it to exist
  • Every Pod's token lives at /var/run/secrets/kubernetes.io/serviceaccount
  • subPath mounts one file but never receives updates
  • kubectl explain pod.spec.volumes.projected.sources lists all source types

Common mistakes

  • Storing database data in emptyDir and losing it when the Pod is rescheduled.
  • Using hostPath for app data on a multi-node cluster.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1A container in a Pod crashes and restarts. What happens to files it wrote in an emptyDir?

Question 2

2An emptyDir uses medium: Memory and the app fills it with 300Mi. The container's memory limit is 256Mi. Likely result?

Question 3

3Which volume type is behind the service account token every Pod gets by default?

Question 4

4A hostPath volume uses type: Directory and the folder does not exist on the node. What happens?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Create a Pod with two busybox containers sharing an emptyDir at /shared. One writes the date every 5 seconds; read the file from the other.

  2. Exercise 2medium

    Run a Pod that mounts the node's /var/log read-only at /host-logs and lists the files there.

  3. Exercise 3hard

    Build one projected volume at /etc/bundle that holds Secret db (key password), ConfigMap app (key mode) and the Pod's labels from the downward API.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

What is the difference between a volume and a PersistentVolume?
A volume is declared inside one Pod and usually lives as long as the Pod. A PersistentVolume is a separate cluster object for durable storage that you attach to Pods through a claim.
Is hostPath safe to use?
Only for trusted system Pods or single-node labs. It gives the Pod access to the node's files and ties data to one node.
Where is emptyDir data stored?
On the node's disk under /var/lib/kubelet/pods, or in RAM if you set medium: Memory.

Go deeper

ShareXLinkedInWhatsApp