ARG or ENV, which one to use in this case?
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>
.
The environment variables set usingENV
will persist when a container is run from the resulting image.
So if you need build-time customization, ARG
is your best choice.
If you need run-time customization (to run the same image with different settings), ENV
is well-suited.
If I want to add let's say 20 (a random number) of extensions or any other feature that can be enable|disable
Given the number of combinations involved, using ENV
to set those features at runtime is best here.
But you can combine both by:
- building an image with a specific
ARG
- using that
ARG
as anENV
That is, with a Dockerfile including:
ARG var
ENV var=${var}
You can then either build an image with a specific var
value at build-time (docker build --build-arg var=xxx
), or run a container with a specific runtime value (docker run -e var=yyy
)
So if want to set the value of an environment variable to something different for every build then we can pass these values during build time and we don't need to change our docker file every time.
While ENV
, once set cannot be overwritten through command line values. So, if we want to have our environment variable to have different values for different builds then we could use ARG
and set default values in our docker file. And when we want to overwrite these values then we can do so using --build-args
at every build without changing our docker file.
For more details, you can refer this.