Docker "UndefinedVar: Usage of undefined variable" in Build ARG/ENV
BuildKit warned (or failed in strict mode) that a $VARIABLE used in the Dockerfile was never defined. An ARG is referenced before it is declared, or a build-arg was never passed, so it expands to empty.
What this error means
The build prints UndefinedVar: Usage of undefined variable '$X', and the resulting command runs with an empty value - a blank tag, a missing path, or a broken URL. With strict frontends it fails the build outright.
1 warning found (use --debug to expand):
- UndefinedVar: Usage of undefined variable '$VERSION' (line 7)
# RUN curl -o app https://example.com/app-$VERSION -> expands to ...app-Common causes
ARG used before it is declared
In multi-stage builds, an ARG declared in one stage is not visible in another until re-declared. Referencing it before/outside its scope yields an undefined variable.
Build-arg never passed
A Dockerfile expects --build-arg VERSION=... but the CI build command omits it, so $VERSION is empty.
Typo in the variable name
A mismatch between the declared ARG/ENV name and the usage ($VERSON vs $VERSION) leaves the reference undefined.
How to fix it
Declare the ARG in the stage that uses it
Re-declare ARGs per stage and reference them only after declaration.
FROM alpine AS build
ARG VERSION
RUN curl -fsSLo app "https://example.com/app-${VERSION}"Pass the build-arg and assert it is set
Provide the value at build time and fail fast if it is empty.
docker build --build-arg VERSION=1.4.2 -t myorg/api:1.4.2 .
# in the Dockerfile, guard required args:
RUN test -n "${VERSION}" || (echo "VERSION build-arg required" && false)How to prevent it
- Re-declare ARGs in each stage that references them.
- Pass all required
--build-argvalues in CI and assert non-empty. - Keep ARG/ENV names consistent to avoid typos.