Sub topic 12
Pinning the base image by digest
This chapter assumes you can read a basic Dockerfile and that you have Docker installed. It also assumes you know why the lock file from the previous chapters does not cover the operating system. Here you will learn what a tag does not promise, how to find and use a digest, and what pinning still leaves open.
Why a tag is not a version
A line like FROM python:3.11-slim names a repository (python) and a tag (3.11-slim). A tag is a label that the image publisher can move. The Python maintainers rebuild 3.11-slim for each 3.11 patch release. They also rebuild it when the Debian base gets security updates. Two builds a month apart can therefore start from different images with the same name.
That drift reaches your results through several routes:
- The Python patch version changes, for example from 3.11.8 to 3.11.9.
- System libraries such as
libc,libgompor OpenSSL change. - Any
apt-get installyou run on top resolves against the newer package index. - Compiled wheels in your lock file may behave differently against a different
libcor compiler runtime.
The tag also says nothing about which CPU architecture you get. The registry picks one at pull time based on the machine that pulls.
What a digest is
A digest is a SHA-256 hash of an image manifest, written sha256: followed by 64 hex characters. A manifest is a small JSON document that lists the image's configuration and its layers, each by its own hash. Change any byte in a layer and the layer hash changes. That changes the manifest and its digest. A digest therefore identifies exactly one image. A registry cannot return different content for it without the hash check failing.
For multi-architecture images, the tag points to an image index. The index is a manifest that lists one child manifest per platform (for example linux/amd64 and linux/arm64). The digest you copy from a registry is normally the index digest. It pins every platform at once, and Docker then selects the child that matches the pulling machine.
Finding the digest
Resolve the tag to a digest once, on purpose, and record the result in your repository. Either of these commands works:
# Prints the index digest and the per-platform manifests from the registry
docker buildx imagetools inspect python:3.11-slim
# After a pull, prints the digest the local image was pulled from
docker pull python:3.11-slim
docker inspect --format '{{index .RepoDigests 0}}' python:3.11-slimThe second command prints a full reference such as python@sha256:<digest>. Copy it into the Dockerfile.
Using the digest in a Dockerfile
Keep the tag next to the digest. Docker resolves by digest and ignores the tag, but the tag tells a human reader which release line the digest came from.
# Replace <digest> with the value from `docker buildx imagetools inspect`
FROM python:3.11-slim@sha256:<digest>
WORKDIR /app
COPY requirements.lock .
RUN pip install --no-cache-dir --require-hashes -r requirements.lock
COPY src/ ./src/
CMD ["python", "-m", "src.train"]If you build for several targets, you can lift the reference into a build argument so that CI and local builds share one value. An ARG declared before the first FROM is allowed to appear in that FROM line:
ARG BASE_IMAGE=python:3.11-slim@sha256:<digest>
FROM ${BASE_IMAGE}Now an update to the base image is a one-line diff, and the diff shows up in code review.
Checking that every FROM line is pinned
A pin only helps if nobody removes it. This short script scans Dockerfiles and fails on any FROM that lacks a digest. It skips FROM scratch and references to earlier build stages.
import re
import sys
from pathlib import Path
FROM_RE = re.compile(r"^\s*FROM\s+(?:--\S+\s+)*(\S+)(?:\s+AS\s+(\S+))?", re.IGNORECASE)
def unpinned(path: Path) -> list[str]:
stages: set[str] = set()
bad: list[str] = []
for line in path.read_text().splitlines():
match = FROM_RE.match(line)
if not match:
continue
image, alias = match.group(1), match.group(2)
if image != "scratch" and image.lower() not in stages and "@sha256:" not in image:
bad.append(image)
if alias:
stages.add(alias.lower())
return bad
if __name__ == "__main__":
failed = False
for name in sys.argv[1:]:
for image in unpinned(Path(name)):
print(f"{name}: base image is not pinned by digest: {image}")
failed = True
sys.exit(1 if failed else 0)Run it as python check_pins.py Dockerfile. A line that uses ${BASE_IMAGE} is reported, because the script cannot see the argument's value. Keep the check simple and put the digest literally in the FROM line, or extend the script to read the ARG default.
What a digest does not pin
A digest fixes the base image. It does not make the whole build reproducible, and it introduces its own costs.
| Gap | What still varies | What to do |
|---|---|---|
| `apt-get install` in your Dockerfile | Packages resolve against the current Debian index | Avoid it where possible, or pin exact versions, or put the packages into a base image you build and pin yourself |
| Registry retention | Registries can delete old images, and a pinned digest then fails to pull | Copy the base image into a registry you control |
| Security patches | A frozen base never receives fixes | Update the digest on a schedule and rebuild |
| Your built image | Timestamps and file ordering can make two builds differ byte for byte | Treat the digest of the image you ship as the artifact identity |
| Host GPU driver | It lives outside the image | Record the driver version with the run |
The last row matters for GPU work. The image contains the CUDA runtime libraries, but the NVIDIA driver comes from the host. Pinning the image does not pin the driver, so record it with every training run.
Updating the pin on purpose
Treat a base image update like a dependency update. Resolve the new digest, change the FROM line in one commit, rebuild, and run your tests and a short training run. Compare the metrics with the previous image. If they differ beyond your seed-to-seed noise, you have learned that the operating system layer matters for your model, and the pin is doing its job. Tools such as Renovate and Dependabot can open pull requests that change digests, so the review step stays and the manual lookup goes.
Exercise
A teammate says "we already pin the base image, because our Dockerfile says FROM python:3.11-slim and we never change it." Give two reasons that is not a pin, and state what the fix is.
Show answer
First, 3.11-slim is a tag, and the maintainers move it to a new image for each patch release and base OS update, so the same line can pull different images on different days. Second, the tag resolves to a different platform manifest depending on the machine that pulls. The fix is to resolve the tag to its index digest with docker buildx imagetools inspect python:3.11-slim and write FROM python:3.11-slim@sha256:<digest>. Then update the digest deliberately when you want newer patches.
Exercise
Your pinned build starts failing months later with "manifest unknown" when it pulls the base image. What probably happened, and how do you prevent it?
Show answer
The registry removed the image that the digest referred to, which happens when images are retired or cleaned up. A digest guarantees content but not availability. Prevent it by copying the base image into a registry you control (pull it, tag it for your registry, push it) and pinning that copy's digest in the Dockerfile.