4.2.9.1 ARG Build Variables
A focused guide to ARG Build Variables, connecting core concepts with practical Docker and container operations.
ARG build variables are values supplied at build time through --build-arg, letting a single Dockerfile be reused for slightly different builds — different versions, different feature configurations — without needing a separate Dockerfile for each variation.
Supplying a Build Variable
A value passed via --build-arg overrides whatever default the corresponding ARG instruction declared, customizing that specific build invocation.
ARG NODE_VERSION=20
FROM node:$NODE_VERSION-alpine
docker build --build-arg NODE_VERSION=18 -t myapp:node18 .
docker build --build-arg NODE_VERSION=20 -t myapp:node20 .
Both builds use the same Dockerfile, producing images based on different Node.js versions purely through the supplied build variable.
Using Build Variables to Toggle Build Behavior
Build variables are also useful for conditionally affecting build behavior, such as including or excluding development tooling depending on the intended use of the resulting image.
ARG INCLUDE_DEV_TOOLS=false
RUN if [ "$INCLUDE_DEV_TOOLS" = "true" ]; then apt-get install -y vim; fi
docker build --build-arg INCLUDE_DEV_TOOLS=true -t myapp:dev .
docker build -t myapp:prod .
Why Build Cache Still Applies to ARG-Affected Layers
Changing a build variable's value invalidates the cache for any layer whose outcome depends on it, just as changing a Dockerfile instruction's text would, since the cache considers the variable's value as part of what determines a layer's identity.
docker build --build-arg NODE_VERSION=20 -t myapp .
docker build --build-arg NODE_VERSION=18 -t myapp .
The second build cannot reuse layers from the first that depended on the now-different NODE_VERSION value.
Why ARG Build Variables Matter
Build variables provide a clean, explicit mechanism for parameterizing a Dockerfile, avoiding the need to maintain multiple, nearly identical Dockerfiles that differ only in a small number of values that could instead be supplied at build time.