CodeBlanks Logo Icon CodeBlanks

The ARG instruction

Learn build-time variables with ARG.

The ARG instruction

ARG defines a variable valid only during the build; it doesn't exist in the running container. Its value is given with docker build --build-arg; if not given, the default is used:

ARG PYTHON_VERSION=3.12
FROM python:${PYTHON_VERSION}-slim
ARG UYGULAMA_SURUMU=dev
RUN echo "$UYGULAMA_SURUMU" > /surum.txt

$ docker build --build-arg PYTHON_VERSION=3.11 --build-arg UYGULAMA_SURUMU=1.4.0 -t api .

ARG before FROM

An ARG defined before FROM can only be used in FROM lines. If you want to use it after FROM too, it is declared again without a value:

ARG SURUM=3.12
FROM python:${SURUM}-slim
ARG SURUM                 # declare again: the value comes from above
RUN echo "Python $SURUM"

ARG values can also appear in docker history; for secret values BuildKit's --secret feature is used.

Practice Choose the version from outside

Write a Dockerfile: before FROM, ARG NODE_VERSION=20; base image node:${NODE_VERSION}-alpine; after FROM, ARG SURUM=dev and ENV APP_SURUM=$SURUM carrying it to run time.

Starter code

terminal
# buraya yaz

Sample solution

terminal
ARG NODE_VERSION=20
FROM node:${NODE_VERSION}-alpine
ARG SURUM=dev
ENV APP_SURUM=$SURUM

Expected output

[+] Building 2.9s (8/8) FINISHED
 => naming to docker.io/library/web:latest done

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the difference between ARG and ENV?

  • ARG is valid only in the container
  • ENV can't be used in the build
  • ARG is valid only in the build, ENV in the build and the running container Correct answer
  • They are the same

Explanation: To carry an ARG value to run time, ENV NAME=$NAME is written.

2 Give the build argument.

Question
docker build ____ SURUM=1.4.0 -t api .
Answer
docker build --build-arg SURUM=1.4.0 -t api .

Explanation: --build-arg NAME=value fills an ARG.

3 Match.

Term Meaning
ARG Build variable
--build-arg Gives the ARG value
ARG before FROM Base image choice
--secret Secret build value

All lessons in Beginner