Sub topic 11
Ordering Docker Layers for Fast ML Rebuilds
Assume you know basic Docker commands, Python packaging, and how an ML project is trained from a command such as python -m src.train. This chapter focuses on Docker’s build cache, not on writing a complete training application.
How layer caching works
A Dockerfile is processed from top to bottom. Most instructions create an image layer. Docker can reuse a layer when the instruction and its relevant inputs have not changed.
A source-code edit should not force Docker to download and install every Python dependency again. To achieve that, put stable inputs before frequently changing inputs.
| Layer input | How often it changes | Recommended position |
|---|---|---|
| Base image | Occasionally | First |
| Dependency lock file | Occasionally | Before source code |
| Application source | Often | Near the end |
| Training data | Often or externally managed | Usually outside the image |
If a layer changes, Docker usually rebuilds that layer and all following layers. Therefore, placing COPY src/ ./src/ before dependency installation makes every source edit invalidate the installation layer.
A cache-friendly Dockerfile
This example assumes the project contains requirements.lock and a src/ directory.
FROM python:3.11-slim
WORKDIR /app
# This layer changes only when the dependency set changes.
COPY requirements.lock .
RUN pip install --no-cache-dir --require-hashes -r requirements.lock
# Source code changes often, so copy it after dependency installation.
COPY src/ ./src/
CMD ["python", "-m", "src.train"]When src/train.py changes, Docker can reuse the base-image and dependency layers. It only needs to copy the new source and recreate the final image layer.
When requirements.lock changes, Docker correctly reruns pip install. The new lock file is part of the cache key, so Docker does not reuse an installation made from an older dependency set.
Keep the build context small with a .dockerignore file. This prevents local virtual environments, datasets, Git metadata, and experiment outputs from being sent to the Docker daemon.
.venv/
__pycache__/
.git/
data/
runs/
*.pycSeparating stable and changing files
Copy only the files required by each build step. For example, if a package manager needs pyproject.toml as well as a lock file, copy those files before installing. Do not copy the entire repository at that point.
COPY pyproject.toml requirements.lock ./
RUN pip install --no-cache-dir --require-hashes -r requirements.lock
COPY src/ ./src/A cache speeds up rebuilding, but it must not replace dependency verification. The lock file and its hashes still determine what installation is allowed to use.
Exercise
Why should COPY src/ ./src/ come after the dependency installation step?
Show answer
Source code changes then invalidate only the later source layer, allowing Docker to reuse the dependency installation layer.