Volumes: files that outlive a container

Why container files vanish, and how to keep them.

Beginner15 min · lesson 17 of 21
Lesson files
The scripts, test data and local test servers this lesson uses, exactly as they ran on the lab machine (4 files, 1 KB): volumes.tar.gz. The lab VM shares no folders with your computer, so fetch them inside the VM: 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: 1ead21ef091cd1c5a00dfdbff1fcf62a818446b84f19620491736a02891d2537

Every 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:

notes.yaml
apiVersion: v1
kind: Pod
metadata:
name: notes
spec:
containers:
- name: app
image: busybox:1.38.0
# runs until someone creates /tmp/stop, then exits so the kubelet restarts the container
command: ["sh", "-c", "trap 'exit 0' TERM; until [ -f /tmp/stop ]; do sleep 1; done"]
volumeMounts:
- name: cache
mountPath: /cache
volumes:
- name: cache
emptyDir: {}
ubuntu@secopslog-k8s:~/lab/volumes · Kubernetes 1.37
$ kubectl apply -f notes.yaml && kubectl wait --for=condition=Ready pod/notes --timeout=60s
pod/notes created pod/notes condition met
$ kubectl exec notes -- sh -c 'echo saved > /tmp/note.txt; echo saved > /cache/note.txt; ls -l /tmp/note.txt /cache/note.txt'
-rw-r--r-- 1 root root 6 Nov 11 09:24 /cache/note.txt -rw-r--r-- 1 root root 6 Nov 11 09:24 /tmp/note.txt

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:

ubuntu@secopslog-k8s:~/lab/volumes · Kubernetes 1.37
$ kubectl exec notes -- touch /tmp/stop
$ kubectl get pod notes
NAME READY STATUS RESTARTS AGE notes 1/1 Running 1 (2s ago) 4s
$ kubectl exec notes -- cat /cache/note.txt /tmp/note.txt
cat: can't open '/tmp/note.txt': No such file or directory saved command terminated with exit code 1

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:

ubuntu@secopslog-k8s:~/lab/volumes · Kubernetes 1.37
$ kubectl get pod notes -o jsonpath='{.spec.nodeName}{" "}{.metadata.uid}{"\n"}'
lab-worker 8a8b5abb-4936-46eb-a551-3a07567325f4
$ docker exec "$(kubectl get pod notes -o jsonpath='{.spec.nodeName}')" ls /var/lib/kubelet/pods/"$(kubectl get pod notes -o jsonpath='{.metadata.uid}')"/volumes/kubernetes.io~empty-dir/cache
note.txt

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

ubuntu@secopslog-k8s:~/lab/volumes · Kubernetes 1.37
$ kubectl delete pod notes && kubectl apply -f notes.yaml && kubectl wait --for=condition=Ready pod/notes --timeout=60s
pod "notes" deleted from default namespace pod/notes created pod/notes condition met
$ kubectl exec notes -- ls -la /cache
total 8 drwxrwxrwx 2 root root 4096 Nov 11 09:25 . drwxr-xr-x 1 root root 4096 Nov 11 09:25 ..

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:

ubuntu@secopslog-k8s:~/lab/volumes · Kubernetes 1.37
$ kubectl get pod notes -o jsonpath='{range .spec.volumes[*]}{.name}{"\n"}{end}'
cache kube-api-access-pp6nb

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:

info.yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: site
data:
site.conf: "listen 8080\n"
---
apiVersion: v1
kind: Pod
metadata:
name: info
labels:
app: info
team: web
spec:
containers:
- name: app
image: busybox:1.38.0
command: ["sh", "-c", "trap 'exit 0' TERM; while true; do sleep 1; done"]
volumeMounts:
- name: all-in-one
mountPath: /etc/info
readOnly: true
volumes:
- name: all-in-one
projected: # several sources in one directory
sources:
- configMap:
name: site
- downwardAPI: # facts about the Pod itself
items:
- path: labels
fieldRef:
fieldPath: metadata.labels
ubuntu@secopslog-k8s:~/lab/volumes · Kubernetes 1.37
$ kubectl apply -f info.yaml && kubectl wait --for=condition=Ready pod/info --timeout=60s
configmap/site created pod/info created pod/info condition met
$ kubectl exec info -- sh -c 'ls /etc/info; cat /etc/info/site.conf /etc/info/labels; echo'
labels site.conf listen 8080 app="info" team="web"

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:

host.yaml
# hostPath: a directory of the node itself. Read-only here, and still a bad idea for apps.
apiVersion: v1
kind: Pod
metadata:
name: host
spec:
restartPolicy: Never
containers:
- name: look
image: busybox:1.38.0
command: ["sh", "-c", "cat /node-etc/hostname; ls /node-etc/kubernetes"]
volumeMounts:
- name: node-etc
mountPath: /node-etc
readOnly: true
volumes:
- name: node-etc
hostPath:
path: /etc
type: Directory

Apply it and check kubectl get pod host until STATUS shows Completed, then read what it printed:

ubuntu@secopslog-k8s:~/lab/volumes · Kubernetes 1.37
$ kubectl apply -f host.yaml
pod/host created
$ kubectl get pod host && kubectl logs host
NAME READY STATUS RESTARTS AGE host 0/1 Completed 0 4s lab-worker kubelet.conf manifests pki

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.

Quick check
01An app writes uploads to /data inside its container, with no volume. The container fails a liveness probe and is restarted. What happens to the uploads?
Incorrect — The Pod stays, but the container's own files do not; /tmp/note.txt was gone.
Incorrect — A container restart is enough to lose them.
Incorrect — The kubelet adds no volume for app data.
Correct — The restarted container starts from a fresh copy of the image.
02You delete a Pod that has an emptyDir, and its Deployment creates a new one. What is in the new Pod's emptyDir?
Incorrect — The new Pod has a new ID and a new, empty directory.
Correct — /cache was empty after the Pod was recreated. The old directory went with the old Pod.
Incorrect — The old directory is deleted with the Pod, whatever the node.
Incorrect — An emptyDir hides whatever the image has at that path and starts empty.
03Why is a hostPath volume a bad home for an app's data?
Incorrect — Speed is not the issue; it is a plain directory on the node.
Incorrect — hostPath data stays on the node through restarts.
Correct — The data stays on one node, and the host Pod could read /etc/kubernetes on its node.
Incorrect — It still works, as the host Pod showed, though many clusters block it by policy.

Related