TExcelTAD
Home › Docker › WORKDIR, ENV and ARG

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

dockerfile
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, COPY and ADD, 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.

python · try it yourself
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:

dockerfile
ENV PYTHONUNBUFFERED=1 \
    PIP_NO_CACHE_DIR=1 \
    APP_HOME=/app
WORKDIR $APP_HOME

Later 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.

dockerfile
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_VERSION

Note: # starts a comment only at the beginning of a line. In ENV MODE=prod # default, the # default part is handed to ENV as more arguments and the build fails. (In shell-form RUN it happens to work only because the shell itself treats # as a comment.)

bash
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:

  1. An ARG declared before the first FROM can be used in FROM lines only. To use it inside a stage, declare it again (just ARG PYTHON_VERSION, without a value) after the FROM.
  2. Each stage has its own scope: an ARG declared 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:

python · try it yourself
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: ARG values are recorded in the image metadata and visible with docker history. Never pass secrets as build args.

Test yourself

After WORKDIR /app and WORKDIR api, what is the working directory?

  1. /api
  2. /app/api
  3. api
  4. /app

Which variables are available inside a running container?

  1. Both ARG and ENV values
  2. Only ARG values
  3. Only ENV values (plus anything passed with -e)
  4. Neither

ARG NODE=22 appears before FROM node:${NODE}. Inside the stage, RUN echo $NODE prints nothing. Why?

  1. ARG values cannot be echoed
  2. An ARG before FROM is only in scope for FROM lines; re-declare ARG NODE inside the stage
  3. The variable must be lowercase
  4. You must use ENV in FROM