How to Set Docker Environment Variables [With Examples]

How to Set Docker Environment Variables [With Examples]
Published on Oct 10, 2023 Updated on Mar 19, 2026

Docker environment variables pass configuration data into containers at runtime. They control application behavior such as database connection strings, API keys, feature flags, and log levels, without hardcoding values into images or source code.

Environment variables make containers portable. The same image runs in development, staging, and production with different configurations, and you never rebuild the image to change a setting. Docker provides multiple ways to set these variables: in a Dockerfile, through CLI flags, via .env files, and with Docker Compose.

This tutorial covers each method with practical examples. You will learn how to define variables in a Dockerfile using ENV and ARG, pass them at runtime with docker run, manage them in Docker Compose files, and understand the precedence rules that determine which value wins when the same variable appears in multiple places.

#What are Docker environment variables?

Docker environment variables are constant values that apply to all the applications running within a Docker container. These variables are used in many scenarios, such as to define the behavior of an application or script, configure parameters for Docker images, and store important credentials like database credentials and API secrets.

What's more, environment variables in Docker are critical to enhancing the container's portability and flexibility. Environment variables let you adjust settings based on where you deploy the container without recreating the whole image and allow you to inject configurations at run time, enabling the container to work in various places and improve portability.

Ready to supercharge your Docker infrastructure? Scale effortlessly and enjoy flexible storage with Cherry Servers bare metal or virtual servers. Eliminate infrastructure headaches with free 24/7 technical support, pay-as-you-go pricing, and global availability.

#1. How to set environment variables in Dockerfile

A Dockerfile specifies everything it needs to build a Docker image. You can define two types of variables in the Dockerfile:

  • Type 1: ENV - environment variables

  • Type 2: ARG - build time variables

The ENV contains environment variables that will be applied to any container built from it. You can specify the variables according to the following format.

ENV env_variable_name=value

The following shows an example of a Dockerfile with environmental variables:

# syntax=docker/dockerfile:1

FROM python:3.12-alpine

WORKDIR /code

ENV FLASK_APP=app.py \
    FLASK_RUN_HOST=0.0.0.0 \
    PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1

RUN apk add --no-cache gcc musl-dev linux-headers

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

EXPOSE 5000

COPY . .

RUN adduser -D appuser && chown -R appuser:appuser /code
USER appuser

CMD ["flask", "run"]

The requirements.txt file should sit in the same directory as your Dockerfile. List the Python packages your application depends on, one per line. For a Flask app, the file might look like this:

flask  
gunicorn  
requests

Build the image from the Dockerfile using the docker build command. The -t flag assigns a name to the image.

Command Line
docker build -t my-web-app .

Then start a container from the image:

Command Line
docker run -d -p 5000:5000 my-web-app

The applications and tasks inside the container can now access the environment variables you defined in the Dockerfile. For example, FLASK_APP and FLASK_RUN_HOST are available to Flask without any extra flags.

#ARG vs ENV: key differences

ARG and ENV both define variables in a Dockerfile, but they serve different purposes:

ARG ENV
Available during Build time only Build time and runtime
Persists in container No Yes
Override method --build-arg flag -e flag or --env-file
Use case Version numbers, build flags App config, credentials, paths

A common pattern passes an ARG value into an ENV so it persists at runtime:

ARG APP_VERSION=1.0  
ENV APP_VERSION=${APP_VERSION}

The ARG sets the value during build, and the ENV instruction carries it forward into every container that runs from the image. Without the ENV line, the variable disappears after the build completes.

#2. How to view environment variables in Docker

Docker provides a few options for inspecting and viewing the environmental variables currently set in the containers for debugging purposes.

#Option 1: Use docker inspect command

You can use the Docker inspect command to see what environmental variables have been set in your container or the Docker image, and check the Env part of the JSON that generates. You need to specify the container or image ID.

Command Line
docker inspect <containerId>/<Image_id>

To view only the environmental variables, use the following format of the inspect command.

Command Line
docker inspect --format '' <containerId>/<Image_id>

Let’s take another example of a running container whose details are shown below:

Command Line
docker ps

CONTAINER ID  IMAGE  COMMAND                CREATED        STATUS        PORTS                                   NAMES

019f57f5457d  nginx  "/docker-entrypoint.…" 12 seconds ago Up 10 seconds 0.0.0.0:8080->80/tcp, [::]:8080->80/tcp strange_chatelet
Command Line
docker inspect --format '' 019f57f5457d

[PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin NGINX_VERSION=1.29.5 NJS_VERSION=0.9.5 NJS_RELEASE=1~trixie ACME_VERSION=0.3.1 PKG_RELEASE=1~trixie DYNPKG_RELEASE=1~trixie]

#Option 2: Use docker exec command

Another way to see the configured environment variables is using Docker exec command. Use the docker exec command following the format.

Command Line
docker exec <containerID> env
Command Line
docker exec 019f57f5457d env
 
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin  
HOSTNAME=019f57f5457d  
NGINX_VERSION=1.29.5  
NJS_VERSION=0.9.5  
NJS_RELEASE=1~trixie  
ACME_VERSION=0.3.1  
PKG_RELEASE=1~trixie  
DYNPKG_RELEASE=1~trixie  
HOME=/root

#Option 3: Use Docker Compose config to verify Compose variables

When working with Docker Compose, run docker compose config to see the fully resolved configuration with all variables substituted. The output shows the actual values that will reach your containers, which helps catch interpolation errors and missing variables before deployment.

Command Line
docker compose config

#3. How to set and override Docker environment variables using docker run command

Docker environment variables are defined in the Docker file or a separate environment file. When starting a container, you can set environmental variables using the command line using the docker run command. You can also override the existing environment variables, specifying new values.

When using the Docker run command, you can specify environmental variables in several ways.

#Option 1: Use the -e option

You can use the -e flag to set or override an environment variable when running a container. You can specify multiple variables by using multiple -e flags.

Command Line
docker run -e env_var=value <imageName>

Following is an example:

Command Line
docker run -e LOG_LEVEL='DEBUG' my-web-app
  
* Serving Flask app 'app.py'  
* Debug mode: off  
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.  
* Running on all addresses (0.0.0.0)  
* Running on http://127.0.0.1:5000  
* Running on http://172.17.0.7:5000  
Press CTRL+C to quit

You can check if it is actually set by checking the images' container id, as stated in the first section.

"Env": [
    "LOG_LEVEL=DEBUG",
    "PATH=/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
    "LANG=C.UTF-8",
    "GPG_KEY=0D96DF4D4110E5C43FBFB17F2D347EA6AA65421D",
    "PYTHON_VERSION=3.7.17",
    "PYTHON_PIP_VERSION=23.0.1",
    "PYTHON_SETUPTOOLS_VERSION=57.5.0",
    "PYTHON_GET_PIP_URL=https://github.com/pypa/get-pip/...",
    "PYTHON_GET_PIP_SHA256=45a2bb8bf2bb5eff16fdd00faef...",
    "FLASK_APP=app.py",
    "FLASK_RUN_HOST=0.0.0.0"
]

Also read: How to manage Linux environment variables

#Option 2: Use the --env-file option

Another way to set or override environmental variables is using the --env-file option.

Command Line
docker run --env-file <env_file_name> <imageName>

For example, we defined the following environmental variables in a dev.env file.

API_KEY=WENMCOMnhfwDWER  
MONGODB_URL=https://monogodbURL:uname:pw
Command Line
docker run --env-file dev.env my-web-app

* Serving Flask app 'app.py'  
* Debug mode: off  
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.  
* Running on all addresses (0.0.0.0)  
* Running on http://127.0.0.1:5000  
* Running on http://172.17.0.7:5000  
Press CTRL+C to quit
"Env": [
    "API_KEY=WENMCOMnhfwDWER",
    "MONGODB_URL=https://monogodbURL:uname:pw",
    "PATH=/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
    "LANG=C.UTF-8",
    "GPG_KEY=0D96DF4D4110E5C43FBFB17F2D347EA6AA65421D",
    "PYTHON_VERSION=3.7.17",
    "PYTHON_PIP_VERSION=23.0.1",
    "PYTHON_SETUPTOOLS_VERSION=57.5.0",
    "PYTHON_GET_PIP_URL=https://github.com/pypa/get-pip/raw/9af82b715db434abb94a0a6f3569f43e72157346/public/get-pip.py",
    "PYTHON_GET_PIP_SHA256=45a2bb8bf2bb5eff16fdd00faef6f29731831c7c59bd9fc2bf1f3bed511ff1fe",
    "FLASK_APP=app.py",
    "FLASK_RUN_HOST=0.0.0.0"
]

In addition, you can also combine both -e and --env-file options to set and override environmental variables. If you set the same environment variable using both options, both the values will be set as Docker environment variables, and what you have defined using the -e option will take precedence.

#4. How to set and override Docker environment variables using Docker Compose

Setting Docker environment variables at run time using the CLI is not a good practice for multi-container applications. Instead, we can use a special configuration file docker-compose.yaml to define all environmental variables.

This file contains all the configurations applicable to the container, and using one command, you can apply them when running the container.

#Option 1: Use the environment attribute in the docker-compose.yaml file.

A typical docker-compose.yaml file will look like this. You can define the environmental variables in the environment section.

docker-compose.yaml
services:
  web:
    build: 
    environment:
      - key1="value1"
      - key1="value1"

Let's first clone the repository at https://github.com/wiztechth/compose-redis/tree/master, which will create a web application.

Command Line
git clone https://github.com/wiztechth/compose-redis/tree/master

Next, define the following environmental variables in the docker-compose.yaml file.

environment:
      - DEBUG=1
      - ENV="staging"
docker-compose.yaml
services:
  web:
    build: .
    ports:
      - "8000:5000"
    environment:
      - DEBUG=1
      - ENV="staging"
  redis:
    image: "redis:alpine"

Execute the following command by going into the application from the command line. It works exactly like the command docker run -e key=value.

Command Line
docker compose up

Next, using the following command, open up a new terminal window and check if the environmental variables you have defined have been applied using the docker compose run command.

Command Line
docker compose run web env

Check how all the variables you have set have been applied. All other environmental variables come from the Dockerfile.

docker compose run web env
PATH=/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin  
HOSTNAME=dc8f375a4aa7  
TERM=xterm  
DEBUG=1  
ENV="staging"  
LANG=C.UTF-8  
GPG_KEY=0D96DF4D4110E5C43FBFB17F2D347EA6AA65421D  
PYTHON_VERSION=3.7.17  
PYTHON_PIP_VERSION=23.0.1  
PYTHON_SETUPTOOLS_VERSION=57.5.0  
PYTHON_GET_PIP_URL=https://github.com/pypa/get-pip/raw/9af82b715db434abb94a0a6f3569f43e72157346/public/get-pip.py  
PYTHON_GET_PIP_SHA256=45a2bb8bf2bb5eff16fdd00faef6f29731831c7c59bd9fc2bf1f3bed511ff1fe  
FLASK_APP=app.py  
FLASK_RUN_HOST=0.0.0.0  
HOME=/root

#Option 2: Specify a separate environment variable file in docker-compose.yaml file

Alternatively, you can use a separate file to define your environmental variables and define that file in the env_file section of the docker-compose.yaml file. For our example, let's create a .env file and specify the following environmental variables with values.

REDIS_PASSWORD=test  
LOG_LEVEL=INFO

Then, include the path in the docker-compose.yaml file in the env_file: section as follows.

docker-compose.yaml
services:
  web:
    build: 
    ports:
      - "8000:5000"
   env_file:
      - .env
  redis:
    image: "redis:alpine"
docker compose run web env  
PATH=/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin  
HOSTNAME=d6b131b5a170  
TERM=xterm  
REDIS_PASSWORD=test  
LOG_LEVEL=INFO  
LANG=C.UTF-8  
GPG_KEY=0D96DF4D4110E5C43FBFB17F2D347EA6AA65421D  
PYTHON_VERSION=3.7.17  
PYTHON_PIP_VERSION=23.0.1  
PYTHON_SETUPTOOLS_VERSION=57.5.0  
PYTHON_GET_PIP_URL=https://github.com/pypa/get-pip/raw/9af82b715db434abb94a0a6f3569f43e72157346/public/get-pip.py  
PYTHON_GET_PIP_SHA256=45a2bb8bf2bb5eff16fdd00faef6f29731831c7c59bd9fc2bf1f3bed511ff1fe  
FLASK_APP=app.py  
FLASK_RUN_HOST=0.0.0.0  
HOME=/root

In addition, you can use the following command to see the environmental variables configured to the application.

Command Line
docker compose config
Outputname: env_variables_test
services:
  redis:
    image: redis:alpine
    networks:
      default: null
  web:
    build:
      context: C:\Users\UPEREP6\Desktop\docker\env_variables_test
      dockerfile: Dockerfile
    environment:
      LOG_LEVEL: INFO
      REDIS_PASSWORD: test
    networks:
      default: null
    ports:
      - mode: ingress
        target: 5000
        published: "8000"
        protocol: tcp
networks:
  default:
    name: env_variables_test_default

Also, you can combine multiple environmental variable files. To check this, rename the .env file as stg.env and specify both the file paths as follows.

services:
  web:
    build: 
    ports:
      - "8000:5000"
    env_file:
      - dev.env
      - stg.env
  redis:
    image: "redis: alpine"
"Env": [
    "MONGODB_PASSWORD=test",
    "REDIS_PASSWORD=test",
    "API_KEY=WENMCOMnhfwDWER",
    "MONGODB_URL=https://monogodbURL:uname:pw",
    "LOG_LEVEL=INFO",
    "PATH=/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
    "LANG=C.UTF-8",
    "GPG_KEY=0D96DF4D4110E5C43FBFB17F2D347EA6AA65421D",
    "PYTHON_VERSION=3.7.17",
    "PYTHON_PIP_VERSION=23.0.1",
    "PYTHON_SETUPTOOLS_VERSION=57.5.0",
    "PYTHON_GET_PIP_URL=https://github.com/pypa/get-pip/raw/9af82b715db434abb94a0a6f3569f43e72157346/public/get-pip.py",
    "PYTHON_GET_PIP_SHA256=45a2bb8bf2bb5eff16fdd00faef6f29731831c7c59bd9fc2bf1f3bed511ff1fe",
    "FLASK_APP=app.py",
    "FLASK_RUN_HOST=0.0.0.0"
]

Specifying environmental variables in a separate file like this makes the containers flexible. For example, you can save the file in any location and give it a specific name, such as dev.env, prod.env, etc., according to the application's environment. Therefore, you can have environment-specific configurations separately to organize your applications.

Tip: Since Docker Compose version 2.24.0, you can mark env files as optional using the required field. Compose silently skips the file if it does not exist, which helps when an override file is present only in certain environments:

env_file:
  - path: ./default.env
    required: true
  - path: ./override.env
    required: false

#Option 3: Set Docker environment variables with Docker Compose at run time

In addition, docker compose also allows setting environment variables in the command line using the --env-file option.

Command Line
docker compose --env-file <environmental_variables_file> up

To see how it works, add the following new sample environmental variable to the .env file you have created.

MONGODB_PASSWORD=test

Then run the application and check the configured environmental variables.

Command Line
docker compose --env-file .env up  
[+] Running 2/2  
✔ Container env_variables_test-redis-1 Running 0.0s  
✔ Container env_variables_test-web-1 Recreated  
Attaching to env_variables_test-redis-1, env_variables_test-web-1  
env_variables_test-web-1 | * Serving Flask app 'app.py'  
env_variables_test-web-1 | * Debug mode: off  
env_variables_test-web-1 | WARNING: This is a development server. Do not use it in a pro...  
env_variables_test-web-1 | * Running on all addresses (0.0.0.0)  
env_variables_test-web-1 | * Running on http://127.0.0.1:5000  
env_variables_test-web-1 | * Running on http://172.18.0.3:5000  
env_variables_test-web-1 | Press CTRL+C to quit
"Env": [
    "MONGODB_PASSWORD=test",
    "REDIS_PASSWORD=test",
    "LOG_LEVEL=INFO",
    "PATH=/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
    "LANG=C.UTF-8",
    "GPG_KEY=0D96DF4D4110E5C43FBFB17F2D347EA6AA65421D",
    "PYTHON_VERSION=3.7.17",
    "PYTHON_PIP_VERSION=23.0.1",
    "PYTHON_SETUPTOOLS_VERSION=57.5.0",
    "PYTHON_GET_PIP_URL=https://github.com/pypa/get-pip/raw/9af82b715db434abb94a0a6f3569f43e72157346/public/get-pip.py",
    "PYTHON_GET_PIP_SHA256=45a2bb8bf2bb5eff16fdd00faef6f29731831c7c59bd9fc2bf1f3bed511ff1fe",
    "FLASK_APP=app.py",
    "FLASK_RUN_HOST=0.0.0.0"
]

#Option 4: Use docker compose run to set one-off environment variables

Another way to set environmental variables is when you use the 'docker compose run' command. The docker compose run executes run one-off commands. This is exactly similar to the docker run command. Similarly, you need to use the e or --env-file option with it.

The environment variables you set in this manner apply only to that particular container run. They will not be preserved for future containers you start from the same image unless you set them again.

For example, the following command will change the value of the variable DEBUG in our web application.

Command Line
docker compose run -e DEBUG=0 web

* Serving Flask app 'app.py'  
* Debug mode: off  
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.  
* Running on all addresses (0.0.0.0)  
* Running on http://127.0.0.1:5000  
* Running on http://172.18.0.2:5000  
Press CTRL+C to quit
"Env": [
    "REDIS_PASSWORD=test",
    "MONGODB_URL=https://monogodbURL:uname:pw",
    "API_KEY=WENMCOMnhfwDWER",
    "LOG_LEVEL=INFO",
    "DEBUG=0",
    "MONGODB_PASSWORD=test",
    "PATH=/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
    "LANG=C.UTF-8",
    "GPG_KEY=0D96DF4D4110E5C43FBFB17F2D347EA6AA65421D",
    "PYTHON_VERSION=3.7.17",
    "PYTHON_PIP_VERSION=23.0.1",
    "PYTHON_SETUPTOOLS_VERSION=57.5.0",
    "PYTHON_GET_PIP_URL=https://github.com/pypa/get-pip/raw/9af82b715db434abb94a0a6f3569f43e72157346/public/get-pip.py",
    "PYTHON_GET_PIP_SHA256=45a2bb8bf2bb5eff16fdd00faef6f29731831c7c59bd9fc2bf1f3bed511ff1fe",
    "FLASK_APP=app.py",
    "FLASK_RUN_HOST=0.0.0.0"
]

#Environment variable precedence

When the same variable appears in multiple places, Docker follows a strict precedence order. The source higher in the list wins:

  1. docker compose run -e (CLI override) — highest priority

  2. environment attribute in compose.yaml

  3. Shell environment variables (exported in your terminal)

  4. --env-file flag passed to docker compose up

  5. env_file attribute in compose.yaml

  6. .env file in the project root (used for Compose interpolation)

  7. ENV instruction in the Dockerfile — lowest priority

A practical example: your Dockerfile sets LOG_LEVEL=info, your .env file sets LOG_LEVEL=debug, and you run docker compose run -e LOG_LEVEL=warn web. The container receives LOG_LEVEL=warn because CLI overrides take priority.

Understanding this order prevents a common debugging headache: a variable appears "stuck" on an old value because a higher-priority source overrides the change you made in a lower-priority file.

For a complete breakdown, see Docker's official environment variable precedence documentation.

#How to use default values and variable substitution

Docker Compose supports shell-style variable substitution in your compose.yaml file. You can reference variables from your .env file or shell environment using ${} syntax and set fallback values so the configuration works even when a variable is missing.

#Set default values with ${VAR:-default}

The :- operator provides a fallback value when the variable is unset or empty:

services:
  web:
    image: "nginx:${NGINX_VERSION:-stable-alpine}"
    ports:
      - "${APP_PORT:-8080}:80"
    environment:
      - LOG_LEVEL=${LOG_LEVEL:-info}

If NGINX_VERSION is not defined in your .env file or shell, Compose uses stable-alpine. If APP_PORT is missing, it defaults to 8080.

#Require a variable with ${VAR:?error}

The :? operator stops Compose with an error message if the variable is not set. Use it for values that must be provided, like database credentials:

services:
  db:
    image: postgres:16
    environment:
      - POSTGRES_PASSWORD=${DB_PASSWORD:?DB_PASSWORD must be set}

Running docker compose up without DB_PASSWORD defined results in an error message and an immediate exit, preventing the container from starting with missing credentials.

#Verify substitution with docker compose config

Always run docker compose config after making changes. The output shows the fully resolved compose file with all variables replaced by their actual values. If a variable is missing and has no default, you will see an empty string or an error. Both are easy to spot before deployment.

#Best practices when setting Docker environment variables

When setting Docker environment variables, it is important to follow some best practices. The following are some important ones you could consider.

  1. Use a separate .env file to set Docker environment variables: it will help you to organize your variables across different environments. However, if you are deploying the Docker repositories, ensure that you add it to the .gitignore file to prevent committing them.

  2. Encrypt and store sensitive data: You should not define sensitive data like passwords and API keys directly in plain text. Use some form of encryption to store them and decrypt them within the application when using them.

  3. Avoid changing environment variables within a running container: to ensure consistency between different environments, never change them at run time. Instead, change after the container is stopped and start a new instance.

  4. Use a standard naming convention: to ensure consistency, use a standard naming convention.

  5. Maintain the environmental variables regularly: Review the defined environment variables regularly to ensure there are no outdated values.

#Troubleshooting common environment variable issues

#Variable not appearing inside the container

The environment or env_file attribute is missing from your compose.yaml service definition. Defining a variable in the .env file alone only makes it available for Compose interpolation (${} syntax in the YAML file). It does not automatically pass the variable into the container. Add an explicit environment or env_file entry for the service.

#Variable has the wrong value

Check the precedence order. A shell-exported variable or a -e CLI flag overrides values from .env and env_file. Run docker compose config to see which value Compose resolves for each variable.

#Interpolation not working in env files

Variable substitution (${VAR}) works inside compose.yaml files but not inside .env files loaded by docker run --env-file. Compose does support interpolation in .env files used for YAML substitution, but env files loaded via the env_file attribute are read as plain key-value pairs. Move interpolation logic into the compose.yaml environment section instead.

#Quotes appearing inside variable values

Quotes in .env files behave differently depending on the context. Unquoted and double-quoted values support interpolation. Single-quoted values are read literally. If your container receives "value" (with quotes) instead of value, remove the surrounding quotes from the .env file entry. Docker does not strip them automatically in all cases.

#ARG value not available at runtime

ARG variables exist only during the build process. They do not persist into the running container. To carry an ARG value into runtime, assign it to an ENV variable in your Dockerfile: ENV MY_VAR=${MY_ARG}.

#Wrapping up

Environment variables control container behavior without baking configuration into images. In this guide, you set variables with ENV and ARG in Dockerfiles, pass them at runtime using docker run -e and --env-file, and manage them across multi-container applications with Docker Compose.

You also learned the precedence rules that determine which value wins when the same variable appears in multiple sources, how to use ${VAR:-default} for fallback values, and why Docker secrets are safer than plain environment variables for sensitive data.

To run your containerized workloads on dedicated hardware, explore Cherry Servers' bare metal and virtual server options.

FAQs

What is the difference between ENV and ARG in a Dockerfile?

`ENV` sets environment variables that persist in the built image and every container created from it. `ARG` defines build-time variables that are only available during the `docker build` process. To pass an `ARG` value into the running container, assign it to an `ENV` in the Dockerfile.

Can I override Dockerfile ENV variables at runtime?

Yes. Pass a new value using `docker run -e VAR=newvalue` or through the `environment/env_file` attributes in Docker Compose. Runtime values override the defaults set in the Dockerfile's `ENV` instruction.

How do I pass environment variables securely in Docker?

For production workloads, use Docker secrets rather than environment variables. Secrets mount sensitive values as files inside containers and stay out of image layers, `docker inspect` output, and process listings. For non-Swarm setups, load variables from encrypted `.env` files that are excluded from version control via `.gitignore`.

Why is my environment variable empty inside the container?

The most common cause is defining the variable only in the `.env` file without referencing it in the compose.yaml `environment` or `env_file` attribute. The `.env` file alone only feeds Compose interpolation. It does not inject variables into containers automatically. Add the variable to the service's `environment` section or use `env_file` to load the file.

What happens when the same variable is set in multiple places?

Docker follows a strict precedence order. CLI flags (`-e`) take the highest priority, followed by the `environment` attribute in compose.yaml, shell variables, `env_file`, and finally the Dockerfile `ENV`. The highest-priority source wins.

Does Docker Compose still support the docker-compose (hyphenated) command?

Docker Compose V1 (the hyphenated `docker-compose` command) reached end of life in July 2023. Docker Compose V2 ships as a Docker CLI plugin and uses the `docker compose` (with a space) syntax. All examples in this guide use the V2 syntax. If you are still running V1, migrate to Compose V2.

Cloud VPS Hosting

Starting at just $3.24 / month, get virtual servers with top-tier performance.

Share this article

Related Articles

Published on Mar 25, 2026 Updated on Mar 26, 2026

Docker Copy Command: Copy Files and Directories in Docker

Learn how to use the Docker COPY command with practical examples. Copy files, directories, and apply best practices for secure, efficient Docker builds.

Read More
Published on Sep 12, 2025 Updated on Nov 14, 2025

Docker Compose Cheat Sheet: Key Commands Guide

Learn Docker Compose commands to easily deploy and manage multi-container apps, scale services, and set up full-stack environments using a single YAML file.

Read More
Published on Aug 19, 2025 Updated on Nov 7, 2025

Docker Pull Command: How to Pull Docker Images

Learn how to search, pull, list, inspect, and remove Docker images step by step. Master Docker image management for smooth app deployment.

Read More
No results found for ""
Recent Searches
Navigate
Go
ESC
Exit
We use cookies to ensure seamless user experience for our website. Required cookies - technical, functional and analytical - are set automatically. Please accept the use of targeted cookies to ensure the best marketing experience for your user journey. You may revoke your consent at any time through our Cookie Policy.
build: 7de6e1976.1753