Volumes: files that outlive a container
Why container files vanish, and how to keep them.
cd ~/lab && curl -fsSLO https://secopslog.com/lab-files/k8s-fund/volumes.tar.gz && tar -xzf volumes.tar.gz, which creates ~/lab/volumes/. SHA-256: 1ead21ef091cd1c5a00dfdbff1fcf62a818446b84f19620491736a02891d2537Every container starts from its image, fresh. Anything it writes goes into a thin layer on top of the image, and when the container is replaced, that layer goes with it. In Docker you notice this when you remove a container. In Kubernetes it happens far more often, because the kubelet restarts a container every time it crashes or fails a liveness probe (lesson 13, Probes). A cache or a half-finished upload is gone after each restart.
A volume is a directory that belongs to the Pod instead of the container. Containers mount it, and it outlives any single container. Some volume types also outlive the Pod; those come in lesson 18, PersistentVolumes.
A file that vanishes
This Pod writes nowhere special. It has one volume, an emptyDir mounted at /cache, and its command exits on purpose when the file /tmp/stop appears, which stands in for a crash:
apiVersion: v1kind: Podmetadata:name: notesspec:containers:- name: appimage: busybox:1.38.0# runs until someone creates /tmp/stop, then exits so the kubelet restarts the containercommand: ["sh", "-c", "trap 'exit 0' TERM; until [ -f /tmp/stop ]; do sleep 1; done"]volumeMounts:- name: cachemountPath: /cachevolumes:- name: cacheemptyDir: {}
Two identical files: one in /tmp, which is part of the container, and one in /cache, the volume. Now make the container exit, run kubectl get pod notes every few seconds until RESTARTS shows 1 and READY shows 1/1, then read both files:
RESTARTS is 1, and the Pod kept its name. Inside, /cache/note.txt still says saved, but /tmp/note.txt is gone: No such file or directory. The restarted container got a fresh copy of the image, and with it a fresh /tmp. Notice that /tmp/stop disappeared too, which is why the container did not exit again straight away. The emptyDir was not touched, because it belongs to the Pod.
Where an emptyDir lives
An emptyDir is just a directory on the node, created when the Pod is placed there. You can find it by the node name and the Pod's unique ID:
The first command prints the node the Pod runs on and the Pod's ID. Inside that node, under /var/lib/kubelet/pods/, the Pod's ID, and volumes/kubernetes.io~empty-dir/cache, sits note.txt. (On kind a node is a container, so docker exec gets you onto it.) That directory is the volume. Because it is on the node's disk, a big emptyDir can fill that disk. You can cap it with sizeLimit, or set medium: Memory to keep it in RAM, where it counts against the container's memory limit.
Deleting the Pod deletes the emptyDir
Same file, same Pod name, but /cache is empty. The new Pod has a new ID, and its emptyDir was created empty. When a Pod is deleted, the kubelet deletes its emptyDir with it. That makes emptyDir the right choice for scratch space, caches and files shared between containers of one Pod, and the wrong choice for anything you need to keep. A Deployment replaces Pods all the time, during every rollout and every drain, so data in an emptyDir is lost far more often than people expect.
Volumes Kubernetes fills for you
Not every volume is for data a container writes. Some put information into a Pod. Every Pod already has one you did not ask for:
Besides cache there is kube-api-access- followed by a few random letters. Kubernetes adds it to every Pod. It is a projected volume holding a short-lived token, the API server's CA certificate and the namespace name, which lets the app talk to the API server as its service account. A projected volume combines several sources in one directory. Here is one that mixes a ConfigMap with facts about the Pod itself, using the downward API:
apiVersion: v1kind: ConfigMapmetadata:name: sitedata:site.conf: "listen 8080\n"---apiVersion: v1kind: Podmetadata:name: infolabels:app: infoteam: webspec:containers:- name: appimage: busybox:1.38.0command: ["sh", "-c", "trap 'exit 0' TERM; while true; do sleep 1; done"]volumeMounts:- name: all-in-onemountPath: /etc/inforeadOnly: truevolumes:- name: all-in-oneprojected: # several sources in one directorysources:- configMap:name: site- downwardAPI: # facts about the Pod itselfitems:- path: labelsfieldRef:fieldPath: metadata.labels
One directory, two files from two sources: site.conf from the ConfigMap, and labels written by the kubelet from the Pod's own labels. ConfigMap and Secret volumes, from lessons 11 and 12, work the same way. All of these last exactly as long as the Pod, and their content comes from the API server, so nothing is lost when the Pod goes.
hostPath: a warning
A hostPath volume mounts a directory of the node itself into the Pod:
# hostPath: a directory of the node itself. Read-only here, and still a bad idea for apps.apiVersion: v1kind: Podmetadata:name: hostspec:restartPolicy: Nevercontainers:- name: lookimage: busybox:1.38.0command: ["sh", "-c", "cat /node-etc/hostname; ls /node-etc/kubernetes"]volumeMounts:- name: node-etcmountPath: /node-etcreadOnly: truevolumes:- name: node-etchostPath:path: /etctype: Directory
Apply it and check kubectl get pod host until STATUS shows Completed, then read what it printed:
The Pod printed the hostname of the node it ran on, a worker, and listed /etc/kubernetes on that node, including kubelet.conf and the pki folder. Even read-only, that is a view into the machine running everything. With write access, a Pod could change node files and take over the node. hostPath is also tied to one node: if the Pod moves, its data stays behind. It is meant for system agents such as log collectors, not for apps, and many clusters block it with Pod Security admission.
Hands-on
1. Write a timestamp into the volume: kubectl exec notes -- sh -c 'date > /cache/stamp; cat /cache/stamp'.
2. Make the container exit: kubectl exec notes -- touch /tmp/stop.
3. Run kubectl get pod notes every few seconds until RESTARTS shows 1 and READY shows 1/1.
4. Read the timestamp again: kubectl exec notes -- cat /cache/stamp.
5. Clean up with kubectl delete -f notes.yaml -f info.yaml -f host.yaml, then check with kubectl get pods.
What you should see: step 1 prints the current date and time. In step 3 RESTARTS reaches 1 again, since this is the new notes Pod from the delete above. Step 4 prints exactly the timestamp from step 1. Step 5 deletes three Pods and the site ConfigMap, and kubectl get pods says No resources found in default namespace.
Remember
Files written inside a container are lost when the container restarts. An emptyDir survives container restarts but is deleted with its Pod. Keep hostPath for node agents, never for app data.
/data inside its container, with no volume. The container fails a liveness probe and is restarted. What happens to the uploads?/tmp/note.txt was gone./cache was empty after the Pod was recreated. The old directory went with the old Pod.host Pod could read /etc/kubernetes on its node.host Pod showed, though many clusters block it by policy.