Sub topic 1
Why container data disappears
A container's files live only as long as the container does. This chapter shows where that data lives, when it is lost, and why Kubernetes needs a separate storage model.
Prerequisites
You should already know the following:
- Pods, Deployments, and namespaces.
- How to apply YAML manifests with
kubectl. - That a container starts from an image.
Where container files live
A container image is a stack of read-only layers. When the container starts, the runtime adds one thin writable layer on top. Every file the process creates or changes goes into that layer.
The writable layer belongs to one container instance. It is not shared and it is not backed up. When the instance is removed, the layer is removed with it.
When the data is lost
Three common events discard the writable layer:
- Container restart. The kubelet restarts a crashed container with a fresh layer built from the image.
- Pod deletion. Deleting a Pod, or replacing it during a rollout, removes its containers.
- Rescheduling. A Deployment creates a replacement Pod, often on another node. Files on the old node do not follow it.
See it happen
This Pod appends a timestamp to a file, prints the file, and exits after 30 seconds. The default restartPolicy of Always makes the kubelet start it again.
apiVersion: v1
kind: Pod
metadata:
name: ephemeral-demo
spec:
containers:
- name: app
image: busybox:1.36
command: ["sh", "-c", "date >> /tmp/log.txt; cat /tmp/log.txt; sleep 30"]Apply it, wait about a minute, and read the logs:
kubectl apply -f ephemeral-demo.yaml
kubectl get pod ephemeral-demo
kubectl logs ephemeral-demoThe RESTARTS column increases. Each run prints exactly one line, even though the earlier runs also appended a line. The file starts empty every time, because each restart gets a new writable layer. Clean up with kubectl delete pod ephemeral-demo.
Why this is a feature
Disposable containers are what let Kubernetes replace, scale, and reschedule workloads freely. Stateless services such as web frontends gain from this design.
Databases, upload stores, and message queues need their data to outlive any single container or Pod. Kubernetes handles this by attaching storage that has its own lifecycle, separate from the container. The next chapter introduces Pod volumes and volume mounts, the first step in that direction.
Exercise
A Deployment's Pod writes uploaded files to /var/uploads inside its container. The node reboots and the Pod is recreated on a different node. Are the files still there, and why?
Show answer
No. The files were in the container's writable layer on the old node. The replacement Pod starts a new container from the image with an empty layer, and the old node's layer is not carried over. Keeping the files requires storage that exists independently of the container, such as a PersistentVolume.