Sub topic 6
Configuration with ENV and ARG
This chapter assumes you can write a basic Dockerfile with FROM, COPY, RUN, and CMD. You should also be able to run docker build and docker run. It covers the two instructions that carry configuration values, ENV and ARG. They look alike but have different lifetimes, and mixing them up causes bugs and leaked secrets.
Two kinds of configuration
A Dockerfile has two moments when a value can matter:
- Build time: while
docker buildruns the instructions to produce the image. - Run time: while a container started from that image is running.
ARG defines a variable that exists only at build time. ENV defines a variable that is available during the build after the instruction and is also stored in the image. Every container started from the image gets it as an environment variable.
| Property | `ARG` | `ENV` |
|---|---|---|
| Available during later build instructions | Yes, from the line where it is declared | Yes, from the line where it is declared |
| Present in the running container | No | Yes |
| Set from the command line at build | `docker build --build-arg NAME=value` | Not directly |
| Overridden at run time | Not applicable | `docker run -e NAME=value` or `--env-file` |
| Stored in image metadata | The name and default are recorded in history | The value is stored in the image config |
| Typical use | Base image version, application version, build flags | `NODE_ENV`, `PORT`, `PATH` additions |
ENV: values that stay in the image
ENV sets an environment variable for all later instructions and for containers created from the image. It has two forms:
ENV NODE_ENV=production
ENV PORT=3000 LOG_LEVEL=info
ENV GREETING="hello from the image"The NAME=value form accepts several pairs in one instruction, and each ENV instruction adds a layer of metadata. Group related variables into one instruction with line continuations to keep the Dockerfile tidy. There is also an older ENV NAME value form with no equals sign. It accepts only one variable per instruction, so prefer NAME=value.
Because ENV values are baked into the image, they act as defaults. Anyone running the container can replace them:
docker run --rm -e LOG_LEVEL=debug myapp:1.0 env
docker run --rm --env-file ./prod.env myapp:1.0 envThe trailing env command replaces the image's default command and prints the container's environment. Use it to check what the container actually sees.
ENV values carry through the build
An ENV value is visible to every later RUN instruction too. This means ENV can change how the build behaves, not only how the app runs. For example, ENV NODE_ENV=production before RUN npm ci makes npm skip development dependencies in some configurations. Place ENV instructions deliberately: a variable set before an expensive RUN becomes part of that layer's cache key, and changing it invalidates the cache from that point on.
ARG: values that exist only during the build
ARG declares a build-time variable, optionally with a default:
ARG APP_VERSION=devYou supply a different value on the command line:
docker build --build-arg APP_VERSION=1.0.1 -t myapp:1.0.1 .If you pass --build-arg for a name that the Dockerfile never declares with ARG, the build prints a warning that the argument was not consumed. It does not fail, and the value is ignored.
An ARG is not an environment variable of the final container. Run env in a container and you will not find it. The value can still show up in docker history output and in image metadata when a RUN instruction used it. That is why build arguments are the wrong place for passwords or tokens.
Scope: before FROM and after FROM
Scope is the most common source of confusion. An ARG declared before the first FROM is available only to FROM lines. It is not visible inside the stage. To use it in the stage, declare it again, without a default, after FROM:
ARG NODE_VERSION=20
FROM node:${NODE_VERSION}-slim
ARG NODE_VERSION
RUN echo "Building with Node ${NODE_VERSION}"The second ARG NODE_VERSION line re-imports the value from the global scope. Without it, ${NODE_VERSION} expands to an empty string inside RUN.
In a multi-stage build, each stage starts with its own scope. An ARG declared in one stage is not visible in the next. Declare it in every stage that needs it.
Using variables in instructions
Both ARG and ENV values can be referenced as $NAME or ${NAME} in several instructions: ADD, COPY, ENV, EXPOSE, FROM, LABEL, STOPSIGNAL, USER, VOLUME, and WORKDIR. RUN, CMD, and ENTRYPOINT pass the text to a shell or program, so expansion there depends on the form you use (see below).
The braced form supports defaults and alternates:
${NAME:-fallback}expands tofallbackifNAMEis unset or empty.${NAME:+alternate}expands toalternateifNAMEis set and non-empty, and to nothing otherwise.
A complete Dockerfile that combines these pieces:
ARG NODE_VERSION=20
FROM node:${NODE_VERSION}-slim
ARG APP_VERSION=dev
ENV NODE_ENV=production \
PORT=3000
LABEL org.opencontainers.image.version=${APP_VERSION}
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
EXPOSE ${PORT}
USER node
CMD ["node", "server.js"]Build and run it with overrides:
docker build \
--build-arg NODE_VERSION=22 \
--build-arg APP_VERSION=1.0.1 \
-t myapp:1.0.1 .
docker run --rm -e PORT=8080 -p 8080:8080 myapp:1.0.1This assumes server.js reads process.env.PORT. The NODE_VERSION and APP_VERSION values are fixed in the image at build time. The PORT value is only a default, and docker run -e replaces it.
ARG and ENV together
To make a build argument available at run time, copy it into an ENV:
ARG APP_VERSION=dev
ENV APP_VERSION=${APP_VERSION}The ARG receives the value from --build-arg, and the ENV stores it in the image. Now the running container sees APP_VERSION.
If an ARG and an ENV share a name, the ENV value wins after the ENV line. Docker documents this precedence: an ENV instruction always overrides an ARG of the same name. Avoid the overlap unless you use the copy pattern above deliberately.
Cache effects
ARG interacts with the build cache. A changed build argument value invalidates the cache starting at the first instruction that uses it, and for RUN this check includes the argument's value. The instruction does not need to mention the variable in its command text. Put ARG lines as late as possible, just before the instruction that needs them. An ARG APP_VERSION at the top that changes on every release forces every later RUN to rebuild.
FROM node:20-slim
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
ARG APP_VERSION=dev
LABEL org.opencontainers.image.version=${APP_VERSION}Here the dependency install stays cached when the version changes, because the ARG comes after it.
Exec form and variable expansion
Variables in CMD and ENTRYPOINT behave differently depending on form. Exec form (a JSON array) does not run a shell, so nothing expands $PORT:
FROM alpine:3.20
ENV PORT=3000
CMD ["echo", "listening on $PORT"]This prints the literal text listening on $PORT. To get expansion, either use shell form or call a shell explicitly:
FROM alpine:3.20
ENV PORT=3000
CMD ["sh", "-c", "echo listening on $PORT"]The usual approach is to let the application read its own environment, as server.js does above. That keeps CMD in exec form and avoids a shell between Docker and your process. Without a shell as the parent, signals such as SIGTERM from docker stop reach your process directly.
Secrets do not belong here
Both instructions record values in places other people can read:
ENVvalues appear indocker inspectand in every container's environment.ARGvalues used byRUNcan appear indocker historyand in build provenance metadata.
Common errors
- Empty variable after
FROM: you declared theARGbeforeFROMand did not redeclare it in the stage. - "One or more build-args were not consumed" warning: the name in
--build-arghas no matchingARG. Check for typos. - Variable not expanded in
CMD: you used exec form, which has no shell. - Run-time override ignored: you tried
docker run -eon something defined byARG. Only theENVcopy exists in the container. - Cache rebuilds on every release: an
ARGwith a changing value sits too early in the file.
Exercise
A Dockerfile starts with ARG BASE_TAG=3.20, then FROM alpine:${BASE_TAG}, then RUN echo "tag is ${BASE_TAG}". The build prints "tag is " with nothing after it. What is wrong, and how do you fix it? Also, how would you make the value visible inside a running container?
Show answer
An ARG declared before FROM is only in scope for FROM lines. Add ARG BASE_TAG after FROM alpine:${BASE_TAG} so the stage re-imports it, and the RUN will print 3.20. To expose it in a running container, add ENV BASE_TAG=${BASE_TAG} after the second ARG, because ARG values do not exist in the container environment.
Exercise
You build with docker build --build-arg API_TOKEN=abc123 -t app . so that a RUN step can download a private package. Name two places the token can be exposed, and say what you should use instead.
Show answer
The token can appear in docker history output, which shows the RUN command with its build arguments, and in image or build provenance metadata that other people can read. If you also copied it into an ENV, it would be in docker inspect and every container's environment. Use a BuildKit secret mount (RUN --mount=type=secret,... with docker build --secret), which exposes the value only to that one RUN step and does not store it in the image.