brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: an ARG before FROM picks the base image version of a Docker build

Docker
~/tips/tip-dockerfile-arg-before-from

ARG PY_VERSION=3.13

Change the base image tag from the build command, and reuse the value inside the stage.

ARG is the only instruction allowed before FROM. That makes it the way to choose a base image version at build time instead of editing the Dockerfile.

ARG PY_VERSION=3.13
FROM python:${PY_VERSION}-slim
ARG PY_VERSION
RUN echo "built on Python $PY_VERSION" > /build-info
docker build --build-arg PY_VERSION=3.12 -t example/app:py312 .

The default builds on 3.13, and the command above builds the same Dockerfile on 3.12. I find that handy to test an app on the next version before switching for real.

The second ARG PY_VERSION line, without a value, is the part people miss. An ARG declared before FROM lives outside every build stage, so after FROM it is empty. Declaring it again inside the stage pulls in the value from before. In a multi-stage build you repeat that line in every stage that needs it.

Build arguments are not secret. Their values show up in docker history and in the image metadata, so never pass a token this way; use a secret mount for that. And a missing default plus a forgotten --build-arg leaves you with FROM python:-slim, which fails with a confusing reference error.

Further reading: Dockerfile reference: understand how ARG and FROM interact

More Docker tips ONBUILD RUN /usr/local/bin/python-build --dir /app/src SHELL ["/bin/bash", "-c"] docker commit <container> myname/testimage:version3 docker import /path/to/exampleimage.tgz docker compose events All Docker tips (192) All topics

Link