WORKDIR, ENV and ARG
These three instructions set up the environment your later instructions, and your running container, work in. WORKDIR sets the current directory, ENV sets environment variables that persist into the container, and ARG defines build-time variables that exist only while building.
WORKDIR
WORKDIR /app
# copies into /app
COPY . .
WORKDIR src
# prints /app/src
RUN pwd- It creates the directory if it does not exist.
- A relative path is resolved against the previous
WORKDIR. - It applies to
RUN,CMD,ENTRYPOINT,COPYandADD, and is the directory the container starts in.
Use WORKDIR instead of RUN cd /app && ...: each RUN starts a fresh shell, so a cd does not carry over to the next instruction.
import posixpath
def track(instructions):
cwd = "/"
for inst in instructions:
name, _, arg = inst.partition(" ")
if name == "WORKDIR":
cwd = posixpath.normpath(posixpath.join(cwd, arg))
elif name == "RUN" and arg.startswith("cd "):
# the cd happens in a throwaway shell; cwd is unchanged afterwards
pass
print(f"{inst:<20} cwd = {cwd}")
track(["WORKDIR /app", "RUN cd /tmp", "RUN pwd", "WORKDIR src", "WORKDIR ../tests", "WORKDIR /srv/www"])WORKDIR /app cwd = /app
RUN cd /tmp cwd = /app
RUN pwd cwd = /app
WORKDIR src cwd = /app/src
WORKDIR ../tests cwd = /app/tests
WORKDIR /srv/www cwd = /srv/www
ENV
ENV sets variables for the rest of the build and for every container started from the image:
ENV PYTHONUNBUFFERED=1 \
PIP_NO_CACHE_DIR=1 \
APP_HOME=/app
WORKDIR $APP_HOMELater instructions can reference them as $NAME or ${NAME}. At run time, docker run -e NAME=value overrides an ENV default.
ARG
ARG declares a variable you can set with docker build --build-arg NAME=value. It exists only during the build; it is not present in the running container.
ARG PYTHON_VERSION=3.12
FROM python:${PYTHON_VERSION}-slim
ARG APP_VERSION=dev
LABEL org.opencontainers.image.version=$APP_VERSION
# copy it into ENV if the app needs it at run time
ENV APP_VERSION=$APP_VERSIONNote:
#starts a comment only at the beginning of a line. InENV MODE=prod # default, the# defaultpart is handed toENVas more arguments and the build fails. (In shell-formRUNit happens to work only because the shell itself treats#as a comment.)
docker build --build-arg PYTHON_VERSION=3.13 --build-arg APP_VERSION=2.1.0 -t shop:2.1.0 .Two scoping rules trip everyone up:
- An
ARGdeclared before the firstFROMcan be used inFROMlines only. To use it inside a stage, declare it again (justARG PYTHON_VERSION, without a value) after theFROM. - Each stage has its own scope: an
ARGdeclared in one stage is not visible in the next.
Variable expansion: a model
The builder substitutes $VAR, ${VAR}, ${VAR:-default} (use a default if unset or empty) and ${VAR:+word} (use word only if set). This model applies those rules and the ARG/ENV scoping:
import re
def expand(text, env):
def sub(match):
name, op, word = match.group(1) or match.group(4), match.group(2), match.group(3)
value = env.get(name, "")
if op == ":-":
return value or word
if op == ":+":
return word if value else ""
return value
return re.sub(r"\$\{(\w+)(?:(:[-+])([^}]*))?\}|\$(\w+)", sub, text)
def build(lines, build_args):
scope, runtime_env = {}, {}
for line in lines:
name, _, rest = line.partition(" ")
if name == "FROM":
print(f"FROM {expand(rest, scope)}")
scope = {k: v for k, v in runtime_env.items()} # new stage: global ARGs are gone
elif name == "ARG":
key, _, default = rest.partition("=")
scope[key] = build_args.get(key, default)
elif name == "ENV":
key, _, value = rest.partition("=")
scope[key] = runtime_env[key] = expand(value, scope)
else:
print(f"{name} {expand(rest, scope)}")
print("container env:", runtime_env)
build([
"ARG PY=3.12",
"FROM python:${PY}-slim",
"RUN echo building on python $PY",
"ARG APP_VERSION=dev",
"ENV APP_VERSION=$APP_VERSION",
"ENV LOG_LEVEL=${LOG_LEVEL:-info}",
"RUN echo version=$APP_VERSION ${DEBUG:+debug-mode}",
], build_args={"APP_VERSION": "2.1.0"})FROM python:3.12-slim
RUN echo building on python
RUN echo version=2.1.0
container env: {'APP_VERSION': '2.1.0', 'LOG_LEVEL': 'info'}
Look at the second line of output: $PY is empty inside the stage because the ARG before FROM was never re-declared. And only the ENV values reach the container.
ARG, ENV or neither?
| You need | Use |
|---|---|
| A value that changes how the image is built (a version to download, a base tag) | ARG |
A default the running app reads (PORT, LOG_LEVEL) |
ENV, overridable with docker run -e |
| A password, token or API key | neither: build secrets (RUN --mount=type=secret) or runtime secrets |
Warning:
ARGvalues are recorded in the image metadata and visible withdocker history. Never pass secrets as build args.
Test yourself
After WORKDIR /app and WORKDIR api, what is the working directory?
- /api
- /app/api
- api
- /app
Which variables are available inside a running container?
- Both ARG and ENV values
- Only ARG values
- Only ENV values (plus anything passed with
-e) - Neither
ARG NODE=22 appears before FROM node:${NODE}. Inside the stage, RUN echo $NODE prints nothing. Why?
- ARG values cannot be echoed
- An ARG before FROM is only in scope for FROM lines; re-declare
ARG NODEinside the stage - The variable must be lowercase
- You must use ENV in FROM