Hello!
When I’m building Docker images, sometimes I need to pass data from the build agent (e.g. my CI pipeline) into the build process. Often, I also want to echo that data into the logs so I can use it for troubleshooting or validation later. Docker supports this!
These examples were all tested in Docker for Mac:
docker --version Docker version 19.03.13, build 4484c46d9d
First, declare your build-time data as an ARG
in your Dockerfile
:
FROM alpine:3.7 ARG USEFUL_INFORMATION ENV USEFUL_INFORMATION=$USEFUL_INFORMATION RUN echo "Useful information: $USEFUL_INFORMATION"
In this example, I’ve also set an ENV
variable so I can RUN
a command to print out the new ARG
.
Now, just build like ususal:
docker build --tag test_build_args --build-arg USEFUL_INFORMATION=1337 . Sending build context to Docker daemon 10.24kB Step 1/4 : FROM alpine:3.7 ---> 6d1ef012b567 Step 2/4 : ARG USEFUL_INFORMATION ---> Using cache ---> 18d20c437445 Step 3/4 : ENV USEFUL_INFORMATION=$USEFUL_INFORMATION ---> Using cache ---> b8bbdd03a1d1 Step 4/4 : RUN echo "Useful information: $USEFUL_INFORMATION" ---> Running in a2161bfb75cd Useful information: 1337 Removing intermediate container a2161bfb75cd ---> 9ca56256cc19 Successfully built 9ca56256cc19 Successfully tagged test_build_args:latest
If you don’t pass in a value for the new ARG
, it resolves to an empty string:
docker build --tag test_build_args . Sending build context to Docker daemon 10.24kB Step 1/4 : FROM alpine:3.7 ---> 6d1ef012b567 Step 2/4 : ARG USEFUL_INFORMATION ---> Using cache ---> 18d20c437445 Step 3/4 : ENV USEFUL_INFORMATION=$USEFUL_INFORMATION ---> Running in 63e4b0ce1fb7 Removing intermediate container 63e4b0ce1fb7 ---> 919769a93b7d Step 4/4 : RUN echo "Useful information: $USEFUL_INFORMATION" ---> Running in 73e158d1bfa6 Useful information: Removing intermediate container 73e158d1bfa6 ---> f928fc025270 Successfully built f928fc025270 Successfully tagged test_build_args:latest
Some details:
- Don’t use this for secrets.
- None of the arguments I’ve needed to pass in had sane defaults. If yours do, Docker supports them.
That’s it! Happy building,
Adam
Need more than just this article? We’re available to consult.
You might also want to check out these related articles: