Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ARG and ENV in Dockerfile

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?

like image 362
Thomas Hirsch Avatar asked Feb 28 '20 11:02

Thomas Hirsch


People also ask

Can we use arg and ENV together?

You can use ARG values to set ENV values to work around that. ENV values are available to containers, but also RUN-style commands during the Docker build starting with the line where they are introduced.

What is arg and ENV in Dockerfile?

From Dockerfile reference: 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. The ENV instruction sets the environment variable <key> to the value <value> .

Can I use ENV variable in Dockerfile?

Dockerfile provides a dedicated variable type ENV to create an environment variable. We can access ENV values during the build, as well as once the container runs.


1 Answers

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
...
like image 193
David Maze Avatar answered Oct 13 '22 11:10

David Maze