Search notes:

Dockerfile: ARG vs ENV

There there two instructions with which it is possible to define variables and their values in a Dockerfile: ARG and ENV.
ARG defines a variable whose value is used while a image is built. This value is not accessible anymore when a corresponding container is run.
In constrast, ENV defines an environment variable whose value is accessible inside a running container.
The value of an ARG variable is either a default value specfied with ARG var=val or set with the command line option --build-arg when docker build is executed.
The vale of an ENV variable is either the default value given in the Docker file (ENV envar=xyz) or explicitly specified with the command line option -e when a container is run with docker run

Demonstration

This difference is demonstrated with this simple example.

Dockerfile

This dockerfile specifies an ARG variable (filename). A file with this name is created (touched) in the /tmp directory of the image.
The dockerfile also specifies to execute a shell script named script.sh (CMD /script.sh). This script is copied from the host with the COPY instruction.
FROM busybox

ARG  filename=default-file-name
ENV  value=foo-bar-baz

COPY script.sh /script.sh

RUN  chmod +x /script.sh
RUN  touch /tmp/$filename

CMD /script.sh

The shell script to be executed (script.sh)

The shell script being executed is rather simple: it echoes the value of the environment variable $value and lists the files in /tmp)
#!/bin/sh

echo envar value = $value
echo ls -l tmp : $(ls -l tmp)

Building the images

The following commands build two images: one image (named arg-vs-env-default) where the default value for the ARG values filename is used and another image (arg-vs-env-go) where this value is explicitly set to overwritten:
docker build                                   -t arg-vs-env-default     .
docker build --build-arg filename=overwritten  -t arg-vs-env-go          .

Running the images

The following commands create three images and essentially run the mentioned shell script. For the last image, -e is used to set the value of the environment variable value to xyz.
docker run              arg-vs-env-default
docker run              arg-vs-env-go
docker run -e value=xyz arg-vs-env-go

See also

ARG, ENV

Index