Demo of Docker env vars and build args

Here’s a demo Dockerfile using env vars and build args

# build with
#   docker build --tag local/envvars --build-arg VAL1=asdf --build-arg VAL3=333 .
# run with
#   docker run --rm -it -e VAL4=runtime local/envvars
FROM node:14.17

ARG VAL1 VAL3
ENV VAL2=blah
ENV VAL3=$VAL3
# VAL4 only provided at runtime

RUN echo "build time; val1=$VAL1; val2=$VAL2; val3=$VAL3; val4=$VAL4"

ENTRYPOINT ["bash", "-c", "echo runtime, val1=$VAL1, val2=$VAL2, val3=$VAL3, val4=$VAL4"]

When you build it, you can see build args and env vars are in context

...
Step 5/6 : RUN echo "build time; val1=$VAL1; val2=$VAL2; val3=$VAL3; val4=$VAL4"
 ---> Running in 7197d2318303
build time; val1=asdf; val2=blah; val3=333; val4=
...

Then, when you run it

$ docker run --rm -it -e VAL4=runtime local/envvars 
runtime, val1=, val2=blah, val3=333, val4=runtime

…you can see build args (val1) are forgotten but env vars set during build are kept plus ones we set at runtime.

So you can set a default value during build, and then override it at runtime if you need.

Alternatively, you can write a bash script as the entrypoint which does an if to set the correct env var value based on whatever condition you need.

comments powered by Disqus