BudiBadu Logo
Samplebadu

Dockerfile by Example: Build Argument Structure

Docker Engine 20.10+

ARG defines variables that are only available during the build process, not at runtime. This sample code shows how to use them for versioning and build-time configuration.

Code

FROM ubuntu:22.04

# Define an argument with a default value
ARG APP_VERSION=1.0.0

# Use the argument in the build process
RUN echo "Building version $APP_VERSION" > /version.txt

# ARGs are not persisted as ENV vars by default.
# If you need it at runtime, assign it to an ENV.
ENV VERSION=$APP_VERSION

# Arguments can be passed before FROM to select base images
ARG GO_VERSION=1.21
FROM golang:$GO_VERSION

Explanation

The ARG instruction defines variables that users can pass at build-time to the builder with the --build-arg flag. Unlike ENV, ARG variables are ephemeral to the build process and do not persist in the final container's environment unless explicitly assigned to an ENV variable. They are ideal for parameterizing the build, such as specifying software versions or build flags.

Scope and persistence details of ARG:

  • Only available during the build execution
  • Can be declared before FROM to parameterize the base image tag
  • Values are visible in the image history (docker history)
  • Do not persist into the running container environment

A unique capability of ARG is its use before the first FROM instruction, allowing dynamic selection of the base image version. While ARG is safer than ENV for some data since it doesn't persist at runtime, it is still not secure for secrets because the build history retains the values passed. For handling secrets during builds, Docker's --secret mount feature is the recommended secure method.

Code Breakdown

4
ARG APP_VERSION=1.0.0 sets a default build argument.
11
ENV VERSION=$APP_VERSION captures the build arg into a runtime env var.
15
FROM golang:$GO_VERSION uses an argument to define the base image.
7
RUN echo ... uses the argument value during a build step.