Search code examples
dockerdocker-machinedocker-build

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

Solution

  • 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.