Habba
Habba

Reputation: 515

How to use the environment variables of docker machine when building a Dockerfile

When creating a new image my Dockerfile needs to call npm install. This needs to work behind a proxy as well. At this point the following Dockerfile code works:

# Set proxy server
ENV http_proxy http://myproxy.example
ENV https_proxy http://myproxy.example

# run NPM install
RUN npm install --production

I would however like that I can set the ENV variables the same as in the docker-machine I have set up with

 docker-machine create \
 -d virtualbox \
 --engine-env HTTP_PROXY=http://myproxy.example \
 --engine-env HTTPS_PROXY=http://myproxy.example \
 dock

i.e. I would like that the npm install command uses these environment variables. This would make sure that images of this Dockerfile can be built in any environment that has proxy settings available.

I have already set the created machine as env with the command

docker-machine env --no-proxy dock

Upvotes: 0

Views: 609

Answers (2)

BMitch
BMitch

Reputation: 265228

The http_proxy and similar variables are predefined args that you do not need to specify in your Dockerfile:

Docker has a set of predefined ARG variables that you can use without a corresponding ARG instruction in the Dockerfile.

  • HTTP_PROXY
  • http_proxy
  • HTTPS_PROXY
  • https_proxy
  • FTP_PROXY
  • ftp_proxy
  • NO_PROXY
  • no_proxy

To use it, you simply pass it as a build arg with:

docker build \
  --build-arg http_proxy=http://myproxy.example \
  --build-arg https_proxy=http://myproxy.example \
  .

For your npm install line they may already be in your environment, and if not, you should be able to use:

RUN http_proxy=$http_proxy https_proxy=$https_proxy npm install --production

Note, you should not place these in the image ENV since that may negatively impact other locations where you run the image.

Upvotes: 4

samprog
samprog

Reputation: 2644

AFAIK this isn't possible the way you want it to be. The environment variables you set in the docker-machine are for the docker-engine to push/pull images, etc. and can not be referenced.

What you can do is use the ARG instruction, which handles like a variable inside the Dockerfile (Link). This enables you to pass variables with the docker build command

For example you could use it in the following way:

# define proxy variable
ARG proxy

# set proxy
ENV http_proxy=$proxy
ENV https_proxy=$proxy

# run NPM install
RUN npm install --production

So when you build the image you could pass the proxy with docker build -t [ImageName] --build-arg proxy=http://myproxy.example [ProjectDir]

Upvotes: 1

Related Questions