4.2.5.4 RUN Layer Generation
A focused guide to RUN Layer Generation, connecting core concepts with practical Docker and container operations.
RUN layer generation is the process by which each RUN instruction's executed command results in a new, discrete image layer, capturing exactly the filesystem changes that command produced relative to the state immediately before it ran.
One Layer Per RUN Instruction
Each RUN instruction in a Dockerfile produces its own separate layer, regardless of how many individual commands are chained together within that single instruction using shell operators.
RUN apt-get update && apt-get install -y curl && rm -rf /var/lib/apt/lists/*
Despite containing three separate commands joined with &&, this produces a single layer reflecting their combined, net effect.
Multiple RUN Instructions Produce Multiple Layers
Splitting the same work across separate RUN instructions instead produces a separate layer for each one, even if the combined effect on the final filesystem would be identical.
RUN apt-get update
RUN apt-get install -y curl
RUN rm -rf /var/lib/apt/lists/*
RUN apt-get update && apt-get install -y curl && rm -rf /var/lib/apt/lists/*
The first version produces three layers, with the cleanup layer doing nothing to reduce the size already committed by the earlier installation layer; the second produces one layer reflecting only the final, cleaned-up state.
Inspecting Generated Layers
The layers generated by each RUN instruction, and their individual sizes, can be inspected directly after a build.
docker history myapp:1.0
Why the Number of Layers Generated Matters
While Docker does not impose a strict practical limit on layer count for most use cases, unnecessarily fragmenting related operations across many separate RUN instructions can increase image size (since earlier layers' content cannot be reduced by later layers) and add minor overhead to layer management during builds and pulls.
docker images myapp
Why Understanding RUN Layer Generation Matters
A clear understanding of exactly how RUN instructions translate into layers is essential for writing a Dockerfile that produces an appropriately sized, efficiently structured image, rather than one fragmented into many small layers that collectively waste space on redundant, uncombined operations.