How does Docker build an image from a Dockerfile, and what role do layers and the build cache play?
Each instruction is one build step that produces a layer, cached by instruction and input; on a rebuild unchanged steps come from the cache, and everything after the first changed step is rebuilt.
During docker image build, Docker works through the instructions in order (the output counts them as steps 1/3, 2/3, …). Filesystem-changing instructions like FROM and RUN execute in a temporary intermediate container; the result is saved as a snapshot, a new layer, and stored in the cache. Metadata instructions (ENV, CMD, EXPOSE, LABEL) only change the image's configuration.
On the next build Docker compares each step with the cache:
- If the instruction (and, for
COPY/ADD, the copied files) is unchanged, the cached layer is reused. That is fast. - At the first changed step the cache is invalidated, and that step and every one after it are executed again.
Two practical consequences:
- Order for speed. Put rarely changing steps (installing system packages) at the top and frequently changing ones (copying your source code) at the bottom.
- Combine what belongs together. A cached
RUN apt-get updatelayer can go stale, which is why update and install go into oneRUNline.docker build --no-cacheforces a full rebuild.
* Everything from the first changed step down is rebuilt. *
Go deeper:
Docker Docs: Docker build cache — how layers are cached and how to order a Dockerfile for it.
Docker Docs: Build cache invalidation — the exact rules for when a cached layer is reused.