Defining ARG Variables in Dockerfile
Declaring ARG Variables
To define an ARG variable in a Dockerfile, you can use the ARG
instruction. The basic syntax is:
ARG <name>[=<default value>]
Here's an example:
ARG APP_VERSION=1.0.0
ARG BASE_IMAGE=ubuntu:20.04
In this example, we define two ARG variables: APP_VERSION
with a default value of 1.0.0
, and BASE_IMAGE
with a default value of ubuntu:20.04
.
Multiple ARG Declarations
You can also define multiple ARG variables on a single line, separated by a space:
ARG APP_VERSION=1.0.0 BASE_IMAGE=ubuntu:20.04
This is a more concise way of declaring multiple ARG variables in your Dockerfile.
Accessing ARG Variables
Once an ARG variable is defined, you can use it throughout the Dockerfile, including in FROM
, COPY
, ENV
, and other instructions. The ARG variable will be substituted with its value during the build process.
Here's an example of using an ARG variable in the FROM
instruction:
ARG BASE_IMAGE=ubuntu:20.04
FROM ${BASE_IMAGE}
## Rest of the Dockerfile
In this case, the ${BASE_IMAGE}
variable will be replaced with the value of the BASE_IMAGE
ARG during the build process.
Default Values for ARG
If you don't provide a default value for an ARG variable, it will be treated as an optional variable. You can then set the value of the ARG variable when running the docker build
command.
For example:
ARG BASE_IMAGE
FROM ${BASE_IMAGE:-ubuntu:20.04}
## Rest of the Dockerfile
In this case, if the BASE_IMAGE
ARG is not provided during the build, it will default to ubuntu:20.04
.
By understanding how to define and use ARG variables in your Dockerfiles, you can create more flexible and reusable Docker images that can be easily adapted to different environments or requirements.