在我的Dockerfile中,我想定义我以后可以在Dockerfile中使用的变量。

我知道ENV指令,但我不希望这些变量是环境变量。

是否有一种在Dockerfile范围内声明变量的方法?


据我所知,只有ENV允许,正如“环境替换”中提到的那样

环境变量(用ENV语句声明)也可以在某些指令中作为Dockerfile解释的变量使用。

它们必须是环境变量,以便在docker构建为Dockerfile的每一行创建的每个新容器中重新声明。

换句话说,这些变量不是直接在Dockerfile中解释的,而是在为Dockerfile行创建的容器中解释的,因此使用了环境变量。


今天,我同时使用了ARG (docker 1.10+和docker build——build- ARG var=value)和ENV。 单独使用ARG意味着你的变量在构建时可见,而不是在运行时可见。

我的Dockerfile通常有:

ARG var
ENV var=${var}

在你的情况下,ARG就足够了:我通常使用它来设置http_proxy变量,docker构建需要在构建时访问互联网。


Christopher King在评论中补充道:

小心! ARG变量只在“它被使用的阶段”的范围内,并且需要为每个阶段重新声明。

他指向Dockerfile / scope

An ARG variable definition comes into effect from the line on which it is defined in the Dockerfile not from the argument’s use on the command-line or elsewhere. For example, consider this Dockerfile: FROM busybox USER ${user:-some_user} ARG user USER $user # ... A user builds this file by calling: docker build --build-arg user=what_user . The USER at line 2 evaluates to some_user as the user variable is defined on the subsequent line 3. The USER at line 4 evaluates to what_user as user is defined and the what_user value was passed on the command line. Prior to its definition by an ARG instruction, any use of a variable results in an empty string. An ARG instruction goes out of scope at the end of the build stage where it was defined. To use an arg in multiple stages, each stage must include the ARG instruction.

如果变量在同一个RUN指令中被重用,可以简单地设置一个shell变量。我真的很喜欢他们在官方Ruby Dockerfile中的做法。

你可以使用ARG -参见https://docs.docker.com/engine/reference/builder/#arg

ARG指令定义了一个用户可以传递的变量 属性将docker构建命令添加到构建器的构建时 ——build-arg <varname>=<value>标志。如果用户指定了生成 参数没有在Dockerfile中定义,构建输出一个 错误。

在构建期间使用COPY可以很有用(例如,复制特定的标签内容,如特定的文件夹) 例如:

ARG MODEL_TO_COPY
COPY application ./application
COPY $MODEL_TO_COPY ./application/$MODEL_TO_COPY

在构建容器时:

docker build --build-arg MODEL_TO_COPY=model_name -t <container>:<model_name specific tag> .

回答你的问题:

在我的Dockerfile中,我想定义我以后可以在Dockerfile中使用的变量。

你可以用以下方法定义变量:

ARG myvalue=3

等号周围不允许有空格。

然后用在:

RUN echo $myvalue > /test

你可以使用ARG变量defaultValue,在运行命令时,你甚至可以使用——build-arg variable=value更新这个值。要在docker文件中使用这些变量,你可以在run命令中引用它们为$variable。

注意:这些变量可以用于Linux命令,如RUN echo $variable,并且它们不会持久化在映像中。

虽然有点晚了,但如果你不想暴露环境变量,我想这样做会更容易:

RUN echo 1 > /tmp/__var_1
RUN echo `cat /tmp/__var_1`
RUN rm -f /tmp/__var_1

我最终这样做是因为我们在aws codeartifact中托管了私有npm包:

RUN aws codeartifact get-authorization-token --output text > /tmp/codeartifact.token
RUN npm config set //company-123456.d.codeartifact.us-east-2.amazonaws.com/npm/internal/:_authToken=`cat /tmp/codeartifact.token`
RUN rm -f /tmp/codeartifact.token

这里ARG不能工作,我不想使用ENV,因为我不想将这个令牌暴露给其他任何东西