I have a bit of a weird situation where I need to source the output of a script to set up some environment variables (which are only known at build time) before several RUN steps in my Dockerfile.
I know I can do this:
SHELL ["/bin/bash", "-c"]
RUN source <(./my_script) && echo "step 1"
RUN source <(./my_script) && echo "step 1"
And so on. But is there any way I can avoid repeating the source
for every step?
2
Answers
You may be able to avoid this with
ARG
andENV
, running the script in the host envMore details at How do I copy variables between stages of multi stage Docker build?
Otherwise you run into https://github.com/moby/moby/issues/29110 (from Answer to Dockerfile – set ENV to result of command)
For completeness, it possible to hack around many limitations of Dockerfiles by providing your container access to the docker daemon
While this sounds neat, and allows you to go so far as to execute an arbitrary script which results in a new, dynamic
Dockerfile
which you can immediately run .. I don’t and can’t possibly recommend this route in vanilla docker due to all of its maintainabiltiy and security flawsDetailswarnings here about doing this withoutcompose
andbuildkit
(also requires host/OS changes) Access docker within Dockerfile?A similar procedure is much safer and borderline useful with
docker compose
and buildkit (in such a context, you can provide access to the docker socket!), but still not generally recommendable.. still, going withdocker compose
can give you more useful tools in general to provide env values, but is not always possibleCreate a script named
my_source
with following content :Then in you Dockerfile :