Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dockerfile: Inherit environmental variables from shell

When building an image using a Dockerfile, in order to make some env vars available to the docker build context, one should explicitly declare associations of the form

ENV MYVAR=MYVALUE

AFAIK (correct me if I am misguided here), the environmental variables exported to the shell from which the docker build command is executed, are not passed to the Docker build context, i.e. if in my shell I have previously

export FOO=BAR

having the following declaration in my Dockerfile

ENV FOO=$FOO

and then echoing (still from within the Dockerfile) $FOO will print an empty string.

So if all of the above is correct, my question is if there is a way for the docker build context to inherit the environment of the shell being called from.

like image 407
pkaramol Avatar asked Feb 21 '18 16:02

pkaramol


People also ask

Can Dockerfile access environment variables?

ENV values are accessible during the build, and afterwards once the container runs. You can set ENV values in your Dockerfile - either by hardcoding them, or in a dynamic fashion.

Does Docker inherit environment variables?

Using docker-compose , you can inherit env variables in docker-compose. yml and subsequently any Dockerfile(s) called by docker-compose to build images. This is useful when the Dockerfile RUN command should execute commands specific to the environment.

Can you pass arguments to Dockerfile?

You can use the ARG command inside a Dockerfile to define the name of a parameter and its default value. This default value can also be overridden using a simple option with the Docker build command.


1 Answers

You could define default values with ARG:

ARG build_var=default_value
ENV ENV_VAR=$build_var

and then override at build time:

docker build --build-arg build_var=$HOST_VAR
like image 119
frennky Avatar answered Sep 28 '22 05:09

frennky