Skip to main content

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

  1. Each Dockerfile instruction creates a layer FROM, RUN, COPY, and others -> a new layer (read-only).
  2. 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.
  3. OverlayFS combines them through the lowerdir/upperdir mechanisms The basic scheme:
ComponentWhat it is
lowerdirthe image layers (read-only, one on top of another)
upperdirthe layer with changes (while the container is running)
mergedthe final, mounted file system
  1. 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

AdvantageBecause of what
Space savingslayers are reused by different images
Fast buildslayer cache, previously created layers are not rebuilt
Immutabilitylower 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 ready
Premium

A concise answer to help you respond confidently on this topic during an interview.