Sub topic 11
Ordering layers for fast rebuilds
This chapter assumes you can read a basic Dockerfile and have a hash-pinned lock file, such as requirements.lock from pip-compile. It covers how Docker decides to reuse work, how to order instructions so a code edit does not reinstall PyTorch, and the cases where the cache hides problems.
How the build cache decides
An image is a stack of layers. Most Dockerfile instructions (RUN, COPY, ADD) produce one layer. Before running an instruction, the builder checks whether it already has a layer for the same step. The check uses:
- The text of the instruction.
- The layer below it.
- For
COPYandADD, a checksum of the copied file contents. Modification times do not count.
If everything matches, the builder reuses the layer and prints CACHED. If anything differs, it rebuilds that layer. It then rebuilds every layer after it, because each later layer depends on the one below.
The consequence is simple. Put instructions that change rarely at the top and instructions that change often at the bottom.
A slow ordering and a fast one
This ordering is common in ML repositories and it is slow:
FROM python:3.11-slim
WORKDIR /app
COPY . .
RUN pip install --no-cache-dir --require-hashes -r requirements.lock
CMD ["python", "-m", "src.train"]COPY . . copies the whole repository, so editing one line in src/train.py changes that layer's checksum. The pip install layer sits below it, so it reruns. For a project with PyTorch, that means downloading and unpacking gigabytes after every edit.
This is the ordering from the earlier Dockerfile chapter, with a system-package layer added at the top:
# In a real project, pin the base image by digest: python:3.11-slim@sha256:<digest>
FROM python:3.11-slim
# Changes rarely: OS libraries that wheels expect at runtime
RUN apt-get update \
&& apt-get install -y --no-install-recommends libgomp1 \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
# Copy only the lock file first so this layer is reused until dependencies change
COPY requirements.lock .
RUN pip install --no-cache-dir --require-hashes -r requirements.lock
# Application code changes often, so copy it last
COPY src/ ./src/
CMD ["python", "-m", "src.train"]Now a code edit invalidates only COPY src/ and the layers after it. The expensive install layer is reused as long as requirements.lock is byte-for-byte the same.
| Layer | Typical change frequency | Cost to rebuild |
|---|---|---|
| Base image | Months, when you bump the digest | Pull of a few hundred MB |
| System packages | Rarely | Seconds to a minute |
| Lock file and install | When you update dependencies | Minutes, often gigabytes |
| Source code | Many times per day | Seconds |
Seeing the cache work
Build twice, then change only source code, and read the output:
docker build -t ml-train:dev .
docker build -t ml-train:dev .
echo "# edit" >> src/train.py
docker build -t ml-train:dev .The second build should mark every step CACHED. The third should rerun only the COPY src/ step and anything after it. If the pip install step reruns after a code-only edit, something above it changed. Look for a COPY that is too broad or an instruction that embeds a changing value.
Keep the build context small
Docker sends the build context (the directory you pass to docker build) to the builder before any layer is evaluated. In an ML repository the context can contain datasets, checkpoints and notebooks. Sending those slows every build. If you ever write COPY . ., they also invalidate the cache whenever they change.
Add a .dockerignore file next to the Dockerfile:
.git
.venv
__pycache__/
*.pyc
data/
checkpoints/
runs/
*.ipynbIgnoring paths you never copy is still worthwhile because it shrinks the context transfer. Ignoring paths that a broad COPY would otherwise pick up also protects the cache.
Where the cache can mislead you
Stale system packages. Docker does not know that the Debian package index has changed. A cached RUN apt-get update && apt-get install ... layer is reused until its instruction text changes. Always run apt-get update and apt-get install in the same RUN. If they are separate, a cached update layer can leave install using an outdated index. To pick up security updates, rebuild with docker build --pull --no-cache.
Unpinned installs are cached too. A RUN pip install numpy layer is reused even if a new NumPy has been released, so the cache hides drift. The result depends on when the cache was last populated. The lock file closes this gap because the content of requirements.lock is part of the cache key. When it changes, the install reruns with exactly the pinned versions.
Any change to the lock file invalidates the install layer. This includes a changed comment or a reordered line. Regenerate the lock file only when you mean to change dependencies. Otherwise every contributor's build repeats the full install.
Fresh CI runners have no cache. A new virtual machine starts with an empty cache, so every CI build is a full build. Export and import the cache with BuildKit:
docker buildx build \
--cache-from type=registry,ref=registry.example.com/ml-train:buildcache \
--cache-to type=registry,ref=registry.example.com/ml-train:buildcache,mode=max \
-t ml-train:dev .Replace registry.example.com/ml-train with your own registry path. The cache only speeds up the build. It never changes what the build produces, because the lock file and base digest decide that.
Caching downloads when the lock changes
The layer cache is all or nothing. When the lock file changes by one package, the whole install layer reruns and downloads everything again. A BuildKit cache mount keeps pip's download cache between builds without storing it in the image:
# syntax=docker/dockerfile:1
FROM python:3.11-slim
WORKDIR /app
COPY requirements.lock .
RUN --mount=type=cache,target=/root/.cache/pip \
pip install --require-hashes -r requirements.lock
COPY src/ ./src/
CMD ["python", "-m", "src.train"]Remove --no-cache-dir here, since it would stop pip from using the mount. Hash checking still applies to every file pulled from the cache, so the mount does not weaken verification. The cache mount lives on the builder host and is not part of the image, so it does not reduce image size and it is not available on a fresh CI runner unless you restore it.
Checklist
- Put the base image and system packages first.
- Copy only the lock file, then install from it.
- Copy source code last, and only the directories you need.
- Keep a
.dockerignorethat excludes data, checkpoints and virtual environments. - Combine
apt-get updateandapt-get installin oneRUN. - Confirm the order by changing one source file and checking that only the last layers rebuild.
Exercise
A teammate edits one line in src/train.py, rebuilds, and the pip install step runs again and downloads PyTorch. The Dockerfile has COPY . . on the line before RUN pip install --require-hashes -r requirements.lock. Give two changes that fix it, and say what each one does.
Show answer
First, copy only requirements.lock before the install, then run pip install, then copy src/ afterward. The install layer's cache key then depends only on the lock file's contents, so a code edit no longer invalidates it. Second, add a .dockerignore that excludes data, checkpoints, .git and virtual environments. This shrinks the build context and stops unrelated files from changing the checksum of any broad COPY. The first change fixes the cause. The second prevents the same problem from returning through other copied files.
Exercise
Why can a cached RUN pip install numpy layer produce a different environment from a fresh build, and why does installing from a lock file avoid that?
Show answer
The cache key is the instruction text and the layer below it. It does not include what PyPI currently serves, so the cached layer keeps the NumPy version from whenever it was built, while a fresh build gets the newest one. With a lock file, requirements.lock is copied in by COPY and its content checksum is part of the cache key. The versions are fixed by that file, so a cached build and a fresh build install the same packages.