James Lin
James Lin

Reputation: 26558

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

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

Upvotes: 10

Views: 11728

Answers (2)

BMitch
BMitch

Reputation: 264731

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

Upvotes: 14

Bernard
Bernard

Reputation: 17301

The docker build process doesn't happen in your local environment. That's why variables your local shell variables aren't picked up.

When you docker build ., all of the files in the dir where your Dockefile resides are copied to the docker daemon host (whatever your DOCKER_HOST points to). The build steps happens at that point. So yes you either need to pass variables using ARGS, or do copy your local environment variables into a file which will be copied to the docker host as part of the build context.

Remember to make use of the .dockerignore to specify dirs/files which should not be copied to the build context. That speeds up build time specially for remote docker hosts.

For Docker for Mac/Windows, the DOCKER_HOST is not defined but the same behaviour takes place. Your local files (build context) is built on a very small Linux like OS (Xhyve) that's running in your Mac.

Upvotes: 2

Related Questions