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

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 dockerfile needs http_proxy and https_proxy ENV variables to be set in order to work behind the proxy.

As this Dockerfile will be used by multiple teams having different proxies, I want to avoid having to edit the Dockerfile for each team. Instead I am looking for a solution which allows me to pass ENV variables at build time, e.g.,

sudo docker build -e http_proxy=somevalue .

I'm not sure if there is already an option that provides this. Am I missing something?

102522 次浏览

容器可以使用与环境变量类似的 build arguments(在 Docker 1.9 + 中)来构建。

方法如下:

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

然后建造一个生产容器:

docker build --build-arg APP_ENV=prod .

针对你的特殊问题:

FROM debian
ENV http_proxy ${http_proxy}

然后跑:

docker build --build-arg http_proxy=10.11.24.31 .

请注意,如果使用 docker-compose构建容器,则可以使用 docker-compose.yml文件中指定这些构建参数,但不能在命令行上使用 docker-compose.yml文件中指定这些构建参数。但是,您可以使用 使用环境变量的 docker-compose.yml文件中的变量替换

我也遇到过同样的情况。

根据 Sin30的回答,比较好的解决方案是使用 shell,

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

所以我不得不通过反复试验来找出这个问题,因为很多人解释说你可以通过 ARG-> ENV,但是它并不总是起作用,因为 ARG 是在 FROM标签之前还是之后定义的非常重要。

下面的例子应该清楚地解释这一点。我的主要问题最初是,我的所有 ARGS 是定义之前的 FROM,这导致所有的 ENV是未定义的总是。

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