In this lesson, you will learn how Union File Systems (UnionFS) allow Docker to stack independent, read-only layers into a single, unified view of a container’s directory.
The Power of Stacking
Imagine you are building a house using transparent plastic sheets. Each sheet has a different piece of furniture drawn on it. If you stack these sheets on top of each other, you see a fully furnished room. In Docker, these sheets are your image layers.
Each time you run a command in a Dockerfile (like RUN, COPY, or ADD), Docker creates a new, immutable read-only layer. When you start a container, the Union File System mounts these layers together. To the application inside, it looks like one single, standard directory structure. It doesn't know there are multiple "sheets" underneath; it only sees the finished product.
How it Looks Under the Hood
If you have a base layer with an operating system and a second layer that adds a specific application file, the UnionFS merges them. If both layers define a file with the same name, the top-most layer "masks" the one beneath it.
You can visualize this structure using the docker image history command:
# View the layers that make up your image
docker image history <image_name>
When you run this, you will see a list of commands. Each line represents a layer. Because these layers are read-only, they are incredibly efficient—if you have five different images that all share the same "Ubuntu base" layer, Docker only stores that base layer on your disk once, sharing it across all those images.
The "Unified" View
When a container starts, Docker adds one final, thin writable layer on top of these read-only image layers. Any changes you make while the container is running (like creating a log file or editing a config) happen in this top writable layer. The original image layers underneath remain untouched, which is exactly why containers are so lightweight and easy to discard.
Key Takeaway: UnionFS creates a unified view of your filesystem by stacking immutable read-only layers and overlaying them with a single writable layer, allowing for efficient storage and rapid container startup.