3.1.2.1 Image Layer Creation
A focused guide to Image Layer Creation, connecting core concepts with practical Docker and container operations.
Image layer creation is the process that happens during docker build, where the daemon executes each Dockerfile instruction in a temporary container, captures the resulting filesystem changes as a new layer, and then discards that temporary container, leaving only the layer it produced behind.
The Build Process Step by Step
For each filesystem-affecting instruction, Docker starts from the current set of layers, runs the instruction inside a temporary container based on that state, and then commits whatever changed as a new, permanent layer.
FROM debian:bookworm-slim
RUN apt-get update && apt-get install -y curl
Building this produces one layer for the base image's contents, and a second layer capturing exactly the filesystem changes that resulted from running the apt-get commands — nothing more, nothing less.
Capturing Only What Changed
The layer creation process only captures the difference between the filesystem before and after the instruction ran, not the entire filesystem state, which is what keeps each individual layer's size proportional to what it actually changed.
docker history --no-trunc myapp:1.0
Each entry's reported size reflects only the incremental change that specific instruction introduced, not the cumulative size of the image up to that point.
Caching Layer Creation
If an instruction and the state it would operate on are unchanged from a previous build, Docker reuses the previously created layer rather than re-executing the instruction, which is the basis for Docker's build cache.
docker build -t myapp:1.0 .
docker build -t myapp:1.0 .
The second build, with no changes to the Dockerfile or build context, completes almost instantly, since every layer is reused directly from cache rather than recreated.
Why Understanding Layer Creation Matters
Knowing that each instruction is executed in isolation and committed as a discrete layer explains several otherwise surprising behaviors — for example, why deleting a file in a later RUN instruction does not reduce the image's size, since the file still exists, unmodified, in an earlier, already-committed layer beneath it.
RUN curl -o largefile.tar.gz https://example.com/largefile.tar.gz
RUN rm largefile.tar.gz
This produces an image that still contains the full size of largefile.tar.gz, because it was committed to a layer before being deleted in a separate, later layer.