Sub topic 2
Pod volumes and volume mounts
This chapter assumes you can write a Pod manifest and apply it with kubectl. It also assumes you know that a container's filesystem is lost when the container is replaced. Here you will learn how a Pod declares storage and how containers attach to it. PersistentVolumes build on this same mechanism.
Two parts: volumes and mounts
A Pod defines storage in two places.
spec.volumesdeclares a volume. It has a name and a type.spec.containers[].volumeMountsattaches a declared volume to a path inside one container.
The two are linked only by the volume name. One volume can be mounted into several containers, each at a different path.
emptyDir: scratch space for the Pod
An emptyDir volume starts empty when the Pod is scheduled to a node. It lives as long as the Pod stays on that node.
- It survives a container crash and restart, because the Pod is unchanged.
- It is deleted when the Pod is deleted or moved to another node.
This makes it good for caches, temporary files, and sharing data between containers in one Pod. It is not durable storage.
apiVersion: v1
kind: Pod
metadata:
name: shared-pod
spec:
containers:
- name: writer
image: busybox:1.36
command: ["sh", "-c", "while true; do date >> /cache/out.txt; sleep 5; done"]
volumeMounts:
- name: scratch
mountPath: /cache
- name: reader
image: busybox:1.36
command: ["sh", "-c", "until [ -f /in/out.txt ]; do sleep 1; done; tail -f /in/out.txt"]
volumeMounts:
- name: scratch
mountPath: /in
readOnly: true
volumes:
- name: scratch
emptyDir: {}Apply it, then run kubectl logs shared-pod -c reader. You should see the timestamps the writer produces.
By default an emptyDir uses the node's disk. Setting emptyDir.medium: Memory uses RAM instead, which is faster but counts against the container's memory limit. You can cap the size with sizeLimit. A Pod that exceeds it is evicted.
Common errors
- Name mismatch. A
volumeMountsentry whosenamehas no matching entry involumesis rejected when you apply the manifest. - Hidden image files. Mounting a volume over a directory that already holds image content hides that content. Mount to a new path, or use
subPathto mount one subdirectory. - Writing to a read-only mount. With
readOnly: true, writes fail with "Read-only file system". - Expecting persistence. Deleting the Pod erases an
emptyDir. If data must outlive the Pod, you need a PersistentVolume, which later chapters cover.
Exercise
A container in a Pod crashes and Kubernetes restarts it. The Pod stays on the same node. Is data in an emptyDir volume lost? What if the Pod is deleted and recreated?
Show answer
The data is kept after the container restart, because the emptyDir belongs to the Pod and not to the container. If the Pod is deleted and recreated, the data is lost, because a new Pod gets a new, empty emptyDir.