Can we pass ENV variables through cmd line while building a docker image through dockerfile? Can we pass ENV variables through cmd line while building a docker image through dockerfile? docker docker

Can we pass ENV variables through cmd line while building a docker image through dockerfile?


Containers can be built using build arguments (in Docker 1.9+) which work like environment variables.

Here is the method:

FROM php:7.0-fpmARG APP_ENV=localENV APP_ENV ${APP_ENV}RUN cd /usr/local/etc/php && ln -sf php.ini-${APP_ENV} php.ini

and then build a production container:

docker build --build-arg APP_ENV=prod .

For your particular problem:

FROM debianENV http_proxy ${http_proxy}

and then run:

docker build --build-arg http_proxy=10.11.24.31 .

Note that if you build your containers with docker-compose, you can specify these build-args in the docker-compose.yml file, but not on the command-line. However, you can use variable substitution in the docker-compose.yml file, which uses environment variables.


So I had to hunt this down by trial and error as many people explain that you can pass ARG -> ENV but it doesn't always work as it highly matters whether the ARG is defined before or after the FROM tag.

The below example should explain this clearly. My main problem originally was that all of my ARGS were defined prior to FROM which resulted all the ENV to be undefined always.

# ARGS PRIOR TO FROM TAG ARE AVAIL ONLY TO FROM for dynamic a FROM tagARG NODE_VERSIONFROM node:${NODE_VERSION}-alpine# ARGS POST FROM can bond/link args to env to make the containers environment dynamicARG NPM_AUTH_TOKENARG EMAILARG NPM_REPOENV NPM_AUTH_TOKEN ${NPM_AUTH_TOKEN}ENV EMAIL ${EMAIL}ENV NPM_REPO ${NPM_REPO}# for good measure, what do we really haveRUN echo NPM_AUTH_TOKEN: $NPM_AUTH_TOKEN && \  echo EMAIL: $EMAIL && \  echo NPM_REPO: $NPM_REPO && \  echo $HI_5# remember to change HI_5 every build to break `docker build`'s cache if you want to debug the stdout..... # rest of whatever you want RUN, CMD, ENTRYPOINT etc..


I faced the same situation.

According to Sin30's answer pretty solution is using shell,

CMD ["sh", "-c", "cd /usr/local/etc/php && ln -sf php.ini-$APP_ENV php.ini"]