Skip to content

Instantly share code, notes, and snippets.

@sudo-bmitch
Created January 30, 2018 15:24
Show Gist options
  • Save sudo-bmitch/e6b9caa776adb9fdf0cfd1c68f4364a5 to your computer and use it in GitHub Desktop.
Save sudo-bmitch/e6b9caa776adb9fdf0cfd1c68f4364a5 to your computer and use it in GitHub Desktop.
Docker ARGS as environment variables
$ cat df.build-arg
FROM busybox
ARG ARGNAME=default
RUN env
RUN echo "ARGNAME=${ARGNAME}"
RUN echo "ARG Prefix=${ARGNAME%_*}" \
&& echo "ARG Suffix=${ARGNAME#*_}"
CMD env
$ docker build -t test-args --build-arg=ARGNAME=hello_world -f df.build-arg .
Sending build context to Docker daemon 26.09MB
Step 1/6 : FROM busybox
---> 54511612f1c4
Step 2/6 : ARG ARGNAME=default
---> Using cache
---> 3362ed65aaba
Step 3/6 : RUN env
---> Running in 139c42dc0ff8
HOSTNAME=139c42dc0ff8
SHLVL=1
HOME=/root
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
ARGNAME=hello_world
PWD=/
Removing intermediate container 139c42dc0ff8
---> ff914d8e47d4
Step 4/6 : RUN echo "ARGNAME=${ARGNAME}"
---> Running in 0b77b08c0c5a
ARGNAME=hello_world
Removing intermediate container 0b77b08c0c5a
---> e1fd07b92376
Step 5/6 : RUN echo "ARG Prefix=${ARGNAME%_*}" && echo "ARG Suffix=${ARGNAME#*_}"
---> Running in b29e13cef7ad
ARG Prefix=hello
ARG Suffix=world
Removing intermediate container b29e13cef7ad
---> a4ac52e47497
Step 6/6 : CMD env
---> Running in 771d5d35627f
Removing intermediate container 771d5d35627f
---> 1ee8dccea2ac
Successfully built 1ee8dccea2ac
Successfully tagged test-args:latest
$ docker run -it --rm test-args
HOSTNAME=99d6fa3939b1
SHLVL=1
HOME=/root
TERM=xterm
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
PWD=/

Args are processed as build time environment variables, the docker build process itself is not parsing the variables. This means you can see them with env and perform shell processing on the variables that you cannot do in a Dockerfile.

Build step 2

After this line, any RUN line will be a cache miss if the arg value changes.

Build step 3

You can see the variable set in the env output even though the arg was not used in the RUN command directly.

Build step 5

The prefix and suffix syntaxes are available inside busybox or bash, but not in the Dockerfile. You can see the variable substitution happens inside the container, not by the build engine parsing the Dockerfile.

Running the container

The arg is no longer set here. It's only available on build steps inside the above Dockerfile, and even then, only as part of the FROM section. A multi-stage build would need to define the arg inside of each stage to use it again.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment