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:

  1. Define one or more ARG instructions to allow users to pass in variables at build-time using the --build-arg flag.
ARG VERSION=default
  1. Use the ARG variables in your Dockerfile to specify the default value for an environment variable using the ENV instruction.
ENV MY_VERSION=$VERSION
  1. Optionally, you can also specify a default value for the ARG variables by adding a value after the variable name.
ARG VERSION=default
ENV MY_VERSION=${VERSION:-3.0.0}
  1. Build your Docker image, passing in any desired values for the ARG variables using the --build-arg flag.
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.

Tags: