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

后端 未结 3 1513
梦谈多话
梦谈多话 2020-12-07 13:20

I am working on a task that involves building a docker image with centOs as its base using a Dockerfile . One of the steps inside the docke

相关标签:
3条回答
  • 2020-12-07 13:27

    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"]
    
    0 讨论(0)
  • 2020-12-07 13:31

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

    Here is the method:

    FROM php:7.0-fpm
    ARG APP_ENV=local
    ENV 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 debian
    ENV 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.

    0 讨论(0)
  • 2020-12-07 13:49

    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 tag
    ARG NODE_VERSION
    FROM node:${NODE_VERSION}-alpine
    
    # ARGS POST FROM can bond/link args to env to make the containers environment dynamic
    ARG NPM_AUTH_TOKEN
    ARG EMAIL
    ARG NPM_REPO
    
    ENV NPM_AUTH_TOKEN ${NPM_AUTH_TOKEN}
    ENV EMAIL ${EMAIL}
    ENV NPM_REPO ${NPM_REPO}
    
    # for good measure, what do we really have
    RUN 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..
    
    0 讨论(0)
提交回复
热议问题