Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 78 ยท Storage

Volumes

Understand Kubernetes volumes: emptyDir, hostPath, configMap, secret and projected volumes, ephemeral volumes, volumeMounts, subPath and how mount paths resolve.

A container's filesystem is disposable. When a container restarts, everything it wrote is gone, and two containers in the same pod cannot see each other's files by default. A Kubernetes volume fixes both problems: it is a directory, declared once at the pod level, that can be mounted into one or more containers. Some volumes live only as long as the pod; others point at storage that outlives it.

This lesson covers the volume types you will meet daily (emptyDir, hostPath, configMap, secret, projected, downwardAPI, generic ephemeral volumes), the volumeMounts that attach them, and the pitfalls around subPath and read-only mounts. Durable storage is the topic of PersistentVolumes and claims. If you know Docker volumes, you have the idea already (Docker volumes), but Kubernetes separates "what the volume is" from "where it is mounted". Real clusters are not available here, so manifests are read-only and the TryIts are Python stand-ins.

Declare once, mount many times

spec.volumes Names a volume and says what kind it is.
volumeMounts Each container picks a path for it.
Shared Containers in a pod can share one volume.

The volume name is the link between the two lists.

1 / 2

Volumes and mounts

A pod lists its volumes under spec.volumes, and every container lists where it wants them under volumeMounts:

YAML
apiVersion: v1
kind: Pod
metadata:
  name: demo
spec:
  volumes:
    - name: scratch
      emptyDir: {}
  containers:
    - name: writer
      image: busybox:1.37
      command: ["sh", "-c", "echo hello > /out/msg && sleep 3600"]
      volumeMounts:
        - name: scratch
          mountPath: /out
    - name: reader
      image: busybox:1.37
      command: ["sh", "-c", "sleep 5; cat /in/msg; sleep 3600"]
      volumeMounts:
        - name: scratch
          mountPath: /in
          readOnly: true

The two containers see the same files under different paths. Useful volumeMounts fields:

  • name: must match a volume in spec.volumes.
  • mountPath: the directory inside the container. Anything the image already has there is hidden by the mount.
  • readOnly: true: the container cannot write, even if the volume is writable.
  • subPath: mount only one subdirectory or file of the volume.

emptyDir: scratch space

An emptyDir starts empty when the pod is assigned to a node and is deleted when the pod leaves that node. It survives container restarts (a crash does not erase it), but not pod deletion or rescheduling. Typical uses: a cache, a work directory for a batch step, or a handoff between an init container and the main container (init containers).

YAML
volumes:
  - name: cache
    emptyDir:
      sizeLimit: 500Mi
  - name: fast-scratch
    emptyDir:
      medium: Memory

With medium: Memory the directory is a RAM-backed tmpfs: very fast, but the bytes count against the container's memory limit. If you exceed sizeLimit on disk, the kubelet evicts the pod.

hostPath: a directory on the node

hostPath mounts a file or directory from the node's filesystem:

YAML
volumes:
  - name: node-logs
    hostPath:
      path: /var/log
      type: Directory

The optional type makes the kubelet check what it finds (Directory, DirectoryOrCreate, File, FileOrCreate, Socket, and a few more). It is legitimate for node-level agents such as log collectors and monitoring daemons (DaemonSets). For normal applications it is a trap: the data is tied to one node, so a rescheduled pod finds an empty directory somewhere else, and a writable hostPath gives a container a path to attack the node. Pod Security forbids it in the baseline profile for good reason. Use a PersistentVolumeClaim instead.

configMap and secret volumes

A ConfigMap or Secret can be mounted as a directory in which every key becomes a file:

YAML
volumes:
  - name: app-config
    configMap:
      name: web-config
      items:
        - key: nginx.conf
          path: conf.d/site.conf
      defaultMode: 0444
  - name: tls
    secret:
      secretName: web-tls
      defaultMode: 0400
containers:
  - name: web
    image: nginx:1.29
    volumeMounts:
      - name: app-config
        mountPath: /etc/nginx
      - name: tls
        mountPath: /etc/tls
        readOnly: true

Without items, every key is projected as a file named after the key. With items, only the listed keys appear, at the paths you choose. defaultMode sets permissions (written in octal in YAML; JSON would need decimal).

Unlike environment variables, these files update after the object changes, typically within a minute or so, via atomic symlink swaps. There is one major exception: a subPath mount never receives updates. If your app reloads config on file change, mount the whole directory.

projected: several sources, one directory

A projected volume merges several sources into one directory, which is handy when an app expects a single config folder:

YAML
volumes:
  - name: bundle
    projected:
      sources:
        - configMap:
            name: web-config
            items:
              - key: app.ini
                path: app.ini
        - secret:
            name: db-credentials
            items:
              - key: password
                path: secrets/db-password
        - downwardAPI:
            items:
              - path: meta/labels
                fieldRef:
                  fieldPath: metadata.labels
        - serviceAccountToken:
            path: token
            expirationSeconds: 3600
            audience: api

The supported sources are configMap, secret, downwardAPI, serviceAccountToken and clusterTrustBundle. Every file path in the combined volume must be unique; two sources writing the same path is an error. Short-lived service account tokens (service accounts) are delivered exactly this way.

Ephemeral volumes

A generic ephemeral volume looks like a PVC but is created and deleted with the pod. It gives you scratch space from a real storage class (bigger or faster than the node's root disk) without managing claims by hand:

YAML
volumes:
  - name: scratch
    ephemeral:
      volumeClaimTemplate:
        spec:
          accessModes: ["ReadWriteOnce"]
          storageClassName: fast-ssd
          resources:
            requests:
              storage: 20Gi

When the pod is deleted, Kubernetes deletes the claim it created, and with a Delete reclaim policy the disk goes too (StorageClasses). Inline CSI ephemeral volumes also exist for drivers that support them, such as the secrets store driver.

How mount paths resolve

The kubelet checks a few things before starting a container: every volumeMounts.name must exist in spec.volumes, each container may mount only one thing at a given mountPath, and paths must be absolute. When mounts are nested (/data and /data/logs), the kubelet sets up the shorter path first, so the deeper mount sits on top. The stand-in below applies these checks and prints the resulting mount order.

Python Validate volume mounts and mount order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The shallow path /data is mounted before /data/logs, so the hostPath directory covers only the logs subdirectory of the emptyDir. The broken container shows three of the validation errors you would see from the API server or in pod events.

Merging a projected volume

The second stand-in builds the file tree of a projected volume from several sources and rejects path collisions, the way the real volume plugin does.

Python Build the file tree of a projected volume

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

subPath and its trade-offs

subPath lets you drop a single file into a directory that already has contents, without hiding the rest:

YAML
volumeMounts:
  - name: app-config
    mountPath: /etc/app/settings.ini
    subPath: settings.ini

It solves the "mounting hides everything in this directory" problem, but at a price: the file is a bind mount to one specific inode, so a ConfigMap update never reaches the container, and a pod using subPath needs a restart to see new config. Prefer mounting a dedicated directory and pointing the app at it.

Which volume should you use?

  • Share files between containers or keep a cache: emptyDir.
  • Configuration files: configMap; credentials: secret; both in one folder: projected.
  • Pod metadata as files: downwardAPI.
  • Temporary but large or fast storage: generic ephemeral volume.
  • Data that must survive: a PersistentVolumeClaim.
  • Node-level agents only: hostPath.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens to the contents of an emptyDir when one container in the pod crashes and restarts?

    An emptyDir lives as long as the pod stays on the node. Container restarts do not affect it, but deleting or rescheduling the pod does.
  2. 2. Why is hostPath a poor choice for application data?

    A rescheduled pod may land on another node and see an empty directory, and a writable hostPath is a way for a compromised container to reach the host.
  3. 3. A ConfigMap is mounted with subPath. The ConfigMap is edited. What does the container see?

    subPath mounts are bind mounts of a fixed file and never receive updates. Mount the whole directory if the app should see changes.
  4. 4. Which statement about projected volumes is correct?

    Projected volumes combine configMap, secret, downwardAPI, serviceAccountToken and clusterTrustBundle sources, and a path collision between sources is an error.

Summary

  • Volumes are declared in spec.volumes and attached with volumeMounts; the volume name links them.
  • emptyDir survives container restarts but not the pod; medium: Memory uses RAM and counts toward the memory limit.
  • hostPath is node-bound and risky; keep it for node-level agents.
  • configMap and secret volumes turn keys into files that update over time, except through subPath.
  • projected volumes merge several sources; generic ephemeral volumes give pod-lifetime storage from a StorageClass.
  • Each mount path must be absolute, unique per container, and refer to an existing volume.

Next: PersistentVolumes and Claims