A few days ago I discovered (with the help from my colleagues) that ARG
instruction in Docker creates a true environment variable that is available inside the commands invoked at build time.
Before, I thought that ARG “creates a variable” that exists only in the processor of docker files and is basically a glorified macro. The documentation is somewhat ambiguous about it.
To test, I created a Dockerfile that invokes a command during build time, but does not pass the ARG to it explicitly. Instead, the command accesses the ARG as an environment variable.
See https://github.com/ikriv-samples/docker-arg.
FROM python:3.12-alpine ARG FLAVOR COPY init.py . RUN python init.py RUN chmod 755 go.sh CMD sh -c ./go.sh
The init.py
script:
import os with open('go.sh', 'w') as output: print(f"echo {os.environ['FLAVOR']}", file=output)
This creates a `go.sh` script that contains the flavor verbatim, which is executed at the startup of the container.
ARG vs ENV
ARG creates an environment variable available only during build time.
ENV creates an environment variable available during container run time.
We can link the two using this command:
ARG FLAVOR ENV FLAVOR=${FLAVOR}
This copies the value of the build-time environment variable FLAVOR
to the run-time environment variable FLAVOR
.