How to use ARG and ENV in a Dockerfile?
Published on Aug. 22, 2023, 12:19 p.m.
To use ARG and ENV in a Dockerfile, you can follow these steps:
- Define one or more
ARGinstructions to allow users to pass in variables at build-time using the--build-argflag.
ARG VERSION=default
- Use the
ARGvariables in your Dockerfile to specify the default value for an environment variable using theENVinstruction.
ENV MY_VERSION=$VERSION
- Optionally, you can also specify a default value for the
ARGvariables by adding a value after the variable name.
ARG VERSION=default
ENV MY_VERSION=${VERSION:-3.0.0}
- Build your Docker image, passing in any desired values for the
ARGvariables using the--build-argflag.
docker build --build-arg VERSION=2.0.0 -t myimage .
This will build your Docker image, using the value 2.0.0 for the VERSION ARG variable, and set the MY_VERSION environment variable to the same value.
Using ARG and ENV in a Dockerfile can make your image more flexible, allowing you to specify environment variables at build-time while keeping the rest of the Dockerfile static.
Note that it’s generally not recommended to store sensitive information, such as passwords, in ARG or ENV variables because they can be viewed using the docker history command or by inspecting the image layers, respectively.