How to define a variable in a Dockerfile?

2019-02-01 20:12发布

In my Dockerfile, I would like to define variables that I can use later in the Dockerfile.

I am aware of the ENV instruction, but I do no want these variables to be environment variables.

Is there a way to declare variables at Dockerfile scope?

4条回答
何必那么认真
2楼-- · 2019-02-01 20:25

To answer your question:

In my Dockerfile, I would like to define variables that I can use later in the Dockerfile.

You can define a variable with:

ARG myvalue=3

Spaces around the equal character are not allowed.

and use it later with

RUN echo $myvalue > /test
查看更多
老娘就宠你
3楼-- · 2019-02-01 20:39

You can use ARG - see https://docs.docker.com/engine/reference/builder/#arg

The ARG instruction defines a variable that users can pass at build-time to the builder with the docker build command using the --build-arg <varname>=<value> flag. If a user specifies a build argument that was not defined in the Dockerfile, the build outputs an error.

查看更多
来,给爷笑一个
4楼-- · 2019-02-01 20:40

If the variable is re-used within the same RUN instruction, one could simply set a shell variable. I really like how they approached this with the official Ruby Dockerfile.

查看更多
你好瞎i
5楼-- · 2019-02-01 20:49

To my knowledge, only ENV allows that, as mentioned in "Environment replacement"

Environment variables (declared with the ENV statement) can also be used in certain instructions as variables to be interpreted by the Dockerfile.

They have to be environment variables in order to be redeclared in each new containers created for each line of the Dockerfile by docker build.

In other words, those variables aren't interpreted directly in a Dockerfile, but in a container created for a Dockerfile line, hence the use of environment variable.


This day, I use both ARG (docker 1.10+, and docker build --build-arg var=value) and ENV.
Using ARG alone means your variable is visible at build time, not at runtime.

My Dockerfile usually has:

ARG var
ENV var=${var}

In your case, ARG is enough: I use it typically for setting http_proxy variable, that docker build needs for accessing internet at build time.

查看更多
登录 后发表回答