How to Use Environment Variables in Docker and Docker Compose

Environment variables are how most containers get their configuration: a database URL, a log level, a feature flag. Docker has several ways to set them, at build time and at run time, and Compose adds a .env file that does something different from what most people expect. When a value is not what you think it is, the cause is usually one of these layers overriding another.
This post covers docker run -e and --env-file, the Compose environment, env_file and .env options and their order of precedence, default and required values, ENV, ARG and PATH in a Dockerfile, and how to check what a container really sees.
TLDR
| Where | Example | When it applies |
|---|---|---|
docker run -e |
docker run -e LOG_LEVEL=debug myapp |
That one container |
docker run --env-file |
docker run --env-file app.env myapp |
That one container |
Compose environment |
environment: { LOG_LEVEL: debug } |
Every container of the service |
Compose env_file |
env_file: app.env |
Every container of the service |
Compose .env file |
TAG=1.4 next to compose.yaml |
Fills in ${TAG} in the Compose file only |
Dockerfile ENV |
ENV PATH="/opt/app/bin:${PATH}" |
The build and every container of the image |
Dockerfile ARG |
ARG VERSION=1.4 |
The build only |
The .env file is not passed into containers. It only fills in ${VARIABLE} placeholders in compose.yaml. To check the result, run docker compose config.
Prerequisites
- Docker Engine or Docker Desktop with the Compose plugin (
docker compose version). - A service to test with. The examples use small images such as
alpine:3.24.
How Do I Pass Environment Variables to a Docker Container?
Use -e (or --env) once per variable:
docker run --rm -e APP_ENV=production -e LOG_LEVEL=info alpine:3.24 env
-e NAME without a value copies the variable from your shell. That keeps the value out of the command line:
export API_TOKEN=... # set it in your shell first
docker run --rm -e API_TOKEN myapp
For many variables, put them in a file and pass it with --env-file:
# app.env: one VARIABLE=value per line, lines starting with # are comments
APP_ENV=production
LOG_LEVEL=info
DATABASE_URL=postgresql://app@db:5432/app
docker run --rm --env-file app.env myapp
docker run --env-file takes each value literally. GREETING="hello" sets the value to "hello", quotes included, and $OTHER is not expanded. Leave the quotes out. Compose env_file files follow other rules, see below.
How Do I Set Environment Variables in Docker Compose?
Use environment for a few values and env_file for many. Both set variables inside the containers of the service:
services:
api:
image: myorg/api:${TAG:-latest}
environment:
APP_ENV: production
LOG_LEVEL: ${LOG_LEVEL:-info} # from the shell or .env, with a default
API_TOKEN: # no value: copied from the shell that runs docker compose
env_file:
- path: ./api.env
required: false # do not fail when the file does not exist
environment also accepts a list (- APP_ENV=production). Use one form per service, not both.
What Does the .env File Do?
Compose reads a file called .env in the project directory (the directory of compose.yaml) and uses it to fill in placeholders in the Compose file. It does not add those variables to any container:
# .env
TAG=1.4.2
POSTGRES_PASSWORD=change-me
services:
db:
image: postgres:18
environment:
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} # filled in from .env
api:
image: myorg/api:${TAG} # filled in from .env
Here db gets POSTGRES_PASSWORD because the Compose file passes it on. api does not get TAG or POSTGRES_PASSWORD as environment variables at all. If a container needs a variable from .env, name it under environment, or load the file with env_file: .env.
Use another file with docker compose --env-file .env.staging up -d. To see the final values, run docker compose config: it prints the Compose file with every placeholder filled in, and shows a warning for each variable that is not set.
Default Values and Required Variables
Placeholders support the shell's default and error forms:
| Syntax | Result |
|---|---|
${VAR} |
The value, or an empty string and a warning if VAR is not set |
${VAR:-default} |
default if VAR is unset or empty |
${VAR-default} |
default only if VAR is unset |
${VAR:?message} |
Stop with message if VAR is unset or empty |
${VAR?message} |
Stop with message only if VAR is unset |
$$VAR |
A literal $VAR, for a variable that the container's shell expands |
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env} makes docker compose up fail at once with a clear message, instead of starting a database without the setting you expected.
Which Value Wins?
Two different orders apply. For placeholders in the Compose file, a variable in your shell overrides the same variable in .env. For the environment inside the container, Compose uses this order, highest first:
docker compose run -e NAME=valueon the command line.- Values under
environment. - Values from
env_file. ENVin the image's Dockerfile.
A value written as ${VAR} in environment or in an env_file is filled in first, from the shell or .env, and then takes part in this order like any other value.
So environment: { LOG_LEVEL: warn } beats LOG_LEVEL=debug in an env_file, and both beat the image's ENV LOG_LEVEL=info. Unlike docker run --env-file, Compose env_file files support quotes and ${VAR} placeholders.
After you change a variable, run docker compose up -d. Compose recreates the services whose environment changed. docker compose restart does not apply changes, as rebuild, restart and upgrade with Compose shows.
How Do I Set Environment Variables in a Dockerfile?
ENV sets a variable for the following build steps and for every container of the image. ARG sets a variable for the build only:
FROM python:3.14-slim
# Build time only: docker build --build-arg APP_VERSION=1.4.2 .
ARG APP_VERSION=dev
# Both are visible in the running container
ENV APP_VERSION=${APP_VERSION} \
PYTHONUNBUFFERED=1
Keep comments on their own lines. In ENV and ARG, a # after the value is not a comment: depending on the instruction, it becomes part of the value, more arguments, or a syntax error.
Use ENV for defaults that the app needs, and override them at run time with -e or Compose. Use ARG for values that only the build needs, such as a version to download. Multiple build arguments covers ARG in detail. Values of both end up in the image metadata or history, so neither is a place for passwords.
How Do I Update PATH in a Dockerfile?
Prepend or append to the existing value with ENV:
FROM ubuntu:24.04
RUN mkdir -p /opt/tools/bin \
&& printf '#!/bin/sh\necho "Hello from PATH"\n' > /opt/tools/bin/hello \
&& chmod +x /opt/tools/bin/hello
ENV PATH="/opt/tools/bin:${PATH}"
CMD ["hello"]
docker build -t path-demo . && docker run --rm path-demo
# Hello from PATH
- Always include
${PATH}.ENV PATH=/opt/tools/binalone removes/usr/binand the other defaults, and most commands stop working. RUN export PATH=...does not work: eachRUNis a new shell, and the change is lost after that line.- A script needs a
#!line like the one above. Without it, the exec-formCMD ["hello"]fails withexec format error, because no shell is there to run the file. - Many images already set
PATHfor their own tools, such as/usr/local/binor/opt/venv/bin. Check withdocker run --rm myimage printenv PATH.
How Do I Check the Environment of a Running Container?
docker exec web printenv # everything the container's processes see
docker exec web printenv LOG_LEVEL # one variable
docker compose exec api env # the same for a Compose service
docker inspect -f '{{json .Config.Env}}' web # what Docker set at create time
docker inspect shows the variables from the image and the run command. printenv shows what a new process in the container gets. Neither shows variables that the app's entrypoint script sets for itself.
How Do I Keep Secrets Out of Environment Variables?
Environment variables are easy to read: docker inspect prints them, child processes inherit them, and crash reports and debug pages often include them. For passwords and keys:
Use secret files. Compose
secretsmount a file at/run/secrets/<name>inside the container:services: db: image: postgres:18 environment: POSTGRES_PASSWORD_FILE: /run/secrets/db_password secrets: - db_password secrets: db_password: file: ./secrets/db_password.txtMany official images, such as
postgresandmysql, read a*_FILEvariable for exactly this case.Never commit
.envfiles with real values. Commit a.env.examplewith the variable names and safe placeholders, and add.envto.gitignore.Never pass secrets with
ARGorENV. Use build secrets (RUN --mount=type=secret) for values that only the build needs, as shown in use secrets in a Docker build.
Related Resources
- How to rebuild, restart and upgrade a Compose container: which command applies a changed variable
- How to use multiple build arguments in Docker build:
ARGand--build-arg - Introduction to Docker: Docker Compose
- Docker security checklist: secrets, users and images
- Docker terminal simulator: practice
-eand Compose in the browser - Docker quiz: check what you know
Try it hands-on
Run the commands from this article in the browser. Nothing to install.
Docker Terminal Simulator
Practice Docker commands in an interactive browser terminal. Learn images, containers, logs, exec, Dockerfile builds, volumes, networks, and Docker Compose with a live Docker daemon visualization.
Container Security Challenge
Six real docker run commands, each carrying a flag that hands an attacker the host. Click the dangerous ones, then see the actual escape path and what to grant instead. Covers the Docker socket, --privileged, host PID namespace, SYS_ADMIN and unconfined AppArmor, plus one command with nothing wrong with it.
We earn commissions when you shop through the links below.
Bitrise
Managed runners for GitHub Actions
Bitrise Build Hub runs your GitHub Actions jobs on M4 Macs and AMD Linux machines. Change runs-on and keep your workflows, secrets and logs on GitHub.
Atomsized
AWS platform engineering and GitOps
Design and automation for reliable AWS and Kubernetes platforms, safer delivery workflows, and preview and UAT environments your engineers can understand and own.
DigitalOcean
Cloud infrastructure for developers
Simple, reliable cloud computing designed for developers
DevDojo
Developer community & tools
Join a community of developers sharing knowledge and tools
SMTPfast
Developer-first email API
Send transactional and marketing email through a clean REST API. Detailed logs, webhooks, and embeddable signup forms in one dashboard.
QuizAPI
Developer-first quiz platform
Build, generate, and embed quizzes with a powerful REST API. AI-powered question generation and live multiplayer.
Want to support DevOps Daily and reach thousands of developers?
Become a SponsorTags
Found an issue?
Related Posts
Also worth your time on this topic
How to Use Multiple Build Arguments in Docker Build
Learn how to pass multiple build-time variables to Docker builds using --build-arg, set default values in Dockerfiles, and use build arguments for environment-specific configurations.
Running Docker Containers on Your Linux Server
Install Docker and Docker Compose on Ubuntu, run your first container, deploy a WordPress stack with docker-compose, and set up Nginx as a reverse proxy in front of your containers.
60 minutes
Dockerfile Best Practices
What is the difference between a Docker image and a container? What are some Dockerfile best practices?
junior