How to Use Build Argument in Dockerfile: Syntax and Examples
ARG in a Dockerfile to declare a build argument and --build-arg with docker build to pass its value. This lets you customize the build process by injecting variables accessible only during build time.Syntax
The ARG instruction declares a build argument in the Dockerfile. You can optionally assign a default value. During the build, you pass the argument value using --build-arg with the docker build command.
ARG <name>[=<default_value>]: Declares a build argument.--build-arg <name>=<value>: Sets the argument value during build.
Build arguments are only available during build and do not persist in the final image.
ARG <name>[=<default_value>]
# Example:
ARG VERSION=latest
RUN echo "Building version $VERSION"Example
This example shows how to declare a build argument VERSION with a default value and override it during build. The Dockerfile prints the version during build.
FROM alpine:3.18 ARG VERSION=latest RUN echo "Building version $VERSION"
Common Pitfalls
1. Not passing the build argument: If you declare ARG but don't pass --build-arg, the default value (if any) is used or the argument is empty.
2. Using ARG after FROM in multi-stage builds: Arguments used in FROM must be declared before it.
3. Expecting build arguments to persist: Build arguments are not environment variables and do not exist after build.
### Wrong: Using ARG after FROM for FROM substitution FROM alpine:3.18 ARG VERSION=latest # This ARG won't affect FROM ### Right: Declare ARG before FROM ARG VERSION=latest FROM alpine:$VERSION
Quick Reference
Summary tips for using build arguments:
- Declare
ARGbeforeFROMif used inFROM. - Pass values with
docker build --build-arg NAME=value . - Build arguments are not environment variables; use
ENVto persist variables. - Use build arguments to customize builds without hardcoding values.