TExcelTAD
Home › Kubernetes › Volumes

Volumes

A container's filesystem is ephemeral: when the container restarts, everything it wrote is gone, and containers in the same Pod can't see each other's files. Volumes fix both problems. A volume is declared once at the Pod level (spec.volumes) and mounted into one or more containers (volumeMounts).

yaml
apiVersion: v1
kind: Pod
metadata:
  name: report
spec:
  volumes:
    - name: scratch
      emptyDir: {}                       # lives as long as the Pod
    - name: cache
      emptyDir:
        medium: Memory                   # tmpfs in RAM
        sizeLimit: 256Mi
    - name: settings
      configMap: {name: report-config}
  containers:
    - name: worker
      image: ghcr.io/acme/report:1.4
      volumeMounts:
        - {name: scratch, mountPath: /work}
        - {name: cache, mountPath: /cache}
        - {name: settings, mountPath: /etc/report, readOnly: true}

Volume types at a glance

Type Lifetime Typical use
emptyDir Pod (survives container restarts) Scratch space, sharing files between containers
configMap, secret, downwardAPI, projected Pod, content from the API Config files, credentials, Pod metadata
persistentVolumeClaim Independent of the Pod Databases, uploads, anything that must survive
hostPath The node Node agents (log collectors). Dangerous for normal apps
ephemeral Pod, but provisioned like a PVC Large scratch space from a storage class
image (beta) Pod Mount an OCI image's content read-only
CSI drivers (csi:) Varies Cloud disks, secret stores, NFS

Lifetimes, modelled

The key question for every volume is what survives what. This model runs a container restart and then a Pod replacement:

python · try it yourself
class Pod:
    def __init__(self, name, pvc_store):
        self.name = name
        self.container_fs = {}       # the container's writable layer
        self.empty_dir = {}          # emptyDir: bound to this Pod
        self.pvc = pvc_store         # PVC: shared storage outside the Pod

    def write_everywhere(self, key, value):
        self.container_fs[key] = value
        self.empty_dir[key] = value
        self.pvc[key] = value

    def restart_container(self):
        self.container_fs = {}

    def show(self, when):
        print(f"{when:28} container={self.container_fs} emptyDir={self.empty_dir} pvc={self.pvc}")

disk = {}                            # a persistent disk
pod = Pod("db-0", disk)
pod.write_everywhere("orders", 42)
pod.show("after write")
pod.restart_container()
pod.show("after container restart")
pod = Pod("db-0 (replacement)", disk)
pod.show("after Pod replaced")
after write                  container={'orders': 42} emptyDir={'orders': 42} pvc={'orders': 42}
after container restart      container={} emptyDir={'orders': 42} pvc={'orders': 42}
after Pod replaced           container={} emptyDir={} pvc={'orders': 42}

Sharing files between containers

emptyDir is the glue for multi-container Pods. Here a git-sync sidecar keeps a directory updated and nginx serves it:

yaml
spec:
  volumes:
    - name: site
      emptyDir: {}
  initContainers:
    - name: git-sync
      image: registry.k8s.io/git-sync/git-sync:v4.4.0
      restartPolicy: Always
      args: ["--repo=https://github.com/acme/site", "--root=/git", "--period=60s"]
      volumeMounts: [{name: site, mountPath: /git}]
  containers:
    - name: nginx
      image: nginx:1.27
      volumeMounts: [{name: site, mountPath: /usr/share/nginx/html, readOnly: true}]

Mount paths and subPath

A mount hides whatever the image had at that path. To place a single file into an existing directory, mount with subPath:

yaml
volumeMounts:
  - name: settings
    mountPath: /etc/nginx/conf.d/default.conf   # just this file
    subPath: default.conf

How mounts overlay the image's filesystem, as a model:

python · try it yourself
image_files = {
    "/etc/nginx/nginx.conf": "image",
    "/etc/nginx/conf.d/default.conf": "image",
    "/etc/nginx/mime.types": "image",
}
volume = {"default.conf": "volume", "extra.conf": "volume"}

def mount_dir(fs, path, vol):
    fs = {p: v for p, v in fs.items() if not p.startswith(path + "/")}   # the directory is hidden
    fs.update({f"{path}/{name}": src for name, src in vol.items()})
    return fs

def mount_subpath(fs, path, vol, key):
    fs = dict(fs)
    fs[path] = vol[key]
    return fs

print("mount whole volume at /etc/nginx/conf.d:")
for p, src in sorted(mount_dir(image_files, "/etc/nginx/conf.d", volume).items()):
    print(f"  {p:34} ({src})")
print("mount at /etc/nginx (oops):")
for p, src in sorted(mount_dir(image_files, "/etc/nginx", volume).items()):
    print(f"  {p:34} ({src})")
print("subPath default.conf:")
for p, src in sorted(mount_subpath(image_files, "/etc/nginx/conf.d/default.conf", volume, "default.conf").items()):
    print(f"  {p:34} ({src})")
mount whole volume at /etc/nginx/conf.d:
  /etc/nginx/conf.d/default.conf     (volume)
  /etc/nginx/conf.d/extra.conf       (volume)
  /etc/nginx/mime.types              (image)
  /etc/nginx/nginx.conf              (image)
mount at /etc/nginx (oops):
  /etc/nginx/default.conf            (volume)
  /etc/nginx/extra.conf              (volume)
subPath default.conf:
  /etc/nginx/conf.d/default.conf     (volume)
  /etc/nginx/mime.types              (image)
  /etc/nginx/nginx.conf              (image)

Mounting at /etc/nginx removed nginx.conf and mime.types, a classic way to break a container.

The downward API

A Pod can learn about itself through downwardAPI volumes or env vars: its name, namespace, labels, and its own resource limits.

yaml
env:
  - name: POD_NAME
    valueFrom: {fieldRef: {fieldPath: metadata.name}}
  - name: NODE_NAME
    valueFrom: {fieldRef: {fieldPath: spec.nodeName}}
  - name: MEMORY_LIMIT
    valueFrom: {resourceFieldRef: {resource: limits.memory}}

Tip: For data that must outlive the Pod, don't use emptyDir or hostPath: use a PersistentVolumeClaim (next lesson).

Test yourself

Does data in an emptyDir survive a container restart?

  1. No
  2. Yes, it lives as long as the Pod
  3. Only with medium: Memory
  4. Only on the control plane

What happens to the image's files at a path where a volume is mounted?

  1. They are merged
  2. They are hidden by the mount
  3. They are copied into the volume
  4. They are deleted from the image

Which volume type should a database use for its data?

  1. emptyDir
  2. hostPath
  3. persistentVolumeClaim
  4. configMap