In this lesson, you will learn how Docker manages the distinction between the static image files you download and the dynamic, temporary files created when your container runs.
The Foundation: Read-Only Image Layers
When you build an image from a Dockerfile, Docker creates a stack of immutable, read-only layers. Each layer represents a set of filesystem changes (like adding a library or a configuration file). Because these layers are read-only, they are safe to share across multiple containers. If ten containers use the same base image, they all point to the exact same physical files on your disk. Docker uses a Union File System to "merge" these layers so that your application sees a single, unified view of the files.
The Extension: The Container Writable Layer
While image layers are fixed, your application often needs to perform tasks that change the filesystem—like writing logs, creating temporary cache files, or modifying a database.
When you start a container, Docker places a thin writable layer (also called the "container layer") on top of the stack of read-only image layers.
- Copy-on-Write: If your application needs to modify a file that exists in an image layer, Docker first copies that file up into the writable layer and makes the change there. The original file in the image remains untouched.
- Ephemerality: This writable layer is tied strictly to the lifecycle of the container. If you
docker stopanddocker rmthe container, the writable layer—and all the changes stored within it—is permanently deleted.
Visualizing the Stack
Think of it like this:
+---------------------------+
| Writable Layer | <--- Changes stored here (Ephemeral)
+---------------------------+
| Read-Only Image Layer 2 |
+---------------------------+
| Read-Only Image Layer 1 | <--- Base files (Permanent)
+---------------------------+
Because the writable layer is discarded upon deletion, it is a poor place for persistent data. This is why we use Volumes or Bind Mounts when we need to save information beyond the container's short lifespan!
Key Takeaway: Image layers provide a static, read-only template for your application, while the writable layer acts as a temporary scratchpad that captures runtime changes and disappears when the container is removed.