Volumes inside a pod
Volumes that live and die with the pod. emptyDir scratch space, projected files, the downward API, OCI images as data, per-pod claims, and why hostPath is a node-level risk.
Shows the lesson one block at a time. Arrow keys step, number keys jump to a scene, and Escape returns to the page where you were.
A container’s filesystem is the image plus a writable layer that disappears when the container is replaced. Anything that must outlive a crash, be shared with a second container, or arrive from outside the image needs a volumeA directory, declared in the pod spec and backed by some source, that the kubelet makes available to the pod’s containers.. This lesson covers the volumes whose lifetime is the pod’s: they are created when the pod lands on a node and go away with it. Storage that outlives pods belongs to persistent volumes, the next step in this track.
Reconcile, in 8 scenes
Volume versus mount
A pod spec separates what storage exists from where containers see it. spec.volumes declares each volume once, with a name and a source: emptyDir, configMap, projected, image and so on. Each container then lists volumeMounts that attach a volume by name at a mountPath. One volume can be mounted by several containers, at different paths, with different options:
readOnly: truemakes the mount read-only for that container, even if another container writes to the same volume. Sub-mounts under it stay writable unlessrecursiveReadOnly: Enabledis also set, GA since Kubernetes 1.33 and dependent on the node’s kernel (5.12 or later) and container runtime supporting it.subPathmounts one file or subdirectory of the volume instead of its root, andsubPathExprbuilds that path from environment variables, for example a per-pod directory named after the pod.
The API server checks the wiring when the pod is created. A mount that names a volume the pod does not declare is rejected outright:
kubectl apply -f bad-mount.yaml
The Pod "bad-mount" is invalid: spec.containers[0].volumeMounts[0].name: Not found: "cache"
The kubelet sets up every volume before it starts any container. A volume that cannot be set up, such as one backed by a missing ConfigMap or Secret, leaves the whole pod in ContainerCreating with events that name the volume.
emptyDir
An emptyDirA volume that starts empty when the pod is assigned to a node and is deleted when the pod leaves that node. volume is scratch space owned by the pod. Every container in the pod sees the same directory, and it survives container crashes and restarts. It is deleted when the pod is removed from the node for any reason: deletion, eviction, or the node failing.
apiVersion: v1
kind: Pod
metadata:
name: scratch
spec:
containers:
- name: writer
image: busybox:1.37
command: ["sh", "-c", "while true; do date >> /work/log.txt; sleep 5; done"]
volumeMounts:
- name: work
mountPath: /work
- name: reader
image: busybox:1.37
command: ["sh", "-c", "sleep 3600"]
volumeMounts:
- name: work
mountPath: /work
readOnly: true
volumes:
- name: work
emptyDir:
sizeLimit: 500Mi
Typical uses are a cache, a sort or build area too large for memory, checkpoints for a long computation, and a hand-off between an init container and the main container. That hand-off replaces the gitRepo volume: its in-tree driver was turned off by default in Kubernetes 1.33 and is permanently disabled from 1.36, so clone the repository in an init container into an emptyDir, or run a sync sidecar.
By default the volume lives on the node’s disk and draws from the node’s ephemeral storage, the same pool as container logs and writable layers. sizeLimit bounds it: when the volume grows past the limit, the kubelet evicts the pod. The limit is a ceiling, not a reservation, so the volume can run out sooner if other consumers fill the disk. For the scheduler to account for the space, set ephemeral-storage requests on the containers.
With medium: Memory, the kubelet mounts a tmpfs instead, and reads and writes run at memory speed. The price is that every file written counts against the memory limit of the container that wrote it.
Projected volumes
A projected volumeA volume that maps several sources (Secrets, ConfigMaps, downward API fields, service account tokens and more) into one directory. combines sources that would otherwise need a volume each. The sources are secret, configMap, downwardAPI, serviceAccountToken, clusterTrustBundle and podCertificate; ClusterTrustBundles and pod certificates are GA in Kubernetes 1.37. Every pod already has one: the service account admission controller injects a projected volume that combines a token, the cluster’s CA bundle and the pod’s namespace.
kubectl get pod web -o jsonpath='{.spec.volumes[*].name}'
cache kube-api-access-smpvl
kubectl get pod web -o jsonpath='{.spec.volumes[1].projected.sources[*]}'
{"serviceAccountToken":{"expirationSeconds":3607,"path":"token"}} {"configMap":{"items":[{"key":"ca.crt","path":"ca.crt"}],"name":"kube-root-ca.crt"}} {"downwardAPI":{"items":[{"fieldRef":{"apiVersion":"v1","fieldPath":"metadata.namespace"},"path":"namespace"}]}}kubectl exec web -- ls /var/run/secrets/kubernetes.io/serviceaccount
ca.crt namespace token
Your own projected volume follows the same shape:
volumes:
- name: runtime
projected:
defaultMode: 0440
sources:
- configMap:
name: app-config
- secret:
name: app-tls
items:
- key: tls.key
path: tls/tls.key
- downwardAPI:
items:
- path: labels
fieldRef:
fieldPath: metadata.labels
- serviceAccountToken:
audience: vault
expirationSeconds: 3600
path: vault-token
Two details differ from the standalone volume types. A secret source takes name, not the secretName of a secret volume. And defaultMode exists only at the projected level, not per source, with a per-item mode to override it. As with the standalone types, the Secrets and ConfigMaps a projected volume reads must be in the pod’s own namespace.
The serviceAccountToken source exists only inside a projected volume. It writes a token from the TokenRequest API that is bound to the pod and to an audience, by default the API server. expirationSeconds defaults to one hour and cannot be under ten minutes. The kubelet refreshes the file before the token expires, and the API server stops accepting the token once the pod is deleted. A system such as Vault or a cloud identity service can verify that token, which makes it a credential the pod never had to be given.
Downward API
The downward APIThe way a pod’s own metadata and resource settings reach its containers, as environment variables or as files. answers a container’s questions about itself: its pod name, namespace, labels, node, IP and resource limits. There are two forms. Environment variables use fieldRef or resourceFieldRef under env[].valueFrom; a downwardAPI volume, or a downwardAPI projected source, writes the same fields as files.
| Field | Environment variable | Volume file |
|---|---|---|
metadata.name, metadata.namespace, metadata.uid | Yes | Yes |
One label or annotation, metadata.labels['app'] | Yes | Yes |
All labels or all annotations, metadata.labels | No | Yes |
spec.nodeName, spec.serviceAccountName | Yes | No |
status.podIP(s), status.hostIP(s) | Yes | No |
requests and limits for cpu, memory, ephemeral-storage | Yes | Yes |
Saved as dapi.yaml, this pod reads three of those fields into environment variables:
apiVersion: v1
kind: Pod
metadata:
name: dapi-demo
spec:
containers:
- name: app
image: busybox:1.37
command: ["sh", "-c", "sleep 3600"]
env:
- name: POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
- name: NODE_NAME
valueFrom:
fieldRef:
fieldPath: spec.nodeName
- name: POD_IP
valueFrom:
fieldRef:
fieldPath: status.podIP
kubectl apply -f dapi.yaml
pod/dapi-demo created
kubectl wait --for=condition=Ready pod/dapi-demo
pod/dapi-demo condition met
kubectl exec dapi-demo -- printenv POD_NAME
dapi-demo
kubectl exec dapi-demo -- printenv NODE_NAME
kx-worker2
kubectl exec dapi-demo -- printenv POD_IP
10.244.2.2
Resource fields let a runtime size itself to its container: a JVM or a worker pool can read limits.memory with divisor: 1Mi and get a plain number of mebibytes. When the container has no limit, the value falls back to the node’s allocatable amount, which is rarely what the application wants.
volumes:
- name: podinfo
downwardAPI:
items:
- path: labels
fieldRef:
fieldPath: metadata.labels
- path: mem_limit_mib
resourceFieldRef:
containerName: app
resource: limits.memory
divisor: 1Mi
The difference between the forms is the familiar one from ConfigMaps. The kubelet rewrites volume files when labels or annotations change; environment variables keep the values from container start, and a subPath mount of a downward API file never updates.
Image volumes (GA 1.36)
An image volume mounts the contents of an OCI image or artifact, read-only, without running it. It is GA in Kubernetes 1.36. It separates data from code: a model, a dataset or a set of static assets ships through the registry, with the registry’s versioning, signing and caching, while the serving container stays small and generic.
apiVersion: v1
kind: Pod
metadata:
name: classifier
spec:
containers:
- name: server
image: busybox:1.37
command: ["sh", "-c", "sleep 3600"]
volumeMounts:
- name: model
mountPath: /models
volumes:
- name: model
image:
reference: registry.example.com/models/sentiment:2.1
pullPolicy: IfNotPresent
reference behaves like a container’s image field, including pull secrets. pullPolicy takes Always, Never or IfNotPresent, and defaults to Always for a :latest tag and IfNotPresent otherwise. The kubelet resolves the reference when the pod starts. A pull failure blocks the containers from starting and is retried with the usual volume backoff, so a large model adds its pull time to the pod’s startup. The content is fixed for the pod’s life: pushing a new image under the same tag reaches only pods created afterwards. subPath mounts of image volumes work from Kubernetes 1.33. The node’s container runtime must support image volumes.
Generic ephemeral volumes
Sometimes scratch space must be larger or faster than a node’s local disk, or come from a storage system with snapshots or encryption. A generic ephemeral volumeA per-pod PersistentVolumeClaim, created from a template in the pod spec and deleted with the pod. provides a real provisioned volume with pod lifetime:
apiVersion: v1
kind: Pod
metadata:
name: builder
spec:
containers:
- name: build
image: busybox:1.37
command: ["sh", "-c", "sleep 3600"]
volumeMounts:
- name: workspace
mountPath: /workspace
volumes:
- name: workspace
ephemeral:
volumeClaimTemplate:
metadata:
labels:
app: builder
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 10Gi
The ephemeral volume controller creates a claim named <pod>-<volume>, here builder-workspace, with the pod as its owner. When the pod is deleted, the garbage collector deletes the claim, and the StorageClass’s reclaim policy decides what happens to the volume behind it. Anyone who can create pods can create these claims indirectly, but ResourceQuota on claims and storage still applies.
The claim goes through the normal provisioning path, so the usual storage rules apply:
- A StorageClass must resolve. Without
storageClassName, the claim uses the class marked default. If none is, the claim staysPending, and so does the pod. Some managed distributions ship no default class, so check withkubectl get storageclassinstead of assuming one. - Bind late. A class with
volumeBindingMode: WaitForFirstConsumerprovisions the volume after the pod is scheduled, in the pod’s zone. WithImmediate, a volume can land in a zone the pod cannot run in, and the pod staysPendingwith avolume node affinity conflictevent. - Access modes are for matching. They describe what a volume supports, and Kubernetes does not use them for write protection once mounted, with two exceptions.
ReadWriteOncePod, GA since Kubernetes 1.29 and supported only for CSI volumes, is enforced by the scheduler: one pod in the whole cluster.ReadWriteOnceon attachable block storage is limited to one node at attach time, and a second node’s pod waits inContainerCreatingwith aMulti-Attacherror. A slow detach or the node’s attachment limit look the same. - Change it in place. If the class sets
allowVolumeExpansion, raising the claim’s request grows the volume, and Kubernetes expands ext4 and xfs filesystems online while the pod runs. A VolumeAttributesClass, GA in Kubernetes 1.34, changes performance settings such as IOPS on a bound claim when the CSI driver supports it.
kubectl get storageclass
NAME PROVISIONER RECLAIMPOLICY VOLUMEBINDINGMODE ALLOWVOLUMEEXPANSION AGE standard (default) rancher.io/local-path Delete WaitForFirstConsumer false 60s
hostPath
A hostPath volume mounts a file or directory from the node into the pod. It is the one volume type here that exposes the node’s own filesystem, and that is the problem:
- The node holds the kubelet’s credentials and the container runtime’s socket. A pod that can reach either can start privileged containers or escape to the node.
- Nodes differ, so identical pods behave differently depending on where they land.
hostPathusage is not counted as ephemeral storage, so writes can fill a node’s disk with no limit applying.- Admission rules that allow only some host paths hold only if the mounts are read-only.
A type field adds a check before mounting: Directory, File, Socket, CharDevice and BlockDevice require the path to exist as that kind, and DirectoryOrCreate and FileOrCreate create it. Legitimate uses are node agents, usually DaemonSets that read /var/log or talk to a device, and those belong in namespaces with an explicit exemption.
The Pod Security StandardsThree policy levels (privileged, baseline, restricted) that Pod Security Admission enforces per namespace through labels. handle the rest. baseline forbids hostPath entirely. restricted goes further and allows only configMap, csi, downwardAPI, emptyDir, ephemeral, persistentVolumeClaim, projected and secret volumes. Material that relies on PodSecurityPolicy for this predates Kubernetes 1.25, which removed it; Pod Security Admission replaced it.
kubectl get namespace apps --show-labels
NAME STATUS AGE LABELS apps Active 30s kubernetes.io/metadata.name=apps,pod-security.kubernetes.io/enforce=baseline
kubectl apply -f node-logs.yaml
Error from server (Forbidden): error when creating "node-logs.yaml": pods "node-logs" is forbidden: violates PodSecurity "baseline:latest": hostPath volumes (volume "varlog")
Coming from Docker and Compose
Compose’s storage options map onto these volume types, and a few details are worth correcting on the way. The default file is compose.yaml; Compose also reads docker-compose.yml for backward compatibility. The top-level version key is obsolete and only triggers a warning. The commands are docker compose up, down, logs, exec and build, from the Compose V2 plugin. Pin images to a supported major, such as postgres:18, not an old tag.
# compose.yaml
services:
web:
image: nginx:1.31
ports:
- "8080:80"
tmpfs:
- /var/cache/nginx
volumes:
- uploads:/srv/uploads
db:
image: postgres:18
expose:
- "5432"
volumes:
uploads:
ports: ["80"] with only a container port does not keep a port internal: it publishes it on a host port the engine picks. For other services only, use expose, or nothing, since services on one Compose network reach each other anyway. docker volume inspect reports a volume’s driver, mount point, labels, options and scope, not the containers using it; docker ps -a --filter volume=uploads answers that. On Docker Desktop for Mac, bind mounts use VirtioFS by default, with gRPC FUSE as the alternative, and Docker’s documentation does not say whether the old cached and delegated flags have any effect under VirtioFS.
| Compose | Kubernetes |
|---|---|
tmpfs | emptyDir with medium: Memory and a sizeLimit |
| Anonymous volume or container scratch | emptyDir |
| Named volume | A PersistentVolumeClaim, or a generic ephemeral volume when the data is per-pod |
| Bind mount of a host path | hostPath, forbidden under baseline; use a ConfigMap, Secret or image volume for files |
configs and secrets | ConfigMap and Secret volumes |
kubectl --context kind-kx apply -f scratch.yamlkubectl --context kind-kx wait --for=condition=Ready pod/scratchkubectl --context kind-kx exec scratch -c reader -- tail -n 3 /work/log.txtkubectl --context kind-kx exec scratch -c reader -- touch /work/from-readerkubectl --context kind-kx apply -f builder.yamlkubectl --context kind-kx get pvc builder-workspacekubectl --context kind-kx delete pod scratch builderkubectl --context kind-kx get pvc
For your own kind cluster kx: copy a command and paste it into your terminal. Run in the simulator runs the same command in this page's simulated cluster instead; nothing on this page touches your machine. Save the scratch and builder pods from this lesson as scratch.yaml and builder.yaml first. The reader sees the writer's lines but cannot write to its read-only mount, and builder-workspace disappears once its pod is deleted.
Actual state
Check your understanding
Your first answer to each check is the one that counts. After a miss you can answer again; passing every check reconciles the lesson.
Lesson not yet reconciled
Desired: 4 objectives, 0 metReconciled: 4 of 4 objectives met
- Share scratch data between containers with emptyDir and bound its size. (not yet met)
- Project ConfigMaps, Secrets, downward API fields and service account tokens into one directory. (not yet met)
- Mount an OCI image as a read-only volume, GA in Kubernetes 1.36. (not yet met)
- Explain why hostPath is a security risk and which Pod Security Standards level forbids it. (not yet met)
Pass every check above to reconcile this lesson.
Every check has passed, so the desired state is met. First-try accuracy: 0 of 5. This lesson's review cards are in your queue.
Practice
Put this lesson to work on the simulated cluster. Everything runs in your browser, with nothing to install.
Changed since the notes
This lesson draws on an earlier set of study notes. Where the documentation contradicts a claim in them, qualifies it or has moved past it, the claim is listed here with the corrected statement and the source it was checked against.
Show 16 corrections
The notes saidA compose file is named docker-compose.yml by default
CorrectedThe default is compose.yaml (preferred) or compose.yml. docker-compose.yaml and docker-compose.yml are still read for backward compatibility.
Sourcedocs.docker.com/compose/intro/compose-application-model
The notes saiddocker-compose up / down / logs / exec / build
CorrectedUse the Compose V2 plugin:
docker compose up/down/logs/exec/build.The notes saidSynchronization strategies (cached, delegated, or the newer VirtioFS)
CorrectedVirtioFS is the default file sharing implementation in Docker Desktop for Mac, with gRPC FUSE as the alternative. Official docs don't confirm whether the cached/delegated flags do anything under VirtioFS.
Sourcedocs.docker.com/desktop/settings-and-maintenance/settings
The notes saidimage: postgres:15
Correctedpostgres:15 is several major versions behind. PostgreSQL 19 was at Beta 4 on 2026-09-24, and whether it reached GA by 2026-11-19 is unconfirmed. Pin to the newest GA major.
Sourcepostgresql.org/about/news/postgresql-19-beta-4-released-3386
The notes saidThe basic structure of a compose file includes a version declaration
CorrectedThe top-level
versionkey is obsolete. It is informative only and triggers a warning, and Compose always validates against the newest schema.Sourcedocs.docker.com/reference/compose-file/version-and-name
The notes saidYou can specify just a container port to expose it to other containers without publishing it to the host
Corrected
ports: ["80"]publishes the port on a host port the runtime picks automatically. For internal-only access, useexposeor omit ports.The notes saiddocker volume inspect shows which containers use the volume
CorrectedIts output is CreatedAt, Driver, Labels, Mountpoint, Name, Options and Scope. To find containers that use a volume, run
docker ps -a --filter volume=<name>.The notes saidDefault StorageClass 'marked with an annotation' makes simple PVCs work without choosing storage
CorrectedKubernetes behaviour is unchanged, but EKS clusters created on 1.30 or later ship the gp2 StorageClass without the storageclass.kubernetes.io/is-default-class annotation (upgraded clusters keep it), and EKS Auto Mode creates no StorageClass at all. A PVC without storageClassName stays Pending until you annotate a class as default, for example a gp3 class with provisioner ebs.csi.aws.com (add-on) or ebs.csi.eks.amazonaws.com (Auto Mode). The EBS CSI chart/add-on exposes defaultStorageClass.enabled (false by default). The AWS 1.30 release note itself rolled off the docs when 1.30 left support; the linked secondary sources record it.
The notes saidEFS throughput 'bursting (throughput scales with size) and provisioned'
CorrectedEFS has three throughput modes: Elastic (the recommended default for new file systems; scales automatically, billed per data read/written), Provisioned and Bursting. Switching to Provisioned or changing the amount locks some changes for 24 hours.
Sourcedocs.aws.amazon.com/efs/latest/ug/performance.html#throughput-modes
The notes said'Installing the EBS CSI Driver is required for EBS-backed PVCs… EKS add-on management simplifies installation'
CorrectedRequired on non-Auto Mode clusters (EKS add-on aws-ebs-csi-driver; driver latest v1.68.1). EKS Auto Mode includes block storage and does not need the add-on; its provisioner is ebs.csi.eks.amazonaws.com and you must create the StorageClass yourself. The add-on supports EKS Pod Identity from v1.26.0-eksbuild.1 as well as IRSA. IAM policy choices: AmazonEBSCSIDriverPolicyV2 (tag-based scoping), AmazonEBSCSIDriverEKSClusterScopedPolicy (cluster-scoped), or AmazonEBSCSIDriverPolicy (no tag restrictions).
The notes saidChanging EBS performance requires new StorageClass/volumes
CorrectedVolumeAttributesClass is GA in Kubernetes 1.34 (locked on from 1.36). The EBS CSI driver implements ControllerModifyVolume (since driver v1.19.0), so changing a bound PVC's volumeAttributesClassName modifies type, IOPS or throughput of the live volume with no new StorageClass or data copy. EKS Auto Mode docs describe migrating from the deprecated annotation-based volume-modifier-for-k8s to VolumeAttributesClass. EBS Elastic Volumes limits still apply.
The notes saidReadWriteOncePod access mode
CorrectedState the qualifiers: ReadWriteOncePod is GA since Kubernetes 1.29 (feature gate removed 1.31) and works only with CSI volumes; the scheduler enforces single-pod use. The EBS CSI driver supports it.
Sourcekubernetes.io/docs/concepts/storage/persistent-volumes#access-modes
The notes said'For EBS, expansion requires stopping I/O briefly while the filesystem is resized'
CorrectedEBS Elastic Volumes resize attached volumes online, and Kubernetes performs online filesystem expansion (ext4/xfs) while the pod runs; no I/O stop is needed. Note that the 'one modification per volume per 6 hours' rule in the suspected correction is itself stale: since 2026-01-15 EBS allows up to four modifications per volume in a rolling 24-hour window, and the EBS limitations list no longer carries the 6-hour wait.
The notes said'EBS volumes can only attach to one instance at a time, so they support only ReadWriteOnce'
CorrectedA simplification. io1/io2 volumes support Multi-Attach within one AZ, and the EBS CSI driver exposes it as ReadWriteMany for volumeMode: Block only (not filesystem mode); the application must coordinate writes (I/O fencing) to avoid corruption. ReadWriteOncePod is also supported. Shared filesystem RWX belongs to EFS.
The notes said'Pods stuck waiting for volume attachment often indicate zone mismatches'
CorrectedA zone mismatch surfaces at scheduling: the pod stays Pending with a 'volume node affinity conflict' event, and volumeBindingMode: WaitForFirstConsumer avoids it by provisioning in the pod's zone. Pods stuck in ContainerCreating waiting for attachment usually point to a Multi-Attach error (volume still attached to another node), a slow detach, or the node's EBS attachment limit.
Sourcekubernetes.io/docs/concepts/storage/storage-classes#volume-binding-mode
The notes said'Access modes are capabilities, not restrictions'
CorrectedPartly right: Kubernetes uses access modes to match PVCs to PVs and they do not enforce write protection once mounted. But ReadWriteOncePod is enforced (one pod cluster-wide), and ReadWriteOnce on attachable block storage such as EBS is effectively constrained to one node at attach time (Multi-Attach error).
Sourcekubernetes.io/docs/concepts/storage/persistent-volumes#access-modes
Every correction across the guide, by note and topic.
Sources
Checked against kubernetes.io and AWS documentation for Kubernetes 1.37 on .
- kubernetes.io/docs/concepts/storage/volumes
- kubernetes.io/docs/reference/storage/volume-types
- kubernetes.io/docs/concepts/storage/ephemeral-volumes
- kubernetes.io/docs/concepts/storage/projected-volumes
- kubernetes.io/docs/concepts/workloads/pods/downward-api
- kubernetes.io/docs/tasks/inject-data-application/downward-api-volume-expose-pod-information
- kubernetes.io/docs/tasks/configure-pod-container/image-volumes
- kubernetes.io/docs/concepts/configuration/manage-resources-containers
- kubernetes.io/docs/concepts/storage/ephemeral-storage
- kubernetes.io/docs/concepts/storage/persistent-volumes
- kubernetes.io/docs/concepts/storage/storage-classes
- kubernetes.io/docs/concepts/security/pod-security-standards
- docs.aws.amazon.com/eks/latest/userguide/create-storage-class.html
- docs.aws.amazon.com/eks/latest/userguide/workloads-add-ons-available-eks.html
- github.com/kubernetes-sigs/aws-ebs-csi-driver/blob/master/docs/modify-volume.md
- github.com/kubernetes-sigs/aws-ebs-csi-driver/blob/master/docs/multi-attach.md
- docs.aws.amazon.com/ebs/latest/userguide/ebs-modify-volume.html
- docs.aws.amazon.com/efs/latest/ug/performance.html
- docs.docker.com/compose/intro/compose-application-model
- docs.docker.com/reference/compose-file/version-and-name
- docs.docker.com/reference/compose-file/services
- docs.docker.com/reference/cli/docker/container/ls
- docs.docker.com/desktop/settings-and-maintenance/settings
Volumes inside a pod
↓ ↑ step, 1 to 8 scene, Esc leave