Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 111 ยท Dockerfiles

ENV and ARG

Understand ENV and ARG in a Dockerfile: build-time vs run-time variables, scope, defaults, --build-arg, cache effects, and why secrets never belong in either.

Almost every real image needs some configuration: a version number to build, a port to listen on, a mode such as production. A Dockerfile gives you two instructions for this, and they sound alike but live in different worlds. ARG defines a variable that exists only while the image is being built. ENV defines a variable that is baked into the image and is visible to every container started from it.

Mixing them up is a classic source of "why is this variable empty?" bugs. This lesson shows exactly where each variable is visible, how to override it, how it interacts with the build cache, and the biggest rule of all: neither one is a safe place for secrets. All outputs below come from real builds.

ENV: variables that live in the image

ENV sets an environment variable for the rest of the build and for every container that runs from the image.

DOCKERFILE
FROM alpine:3.22
ARG APP_VERSION=dev
ENV APP_ENV=production \
    GREETING="Hello from ENV"
RUN echo "build sees APP_VERSION=$APP_VERSION APP_ENV=$APP_ENV"
CMD ["sh", "-c", "echo run sees APP_ENV=$APP_ENV GREETING=$GREETING APP_VERSION=[$APP_VERSION]"]
CONSOLE
$ docker build -t env-demo .
$ docker run --rm env-demo
run sees APP_ENV=production GREETING=Hello from ENV APP_VERSION=[]

APP_ENV and GREETING arrived inside the container because they are stored in the image metadata:

CONSOLE
$ docker image inspect env-demo --format '{{json .Config.Env}}'
["PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin","APP_ENV=production","GREETING=Hello from ENV"]

Notice that APP_VERSION printed as empty in the container. We will get to why in a moment.

A few syntax details:

  • ENV KEY=value is the modern form. You can set several variables in one instruction by listing pairs; use backslashes to continue lines. Quote values that contain spaces.
  • The old form ENV KEY some value (no equals sign) still works but is easy to misread. Prefer KEY=value.
  • Each ENV instruction creates a layer of metadata, so grouping related variables in one instruction is tidy, though it makes no practical size difference.

Overriding ENV at run time

Anyone running the container can replace an ENV default without rebuilding:

CONSOLE
$ docker run --rm -e APP_ENV=staging env-demo
run sees APP_ENV=staging GREETING=Hello from ENV APP_VERSION=[]

For several variables, put them in a file with one NAME=value per line and use --env-file:

CONSOLE
$ cat app.env
APP_ENV=staging
DEBUG=false
$ docker run --rm --env-file app.env env-demo
run sees APP_ENV=staging GREETING=Hello from ENV APP_VERSION=[]

So ENV in a Dockerfile is best seen as a default that the person running the container can change. Configuring Containers covers run-time configuration in depth.

Variables in later instructions

An ENV variable can be used in the instructions that follow it, including other ENV lines. Docker expands $VAR and ${VAR} itself, and supports a few shell-like forms:

DOCKERFILE
FROM alpine:3.22
ENV PORT=8080
ENV ADDR=0.0.0.0:${PORT}
ENV NAME_UP=${UNSET_VAR:-fallback}
CMD ["sh","-c","echo $ADDR $NAME_UP"]
CONSOLE
$ docker run --rm env-expand
0.0.0.0:8080 fallback
$ docker run --rm -e PORT=9 env-expand
0.0.0.0:8080 fallback

The second command surprises people: overriding PORT at run time did not change ADDR. ENV ADDR=0.0.0.0:${PORT} was expanded while building, so the finished image already contains the final string:

CONSOLE
$ docker run --rm env-expand env | grep -E 'PORT|ADDR'
PORT=8080
ADDR=0.0.0.0:8080

If a value should follow a run-time override, build it at run time, for example in a shell-form CMD or an entrypoint script (see CMD and ENTRYPOINT).

Docker expands variables only in some instructions: ADD, COPY, ENV, EXPOSE, FROM, LABEL, STOPSIGNAL, USER, VOLUME and WORKDIR (and ONBUILD for those). In RUN and in shell-form CMD it is the shell that expands them; in exec-form CMD nothing does.

ENV does not carry across RUN lines when you use export

A common mistake is trying to set a persistent variable from inside a RUN. Each RUN is its own shell, so an export lasts only for that one command:

DOCKERFILE
FROM alpine:3.22
RUN export MODE=fast && echo "same RUN: $MODE"
RUN echo "next RUN: [$MODE]"
TEXT
same RUN: fast
next RUN: []

Use ENV MODE=fast when later instructions and the final container need it.

ARG: variables that exist only at build time

ARG declares a variable the builder can receive with --build-arg. It is available to RUN and to later instructions in the same build, but it is not put into the environment of containers.

Using the first Dockerfile again (its ARG APP_VERSION=dev and the RUN echo "build sees ..." line), build it twice:

CONSOLE
$ docker build --progress=plain --no-cache -t env-demo .
...
#5 0.285 build sees APP_VERSION=dev APP_ENV=production
$ docker build --progress=plain --no-cache --build-arg APP_VERSION=1.4.2 -t env-demo2 .
...
#5 0.788 build sees APP_VERSION=1.4.2 APP_ENV=production
$ docker run --rm env-demo2
run sees APP_ENV=production GREETING=Hello from ENV APP_VERSION=[]

The build-arg changed what the build saw (1.4.2), but the container's APP_VERSION is still empty. That is the whole difference in one picture:

TEXT
                   build (RUN, COPY ...)     running container
ARG   APP_VERSION        visible                  not visible
ENV   APP_ENV            visible                  visible

You can give an ARG a default (ARG APP_VERSION=dev) or leave it without one (ARG APP_VERSION), in which case it is empty unless --build-arg supplies a value. If you pass a --build-arg that no ARG declares, the build still succeeds and prints no warning, so a typo in the flag name is silent. Always check that the declared and passed names match.

Turning an ARG into an ENV

The standard way to expose a build-time value at run time is to copy it into an ENV:

DOCKERFILE
FROM alpine:3.22
ARG VERSION=0.0.0
ENV APP_VERSION=$VERSION
CMD ["sh", "-c", "echo version $APP_VERSION"]
CONSOLE
$ docker build --build-arg VERSION=2.1.0 -t promote .
$ docker run --rm promote
version 2.1.0
$ docker run --rm -e APP_VERSION=override promote
version override

This is how CI systems stamp a git tag or build number into an image: pass --build-arg VERSION=$(git describe) and let the Dockerfile promote it.

Where an ARG is visible: scope rules

ARG has stricter scope rules than ENV, and the two most important ones involve FROM.

  1. An ARG declared before the first FROM can be used in FROM lines, but it is not visible inside the stage unless you declare it again.
  2. An ARG declared inside a stage is visible only from that line to the end of that stage. In a multi-stage build (Multi-Stage Builds) each stage needs its own declaration.
DOCKERFILE
ARG ALPINE_VERSION=3.22
FROM alpine:${ALPINE_VERSION}
RUN echo "after FROM: ALPINE_VERSION=[$ALPINE_VERSION]"
ARG ALPINE_VERSION
RUN echo "re-declared: ALPINE_VERSION=[$ALPINE_VERSION]"
CONSOLE
$ docker build --progress=plain --no-cache -t scope .
...
#5 0.533 after FROM: ALPINE_VERSION=[]
#6 0.882 re-declared: ALPINE_VERSION=[3.22]
$ docker build --build-arg ALPINE_VERSION=3.21 -t scope2 .
$ docker run --rm scope2 cat /etc/alpine-release
3.21.9

Before the first FROM, the ARG chose the base image: a very useful trick for building the same app on several base versions (--build-arg ALPINE_VERSION=3.21 changed the actual operating system). Inside the stage the variable was empty until re-declared with a bare ARG ALPINE_VERSION, which picks up the global default.

Docker also provides predefined build arguments you can use without declaring them: the proxy variables (HTTP_PROXY, HTTPS_PROXY, NO_PROXY) and the platform variables TARGETPLATFORM, TARGETOS, TARGETARCH, BUILDPLATFORM and friends. The platform ones need an ARG TARGETARCH line inside the stage before you can read them (Multi-Platform Images shows them in action).

ARG and the build cache

Build arguments take part in cache decisions. Docker (BuildKit) re-runs every RUN that comes after a changed ARG, because the argument becomes part of that step's environment and therefore its cache key.

Put the ARG at the top, and one changed value rebuilds the expensive step too:

DOCKERFILE
FROM alpine:3.22
ARG BUILD_ID=0
RUN echo expensive step
RUN echo "id $BUILD_ID"
CONSOLE
$ docker build --progress=plain --build-arg BUILD_ID=1 -t cache-a .
...
#5 [2/3] RUN echo expensive step
#6 [3/3] RUN echo "id 1"

Both RUN lines executed. Declaring the ARG just before the place that needs it lets everything above stay cached:

DOCKERFILE
FROM alpine:3.22
RUN echo expensive step
ARG BUILD_ID=0
RUN echo "id $BUILD_ID"
CONSOLE
$ docker build --progress=plain --build-arg BUILD_ID=1 -t cache-b .
...
#5 [2/3] RUN echo expensive step
#5 CACHED
#6 [3/3] RUN echo "id 1"

The rule: declare an ARG as late as possible. Lesson The Build Cache explains cache keys in full.

Secrets do not belong in ENV or ARG

This is the most important section of the lesson. Both instructions are stored in plain text in the image, and anyone who can pull the image can read them.

DOCKERFILE
FROM alpine:3.22
ARG API_TOKEN
RUN echo "token length: ${#API_TOKEN}"
ENV DB_PASSWORD=hunter2
CONSOLE
$ docker build --build-arg API_TOKEN=abc123secret -t leak .
$ docker history leak --no-trunc --format '{{.CreatedBy}}'
ENV DB_PASSWORD=hunter2
RUN |1 API_TOKEN=abc123secret /bin/sh -c echo "token length: ${#API_TOKEN}" # buildkit
ARG API_TOKEN=abc123secret
...
$ docker run --rm leak env | grep -E 'DB_|API_'
DB_PASSWORD=hunter2

Two separate leaks, both real:

  • ENV is permanent. The password is in the image configuration and in the environment of every container, visible to docker inspect, to any child image, and to anything the app logs when it prints its environment.
  • ARG is not hidden either. The value is recorded in the image history, even though it is absent from the container's environment. "It is only at build time" is not the same as "it is secret".

Deleting the variable in a later layer does not help, because earlier layers and history are immutable. The correct tools are BuildKit secret mounts for build-time secrets and run-time injection (environment from your orchestrator, mounted files, a secrets manager) for run-time ones. See Managing Secrets and BuildKit and buildx.

Never put passwords, tokens, private keys or connection strings in ENV or ARG, and never COPY a .env file with real credentials into an image. If an image with a secret in it was ever pushed, treat the secret as compromised and rotate it.

A classic case: DEBIAN_FRONTEND

Debian and Ubuntu packages sometimes ask questions while installing (time zone, keyboard layout). Nobody can answer in a build, so the build may hang or fail. Setting DEBIAN_FRONTEND=noninteractive tells the package tools not to ask. It is only needed during the build, so make it an ARG; then it does not leak into running containers, where a later interactive apt session would behave differently:

DOCKERFILE
FROM ubuntu:24.04
ARG DEBIAN_FRONTEND=noninteractive
RUN apt-get update \
 && apt-get install -y --no-install-recommends tzdata \
 && rm -rf /var/lib/apt/lists/*

Many Dockerfiles write ENV DEBIAN_FRONTEND=noninteractive instead. That works, but the value then stays in every container made from the image. A test on a small Alpine image shows the scoping of the ARG form: set while a RUN executes, gone at run time.

CONSOLE
$ docker build -t scope-demo .
#5 [2/2] RUN echo "during build: [$DEBIAN_FRONTEND]"
#5 3.785 during build: [noninteractive]
$ docker run --rm scope-demo
at runtime: []

A one-line alternative that never touches the image metadata is to set the variable for a single command: RUN DEBIAN_FRONTEND=noninteractive apt-get install -y tzdata.

ENV vs. ARG at a glance

Question ARG ENV
Available during docker build Yes, from its declaration Yes, from its declaration
Available in a running container No Yes
Set from the command line docker build --build-arg NAME=value docker run -e NAME=value or --env-file
Can be declared before FROM Yes (only for FROM lines) No
Stored in image history Yes Yes
Inherited by child images No (declare it again) Yes
Good for Versions, base image tags, feature switches at build Defaults for the app: port, mode, paths
Safe for secrets No No

Practical habits

  • Use ARG for things that change how the image is built (a base tag, a package version, a git commit to label the image). Use ENV for things the application reads when it runs.
  • Give every ARG a sensible default so a plain docker build . works.
  • Pin versions with ARGs at the top of the Dockerfile only when you really want them to be overridable; declare per-stage arguments close to where they are used.
  • Prefer a small set of ENV defaults in the Dockerfile and let the deployment (Compose file, orchestrator) override them. In Compose that is the environment: key (Environment, Variables and Secrets).
  • Remember that ENV is inherited: if your base image already sets PATH or JAVA_HOME, your ENV PATH=... should append (ENV PATH="/app/bin:${PATH}") rather than replace.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You build with docker build --build-arg VERSION=2 . where the Dockerfile has ARG VERSION=1 and no ENV. What does echo $VERSION print inside a container started from the image?

    ARG values exist only during the build. Unless you copy the value into an ENV, the running container does not have the variable.
  2. 2. A Dockerfile has ENV ADDR=0.0.0.0:${PORT} after ENV PORT=8080. You run the container with -e PORT=9. What is ADDR?

    Docker expands variables in ENV while building and stores the final string in the image. A run-time override of PORT does not rewrite it.
  3. 3. Where must an ARG be declared to be used in a FROM line, and is it then visible inside the stage?

    An ARG before the first FROM can parameterize FROM, but its scope ends there. Inside the stage you repeat ARG NAME (no value) to use the default.
  4. 4. Why is passing a token with --build-arg TOKEN=... not a safe way to hand a secret to the build?

    Build arguments are stored with the build steps. docker history shows them in plain text. Use BuildKit secret mounts instead.
  5. 5. Where should you declare an ARG that only the last RUN needs, to keep earlier steps cached when its value changes?

    A changed ARG invalidates the cache for every RUN that follows its declaration. Declaring it late keeps the earlier, expensive steps cached.

Summary

  • ENV stores variables in the image: they are visible during the build after the declaration and in every container, and can be overridden with -e or --env-file.
  • ARG defines build-time variables, set with --build-arg. They are not in the container environment; promote one with ENV NAME=$ARG_NAME if the app needs it.
  • Variables are expanded at build time inside ENV; later run-time overrides do not recompute them.
  • An ARG before the first FROM selects the base image but must be re-declared inside the stage to be read there.
  • A changed ARG invalidates the cache for every later RUN, so declare it as late as possible.
  • export inside a RUN lasts only for that instruction; use ENV for persistence.
  • Both ENV and ARG values show up in the image (docker inspect, docker history). Never store secrets in them; use BuildKit secret mounts and run-time injection.

Next: WORKDIR, USER, EXPOSE and LABEL