Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Docker how to inject host ENV into Dockerfile ENV during build?

Tags:

docker

I am adding some environment settings on docker repo automatic build, lets say, WEBSERVER_PRIVATE_KEY=123

in my Dockerfile, when I build locally, I assume it would pick up the env value

RUN echo $WEBSERVER_PRIVATE_KEY > /somewhere/key

But it didn't work.

I had a look at the ENV command, but it doesn't seem there is a way to inject that value.

I had a look at the ARG command, but it requires to pass as --build-arg which I doubt it will work during built on docker repo.

See below environment settings on docker repo during automatic builds, how do I make the Dockerfile to reference the WEBSERVER_PRIVATE_KEY in the setting.

enter image description here

like image 855
James Lin Avatar asked Oct 06 '16 23:10

James Lin


1 Answers

You can do this on selective environment variables, but you need to pass them with the --build-arg and configure your Dockerfile to receive them. When you don't give a --build-arg a value for the variable, or an environment variable a value with docker run -e on running, Docker will use your environment to set the value.

Here's an example Dockerfile that uses the build-args:

FROM busybox

ARG DOCKER_HOST=${DOCKER_HOST:-""}
ENV DOCKER_HOST=${DOCKER_HOST}

CMD echo "DOCKER_HOST is ${DOCKER_HOST}"

If you do your build and pass --build-arg DOCKER_HOST, docker will set that variable from your environment:

$ echo $DOCKER_HOST
127.0.0.1:2376

$ docker build --build-arg DOCKER_HOST -t test-env:latest .
...
Successfully built 088fabdd9a96

$ docker run test-env
DOCKER_HOST is 127.0.0.1:2376

If you do the build without the arg, that environment variable won't be passed:

$ docker build -t test-env:latest .
...
Successfully built ef31d886749b

$ docker run test-env
DOCKER_HOST is

But you can still manually pass it from your environment on a docker run -e DOCKER_HOST:

$ docker run -e DOCKER_HOST test-env
DOCKER_HOST is 127.0.0.1:2376
like image 174
BMitch Avatar answered Oct 31 '22 12:10

BMitch