0
0
DockerHow-ToBeginner · 3 min read

How to Use Build Argument in Dockerfile: Syntax and Examples

Use 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.

dockerfile
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.

dockerfile
FROM alpine:3.18

ARG VERSION=latest
RUN echo "Building version $VERSION"
Output
Building version 1.2.3
⚠️

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.

dockerfile
### 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 ARG before FROM if used in FROM.
  • Pass values with docker build --build-arg NAME=value .
  • Build arguments are not environment variables; use ENV to persist variables.
  • Use build arguments to customize builds without hardcoding values.

Key Takeaways

Use ARG in Dockerfile to declare build-time variables.
Pass values with --build-arg during docker build to override defaults.
Declare ARG before FROM if you want to use it in the FROM line.
Build arguments do not persist in the final image environment.
Use build arguments to customize builds without changing Dockerfile code.