Sub topic 10
A Dockerfile That Installs from the Lock File
Assume you know basic Docker commands, Python packaging, and how a lock file is generated. This chapter uses a requirements.lock file created by pip-compile --generate-hashes. The same layering ideas apply to lock files from other tools.
A Docker image is a packaged filesystem and command definition. A container is a running instance of that image. The Dockerfile describes how to build the image. Installing dependencies during the build makes every container from that image use the same resolved package versions.
Install the lock file before application code
FROM python:3.11-slim
WORKDIR /app
# Copy only the dependency lock file first.
COPY requirements.lock .
# Install exactly the hash-checked packages.
RUN pip install --no-cache-dir --require-hashes -r requirements.lock
# Copy application code after dependencies.
COPY src/ ./src/
CMD ["python", "-m", "src.train"]The FROM instruction selects the starting image. The WORKDIR instruction sets the working directory for later commands. COPY places files from the build context into the image.
The RUN instruction installs packages while the image is being built. The --require-hashes option makes pip reject a package that has no accepted hash or whose downloaded file does not match a recorded hash. This prevents an unexpected package artifact from entering the image.
The project must contain src/train.py, or another importable src.train module, for the final command to work.
Use layer caching deliberately
Docker stores the result of each instruction in a layer. If an instruction and its inputs have not changed, Docker can reuse that layer during a later build.
The lock file changes less often than application code. Copying it and installing dependencies before copying src/ means a source-code edit usually reuses the expensive installation layer. Changing requirements.lock invalidates that layer and causes dependencies to be installed again.
A .dockerignore file should exclude files that are not needed in the build context:
.git
.venv
__pycache__
*.pyc
data
runsThis reduces the amount of data sent to the Docker builder and helps avoid accidentally copying local environments or large training artifacts.
Build and run the image
Run these commands from the directory containing the Dockerfile, requirements.lock, and src/ directory:
docker build -t ml-train:dev .
docker run --rm ml-train:devThe dot is the build context. Docker can copy only files inside that context. The --rm option removes the stopped container after the command finishes.
Exercise
Why should application source be copied after the lock-file installation step?
Show answer
Source changes then invalidate only later layers, so Docker can reuse the dependency-installation layer and rebuild faster.