Sub topic 15
When to capture the environment in a container
This chapter assumes you have read the earlier chapters on virtual environments, dependency pinning, and headless execution. You should be able to create a .venv, freeze a requirements.txt, and run a notebook with jupyter nbconvert --execute or papermill. It also assumes basic command-line comfort. You do not need prior Docker experience, but you should know that a container is a packaged, isolated process.
What a pinned environment does not capture
A virtual environment plus a pinned requirements.txt fixes the Python packages. It leaves several things outside your control:
- The Python interpreter itself.
requirements.txtlists packages, not the interpreter. Python 3.10 and 3.12 can give different results or fail to install the same pins. - System libraries. Packages such as
numpy,scipy,geopandas, andpsycopgrely on compiled code (BLAS, GDAL, libpq, OpenSSL). The same wheel can behave differently against different system libraries. - The operating system and CPU architecture. A pin that installs on Linux x86-64 may have no wheel on macOS ARM or Windows. Floating-point results can differ slightly between CPU types.
- Non-Python tools. R, Pandoc, LaTeX, Graphviz, and command-line programs your notebook calls are not in
requirements.txt. - Fonts and locale. Plots can render with different fonts. Sorting and date parsing can depend on locale settings.
A container packages the user-space operating system, system libraries, interpreter, and Python packages into one image. Anyone running that image gets the same user-space software, whatever their host machine looks like.
How a container differs from a virtual machine and a venv
A container shares the host's kernel, so it starts in seconds and is small compared with a virtual machine. It does not include its own kernel and does not emulate hardware.
| Approach | Captures | Does not capture | Typical cost |
|---|---|---|---|
| Virtual environment + pinned file | Python packages | Interpreter, system libraries, OS | Very low |
| Conda environment with lock file | Packages, interpreter, many native libraries | Host kernel, some system tools | Low to medium |
| Container image | User-space OS, system libraries, interpreter, packages | Host kernel, CPU architecture | Medium |
| Virtual machine | Whole OS including kernel | Physical hardware | High |
The comparison shows why a container is often the next step after pinning. It closes most of the gap that pinning leaves, without the weight of a full virtual machine.
When a container is worth adding
Adding a container has a cost: someone has to write and maintain the image definition, and your readers need a container runtime. Add one when a concrete problem justifies it. Common cases:
- Native dependencies cause trouble. If installation instructions include
apt installorbrew installsteps, those steps belong in an image. - Several people use different operating systems. A container removes "works on my laptop" differences in system libraries.
- The analysis must run later on a server. Scheduled jobs, CI runners, and cluster nodes can all run the same image you tested.
- You need to preserve a result for years. A built image, stored in a registry, keeps working after upstream package indexes change or remove old versions.
- A reviewer or collaborator needs to run it with one command. An image removes most setup instructions.
You can usually skip a container when the project is a small personal analysis with pure-Python dependencies, everyone uses the same operating system, and a pinned environment already passes a clean run on a second machine.
A minimal Dockerfile for a notebook project
The following Dockerfile builds on an official Python image, installs the pinned requirements, and copies the project in. It runs the notebook headlessly by default.
FROM python:3.12.7-slim
WORKDIR /project
# Install system libraries first. They change rarely, so this layer is cached.
RUN apt-get update \
&& apt-get install -y --no-install-recommends libgomp1 \
&& rm -rf /var/lib/apt/lists/*
# Install Python packages next. This layer is rebuilt only when requirements.txt changes.
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Copy the project last, because it changes most often.
COPY . .
CMD ["jupyter", "nbconvert", "--to", "notebook", "--execute", \
"notebooks/analysis.ipynb", "--output", "analysis_executed.ipynb", \
"--output-dir", "outputs"]Three choices in this file matter for reproducibility.
- A specific interpreter tag.
python:3.12.7-slimnames a patch release. The tagpython:latestwould change under you. - Layer order. Docker caches each instruction. Putting rarely changing steps first means a code edit does not reinstall every package.
- A pinned
requirements.txt. The image is only as reproducible as the file it installs from. An unpinnedpip install pandasinside a Dockerfile gives a different image each time you build it.
To build and run it, mount an output folder so results appear on your host:
docker build -t notebook-analysis:1.0 .
docker run --rm -v "$PWD/outputs:/project/outputs" notebook-analysis:1.0The --rm flag deletes the stopped container afterwards. The -v option maps the host's outputs folder into the container, so the executed notebook survives after the container exits.
Pinning the base image more tightly
A tag such as python:3.12.7-slim is a label. The maintainers can rebuild an image and move the tag, for example to ship a security patch. If you need the exact same base layers, pin by digest, which is a hash of the image content.
docker pull python:3.12.7-slim
docker inspect --format '{{index .RepoDigests 0}}' python:3.12.7-slimThe second command prints a reference such as python@sha256:.... Use that reference in the FROM line. This follows the same idea as the SHA-256 check you used for data files: a hash identifies content exactly, while a name can drift.
Digest pinning has a trade-off. You stop receiving base-image security updates until you change the digest on purpose. Many teams pin by digest and update it on a schedule.
Common failure modes
A container does not make an analysis reproducible by itself. Watch for these problems:
- Unpinned installs inside the image. If the Dockerfile runs
pip install pandas, two builds a month apart give different images. Install from the pinned file, or from a lock file with hashes. - Rebuilding instead of storing. Rebuilding the image later may fail or produce different packages. Push the built image to a registry, and record its tag or digest in your results.
- Data baked into the image. Large or private datasets do not belong in the image. Mount them at run time and keep the checksum verification step in the notebook, so a changed input still stops the run.
- Randomness is still your job. The container does not seed anything. Keep the explicit
default_rng(SEED)calls in your code. - CPU architecture differences. An image built on Apple Silicon is
arm64. Running it on anx86-64server needs either a rebuild or emulation, and numeric results can differ slightly. Build for the architecture you will run on, for example withdocker build --platform linux/amd64. - Running as root. Containers run as root by default. Files written to a mounted folder can end up owned by root on the host. Add a non-root
USERin the Dockerfile for shared machines. - Treating the container as a replacement for a clean run. Hidden state still exists inside a running Jupyter session in a container. The restart-and-run-all check still applies.
Recording the image in run metadata
Earlier you printed the interpreter, platform, and package versions at the top of the notebook. Inside a container, this output describes the image's environment, which is what you want. Also record which image produced the result. Pass the image name in through an environment variable and print it next to the other metadata:
docker run --rm \
-e IMAGE_REF="notebook-analysis:1.0" \
-v "$PWD/outputs:/project/outputs" \
notebook-analysis:1.0import os
import platform
import sys
print("Image:", os.environ.get("IMAGE_REF", "not running in a container"))
print("Python:", sys.version)
print("Platform:", platform.platform())
print("Machine:", platform.machine())The platform.machine() line shows x86_64 or aarch64, which makes architecture differences visible in the saved output.
Where containers fit in the workflow
A container does not replace the earlier steps. It sits on top of them. The pinned requirements file feeds the image build. The headless command becomes the image's default command. The CI job that checks the notebook can build the image and run it, so the check uses the same environment a reader will use.
Summary of decision criteria
- Start with a virtual environment and pinned dependencies. They solve most problems at low cost.
- Add a container when system libraries, operating system differences, long-term preservation, or server execution make pinning insufficient.
- Pin the base image, install from pinned files, store the built image, and record its reference with your results.
- Keep seeds, checksum checks, and the clean-run check. The container supports them and does not replace them.
Exercise
A colleague's analysis installs with pip install -r requirements.txt on your Linux machine, but fails on a teammate's Windows laptop because a geospatial package needs the GDAL system library. The same colleague plans to add FROM python:latest to a Dockerfile and RUN pip install geopandas. Name two changes that would make the container approach reproducible, and explain why a container is a reasonable fix here.
Show answer
A container is reasonable because the failure comes from a system library (GDAL) that a pinned Python file cannot install, and an image can include it for every user. Two changes: (1) replace python:latest with a specific tag such as python:3.12.7-slim, or better a digest, so the interpreter and base system do not change between builds; (2) install from the pinned requirements.txt (or a hashed lock file) instead of an unpinned pip install geopandas, so package versions are fixed. Also acceptable: store the built image in a registry and record its tag in the run metadata.
Exercise
You run the container on an Apple Silicon laptop and your collaborator runs it on an x86-64 server. The numeric output differs in the last decimal places. Give one likely cause and one way to make the comparison fair.
Show answer
The image architectures differ (arm64 versus x86-64), so compiled numerical libraries can use different instructions and produce slightly different floating-point results. To make the comparison fair, build and run both with the same platform, for example docker build --platform linux/amd64, and compare results with a tolerance (such as numpy.allclose) instead of exact equality.