Sub topic 10
A Dockerfile that installs from the lock file
A lock file pins your Python packages. It does not pin the Python interpreter, the system libraries, or the operating system. A container image covers those layers. This chapter shows how to write a Dockerfile for an ML project that installs strictly from a hash-checked lock file, and how to avoid the errors that most often break such builds.
Prerequisites
This chapter assumes you can do the following:
- You can read a basic Dockerfile and know that
docker buildproduces an image anddocker runstarts a container from it. - You have a
requirements.lockgenerated withpip-compile --generate-hashes, as in the earlier chapters on lock files. - You know what a virtual environment is and why a lock file lists transitive dependencies.
Layer ordering, base image digests and GPU runtime details have their own chapters. This chapter touches them only where the Dockerfile needs them.
What the Dockerfile must guarantee
A Dockerfile for a reproducible ML project has three jobs:
- Start from a known operating system and Python version.
- Install exactly the packages in the lock file, and fail if anything differs.
- Add your code last, so code edits do not force a reinstall.
The lock file answers job 2. The base image answers job 1. The order of instructions answers job 3.
The Dockerfile
# In a real project, pin the base image by digest: python:3.11-slim@sha256:<digest>
FROM python:3.11-slim
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"]Each instruction creates a layer. The sections below explain the choices in order.
The base image
python:3.11-slim fixes the Python minor version and a minimal Debian userland. A tag such as 3.11-slim is a moving label. The maintainers republish it with security fixes and new patch releases, so the same tag can point to different contents next month. The comment at the top reminds you to pin by digest in a real project. The chapter on base image pinning covers this in detail.
The Python version matters because a lock file records packages for a specific interpreter. Wheels (prebuilt package files) are tagged by Python version and platform, and the hashes in the lock file refer to those exact files. If the container ran Python 3.12 while the lock was compiled under 3.11, pip could find no matching hashes for some packages and the install would fail.
Copying the lock file first
COPY requirements.lock .
RUN pip install --no-cache-dir --require-hashes -r requirements.lockDocker caches each layer and reuses it when the instruction and its inputs are unchanged. For COPY, the input is the content of the copied files. If requirements.lock is unchanged, Docker reuses the cached RUN pip install layer. Installing PyTorch can take minutes and download gigabytes, so this saves real time.
If you wrote COPY . . before the install, any edit to any source file would invalidate the cache and trigger a full reinstall.
The install flags
--require-hashesmakes pip reject any requirement that lacks a hash, and any downloaded file whose hash does not match. It also implies that every package must be pinned with==.--no-cache-dirstops pip from keeping downloaded files inside the image. The cache is useless in a layer and only makes the image larger.-r requirements.lockreads the fully resolved file, notrequirements.in.
In hash-checking mode pip does not resolve dependencies. It installs exactly what the file lists. If a transitive dependency is missing from the file, the install fails instead of silently fetching an unpinned version. That failure is the behavior you want.
Copying the code last
COPY src/ ./src/Your code changes on nearly every commit. Placing it after the install keeps the expensive layer cached across those commits.
The command
CMD ["python", "-m", "src.train"] uses the exec form (a JSON list). The process runs directly as the container's main process, so it receives signals such as SIGTERM from docker stop. The shell form would wrap it in /bin/sh -c and can swallow signals.
Build and run
docker build -t ml-train:dev .
docker run --rm --gpus all ml-train:devdocker build produces the image. docker run --rm starts a container and deletes it on exit. --gpus all exposes the host GPUs. It needs the NVIDIA driver and the NVIDIA Container Toolkit on the host. Without a GPU, drop the flag.
How the layers fit together
When a layer is invalidated, Docker rebuilds it and every layer after it. Frequently changing inputs belong at the bottom.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `Hashes are required in --require-hashes mode, but ... has none` | The lock was compiled without `--generate-hashes`, or edited by hand | Recompile with `pip-compile --generate-hashes` |
| `THESE PACKAGES DO NOT MATCH THE HASHES` | The file pip downloaded differs from the one locked. Often the container's platform or Python version differs from where you compiled | Compile the lock on the same Python version and platform as the image, or compile inside the container |
| `No matching distribution found` for a pinned version | No wheel for the image's Python version or CPU architecture | Align the Python version, or check that the package publishes a wheel for your architecture, such as `arm64` on Apple Silicon |
| Dependencies reinstall on every build | `COPY . .` appears before the install, or the build context changes the lock file | Copy only the lock file before the install |
| Build tries to compile a package from source and fails | No wheel is available and the slim image lacks a compiler | Prefer a version with a wheel. Install build tools only if you must, and note that they become part of your environment |
The platform trap
A lock file compiled on a Mac with Apple Silicon and installed in a linux/amd64 image can fail. Hashes are per file, and some packages ship different wheels per platform. The safest habit is to compile the lock in the same environment that will consume it. The chapter on combining lock files and containers builds on this.
Things the Dockerfile does not fix
- The slim image has few system libraries. Some packages need
libgomp1or similar. If you addapt-get install, combineupdateandinstallin oneRUNand clear/var/lib/apt/lists/*afterward. - The container runs as root by default. For shared machines, add a non-root user with
USER. - Add a
.dockerignorefile listing.git,data/,.venv/and model checkpoints. Without it,docker buildsends them to the daemon as build context, which slows builds and can leak large files into layers. - Large data and model weights usually do not belong in the image. Mount them as volumes or fetch them at run time, and version them separately.
Checking that the install is strict
You can test that hash checking is active. Add a bogus line or alter one hash in a copy of the lock file and build. The build should fail at the pip install step. If it succeeds, your install is not reading the file you think it is. Run this check once when you set up the project.
Exercise
A teammate changes one line in src/train.py and your CI build re-downloads all of PyTorch. The Dockerfile has COPY . . followed by RUN pip install --no-cache-dir --require-hashes -r requirements.lock. What is wrong, and how do you fix it?
Show answer
COPY . . copies the whole project, including src/train.py, before the install. Changing that file changes the input of the COPY layer, so Docker invalidates it and every later layer, including the install. Fix it by copying only requirements.lock first, running the install, and copying src/ afterward.
Exercise
Your build fails with "THESE PACKAGES DO NOT MATCH THE HASHES". You compiled the lock on a Mac laptop with Apple Silicon, and the image is linux/amd64. Give the likely cause and one way to fix it.
Show answer
Some packages publish different wheel files per platform, and the hashes in the lock refer to the wheels pip chose on the laptop. The image needs different wheels, so the hashes do not match. Recompile the lock in the same environment as the image, for example by running pip-compile --generate-hashes inside a container of the same base image and platform.