I am learning how to use ARG and ENV in Dockerfiles.
I have this simple Dockerfile:
ARG my_arg
ARG other_arg=other_default
FROM centos:7
ENV MY_ENV $my_arg
ENV OTHER_ENV $other_arg
CMD echo "$MY_ENV $OTHER_ENV"
When I build it:
docker build --build-arg my_arg=my_value
And run it:
docker run <resulting-image>
I do not see the expected output, which would be
my_value other_default
Instead, I see the empty string.
What am I doing wrong?
2
Answers
In a Dockerfile, each
FROM
line starts a new image, and generally resets the build environment. If your image needs to specifyARG
s, they need to come after theFROM
line; if it’s a multi-stage build, they need to be repeated in each image as required.ARG
before the firstFROM
are only useful to allow variables in theFROM
line, but can’t be used otherwise.This is further discussed under Understand how ARG and FROM interact in the Dockerfile documentation.
At least since
20.10.2
,ARG
s can be passed from outside theFROM
line onwards, all you need to do is insert anotherARG
with the same name after theFROM
: