CodeBlanks Logo Icon CodeBlanks

The ENV instruction

Learn to define variables in a Dockerfile with ENV.

The ENV instruction

ENV adds a permanent environment variable to the image in the Dockerfile. It is valid both in later build steps and in the running container; it can be overridden with docker run -e:

FROM python:3.12-slim
ENV PYTHONUNBUFFERED=1 \
    PORT=8000
WORKDIR /app
CMD ["python", "app.py"]

PYTHONUNBUFFERED=1 makes Python write output without buffering; that way logs appear immediately in docker logs.

Paths and versions with ENV

ENV variables can be used in later instructions with $NAME. This lets you define a version number or install path in one place:

ENV APP_HOME=/opt/app
WORKDIR $APP_HOME
ENV PATH="$APP_HOME/bin:$PATH"
COPY bin/ $APP_HOME/bin/

Secret values like passwords should not be written into the image with ENV: docker history and docker inspect show them.

Practice Defaults with ENV

Write a Dockerfile based on node:20-alpine: define the variables NODE_ENV=production and PORT=3000 with ENV; WORKDIR /app; COPY . .; EXPOSE 3000; CMD is node server.js in exec form.

Starter code

terminal
# buraya yaz

Sample solution

terminal
FROM node:20-alpine
ENV NODE_ENV=production PORT=3000
WORKDIR /app
COPY . .
EXPOSE 3000
CMD ["node", "server.js"]

Expected output

[+] Building 2.9s (8/8) FINISHED
 => naming to docker.io/library/web:latest done

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 With ENV PORT=8000 in the image, what is PORT in the container with docker run -e PORT=9000 img?

  • 8000
  • Empty
  • 8000,9000
  • 9000 Correct answer

Explanation: The run-time value replaces the default in the image.

2 Make Python output unbuffered.

Question
____ PYTHONUNBUFFERED=1
Answer
ENV PYTHONUNBUFFERED=1

Explanation: ENV is valid both in the build and at run time.

3 Match.

Term Meaning
ENV Permanent variable in the image
-e Overrides at run time
$APP_HOME Using the variable
PYTHONUNBUFFERED Immediate logs

All lessons in Beginner