Stage 1 · Foundations · Chapter 6 of 20 · 6 min read

Environment variables

Build one image, then configure it differently for development, staging and production without rebuilding. Environment variables are how you hand that configuration in.

? What do the diagram colours mean

key idea / Docker itselfcontainer / good pathhost / watch outproblem / blockedneutral

What an environment variable is

A named string the operating system hands a process when it starts. Docker sets them for the container’s main process, and your code reads them like any other variable.

// Node.js
const port = Number(process.env.PORT ?? 4000);   // values are always strings
const dbHost = process.env.DB_HOST;
if (!dbHost) throw new Error('DB_HOST is not set');
Always strings. process.env.PORT is "4000", and DEBUG=false arrives as the truthy string "false". Convert explicitly, and fail fast when a required variable is missing.

Where the values come from

Where a container's environment comes fromImage defaults from Dockerfile ENV, values from --env-file and values from -e are merged by docker run. A run-time value with the same name replaces the image default. The result is the environment your process reads.Dockerfile ENVPORT=4000 NODE_ENV=production--env-file app.envDB_HOST=postgres-e PORT=5000one value on the command linedocker runrun-time value winscontainer envPORT=5000NODE_ENV=productionDB_HOST=postgresread via process.env
The image supplies defaults; docker run adds to them and replaces any with the same name. PORT=5000 beat the image's 4000.

-e and --env-file

-e KEY=value sets one variable; repeat it for more. -e KEY with no value copies it from your shell. For many values, put KEY=value lines in a file and pass --env-file.

$ docker run -d --name posts -e PORT=4000 -e NODE_ENV=production micro-posts
$ docker run -d --name posts --env-file app.env micro-posts
You writeWhat the container gets
-e PORT, host has no PORTPORT is not set (your default applies)
-e PORT=$PORT, host has no PORTPORT is an empty string: your shell expanded it first
KEY="value" in an env filethe quotes are kept as part of the value
KEY=$OTHER in an env filethe literal text $OTHER; nothing is expanded
Flags go before the image name. docker run micro-posts -e PORT=4000 does not set PORT: everything after the image replaces its CMD. And docker run never reads a .env file on its own; Docker Compose does, with different rules (chapter 11).

Keep env files out of images and Git: add .env to .dockerignore (chapter 4) and .gitignore, and commit a .env.example with fake values.

Defaults in the Dockerfile: ENV

ENV bakes a default into the image. A value from docker run -e with the same name wins, for that one container.

FROM node:22
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
ENV PORT=4000 NODE_ENV=production
CMD ["node", "server.js"]

ENV also applies to the build steps after it. Placed above RUN npm ci, NODE_ENV=production would make npm skip devDependencies and break a later build step that needs them.

ARG versus ENV

When ARG, ENV and -e are visibleA timeline of docker build, image, docker run and container. ARG exists only during docker build. Dockerfile ENV is visible in later build steps, stored in the image and present in every container. Values from -e or --env-file exist only in that one container.docker build--build-argimagestores ENVdocker run-e / --env-filecontainerprocess.envARG: build onlyDockerfile ENV: later build steps, the image, every container-e / --env-file: this container only
ARG ends when the build ends. ENV travels with the image. -e lives in one container.
ARGENV
Set withdocker build --build-argDockerfile; overridden by docker run -e
Running container sees itnoyes
Use forversions, base-image tags, build switchesruntime defaults your app reads

To keep a build-time value at run time, copy it: ARG VERSION then ENV APP_VERSION=$VERSION. An ARG declared before FROM is usable only in FROM lines unless you declare it again after.

Set once, at creation

A container’s environment is fixed when it is created. docker restart keeps the old values; to change one, remove the container and run a new one. Check what it actually got with docker exec posts env or docker inspect -f '{{json .Config.Env}}' posts.

What about passwords and API keys? Environment variables are visible to anyone who can run docker inspect, and ENV/ARG values are saved in the image. Secrets get their own section in chapter 18.

Try it yourself

  1. Step 1 · One variable, and pass-through from the host
    $ docker run --rm -e GREETING=hello alpine:3.20 printenv GREETING
    hello
    $ export TEAM=web
    $ docker run --rm -e TEAM alpine:3.20 printenv TEAM
    web
  2. Step 2 · An env file keeps quotes
    $ printf '# demo\nMODE="debug"\nLEVEL=2\n' > demo.env
    $ docker run --rm --env-file demo.env alpine:3.20 sh -c 'echo "$MODE $LEVEL"'
    "debug" 2
  3. Step 3 · ARG, ENV and an override
    $ mkdir envdemo && cd envdemo
    $ cat > Dockerfile <<'DF'
    FROM alpine:3.20
    ARG VERSION=dev
    ENV APP_VERSION=$VERSION PORT=4000
    CMD ["sh", "-c", "echo version=$APP_VERSION arg=$VERSION port=$PORT"]
    DF
    $ docker build --build-arg VERSION=2.0 -t envdemo .
    $ docker run --rm -e PORT=5000 envdemo
    version=2.0 arg= port=5000

    arg= is empty: the ARG existed only during the build. Its value survived because ENV copied it.

Common mistakeRunning docker exec api echo $PORT and trusting the answer. Your own shell expands $PORT before Docker runs anything, so you see the host’s value, often empty. Use docker exec api printenv PORT or sh -c 'echo $PORT'.

Recap

Quick check

The Dockerfile has ENV PORT=4000. You run docker run -e PORT=5000 micro-posts. What does the app see?

Show answer

Answer: 5000 for this container; the image still says 4000.

The run-time value wins for this container only; the image is unchanged.

You changed a value in app.env and ran docker restart posts. The app still sees the old value. Why?

Show answer

Answer: The env file is read only when the container is created.

Remove the container and docker run --env-file app.env again.

Your build needs VERSION, and the running app should print it too. ARG or ENV?

Show answer

Answer: Both: ARG VERSION, then ENV APP_VERSION=$VERSION.

ARG receives --build-arg; copying it into ENV keeps it in every container.