✦ For everyone, free.

Practical knowledge for real and everyday life

Home

4.2.9.4 ARG FROM Interaction

A focused guide to ARG FROM Interaction, connecting core concepts with practical Docker and container operations.

ARG FROM interaction describes the special rule that an ARG declared before the first FROM instruction in a Dockerfile is usable within that FROM instruction itself, which is otherwise not possible since ARGs declared inside a build stage are only available within that stage.

Why This Special Case Exists

Normally, an ARG only takes effect from the point it is declared onward, within whatever build stage it appears in. But FROM itself can reference a variable, and since FROM necessarily comes before any stage exists, a separate rule allows an ARG declared before any FROM to be used in determining the base image itself.

ARG NODE_VERSION=20
FROM node:$NODE_VERSION-alpine
docker build --build-arg NODE_VERSION=18 -t myapp .

This selects the base image version dynamically, based on the supplied build argument.

Needing to Redeclare ARG Within a Stage

Although the variable is usable in FROM, using it again within the build stage itself requires redeclaring it after FROM, since the variable's availability does not automatically continue into the stage.

ARG NODE_VERSION=20
FROM node:$NODE_VERSION-alpine
ARG NODE_VERSION
RUN echo "Running on Node $NODE_VERSION"

Without this second ARG NODE_VERSION line (without a value, simply re-declaring it), referencing $NODE_VERSION inside the stage would not work as expected.

Using the Same Pattern Across Multiple Stages

In a multi-stage Dockerfile, this pattern can be repeated in each stage that needs access to the same pre-FROM argument.

ARG VERSION=1.0
FROM golang:1.22 AS build
ARG VERSION
RUN echo "Building version $VERSION"

FROM debian:bookworm-slim
ARG VERSION
LABEL version=$VERSION
Why This Interaction Matters

Understanding this specific rule prevents a common point of confusion: an ARG value mysteriously appearing empty within a build stage despite being declared earlier in the file, simply because it was not redeclared after the relevant FROM instruction.