Using ARG and ENV in Dockerfile

In a Dockerfile, each FROM line starts a new image, and generally resets the build environment. If your image needs to specify ARGs, they need to come after the FROM line; if it's a multi-stage build, they need to be repeated in each image as required. ARG before the first FROM are only useful to allow variables in the FROM line, but can't be used otherwise.

This is further discussed under Understand how ARG and FROM interact in the Dockerfile documentation.

FROM centos:7

# _After_ the FROM line
ARG my_arg
ARG other_arg=other_default
...

At least since 20.10.2, ARGs can be passed from outside the FROM line onwards, all you need to do is insert another ARG with the same name after the FROM:

ARG my_arg
ARG other_arg=other_default

FROM centos:7

# These need to be re-stated here to use the ARGs above.
ARG my_arg
ARG other_arg # This will be populated with the default value 'other_default'.

ENV MY_ENV $my_arg
ENV OTHER_ENV $other_arg

CMD echo "$MY_ENV $OTHER_ENV"