Intro

You can assign build arguments inside your Dockerfile using ARG instructions:

FROM busybox:latest

ARG EXAMPLE_ARG

RUN echo ${EXAMPLE_ARG}

Then you can set the EXAMPLE_ARG via --build-flag for docker build:

$ docker build -t some-image:latest --build-arg EXAMPLE_ARG=example .

The output will be like:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
[+] Building 0.3s (6/6) FINISHED
 => [internal] load build definition from Dockerfile
 => => transferring dockerfile: 174B
 => [internal] load .dockerignore
 => => transferring context: 2B
 => [internal] load metadata for docker.io/library/busybox:latest
 => [1/2] FROM docker.io/library/busybox:latest
 => [2/2] RUN echo example
 => exporting to image
 => => exporting layers
 => => writing image sha256:917f420c3580196a0dff0b5f7e70382676b456a82029b55f40762171be3367d3
 => => naming to docker.io/library/some-image:latest

Info

As build arguments aren’t persisted to the build image, you’ll see an empty string when running echo $EXAMPLE_ARG inside containers created from some-image:latest.

Info

ARG is the only instruction that may come before FROM in your Dockerfile. See Understand how ARG and FROM interact

Default Value for ARG

The ARG instruction can be given a default value when no matching --build-arg flag is supplied:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
# define an alias for the specfic python version used in this file.
FROM python:3.10.10-slim-bullseye as python

# Python build stage
FROM python as python-build-stage

ARG BUILD_ENVIRONMENT=local

# Install apt packages
RUN apt-get update && apt-get install --no-install-recommends -y \
  # dependencies for building Python packages
  build-essential \
  # psycopg2 dependencies
  libpq-dev

# Requirements are installed here to ensure they will be cached.
COPY ./requirements .

# Create Python Dependency and Sub-Dependency Wheels.
RUN pip wheel --wheel-dir /usr/src/app/wheels  \
  -r ${BUILD_ENVIRONMENT}.txt

If you don’t pass the related ARG with --build-arg flag to docker build, docker will assign local -“local.txt”, to BUILD_ENVIRONMENT argument.

All done!