How does Docker merge layers in an image?
Docker merges layers using union filesystem mechanisms (OverlayFS, AUFS, and others). Each layer is a separate read-only piece of the file system, and when an image is built these layers are logically "stacked" on top of each other, forming a single visible root-fs for the container.
How this works step by step
- Each Dockerfile instruction creates a layer
FROM,RUN,COPY, and others -> a new layer (read-only). - Layers are not merged physically Docker does not copy the contents of each layer into the next one. Instead, it uses a union-mount that makes them a single directory tree.
- OverlayFS combines them through the
lowerdir/upperdirmechanisms The basic scheme:
| Component | What it is |
|---|---|
lowerdir | the image layers (read-only, one on top of another) |
upperdir | the layer with changes (while the container is running) |
merged | the final, mounted file system |
- When a file changes - CoW (copy-on-write) If the container changes a file from a lower layer, Docker copies it into the upper layer and the edit happens there, without touching the base layers.
What this gives you
| Advantage | Because of what |
|---|---|
| Space savings | layers are reused by different images |
| Fast builds | layer cache, previously created layers are not rebuilt |
| Immutability | lower layers are read-only and do not get corrupted |
The main idea for middle level
Docker does not "glue" layers into one physical layer. It mounts them on top of each other using OverlayFS, and changes in the container happen only in the top writable layer, using CoW.
If you want, I can add the difference between OverlayFS and AUFS or break down this same process at the level of the system directories (/var/lib/docker/overlay2).
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.