Chapter 2 · Lesson 10 of 20
Docker

Docker Compose environment variables: environment, env_file, .env

Compose passes settings to a container through the environment key or an env_file, and fills ${VAR} placeholders in compose.yaml from the shell or a project .env file.

By the end you will

Pass settings to containers with environment, env_file and a project dotenv file, and check the result.

Time
22 min
Level
Beginner
Check
4 questions
You need
  • Docker with the compose plugin installed

In Docker Compose, set an environment variable for a container with the environment: key or an env_file:, and fill ${VAR} placeholders inside compose.yaml from your shell or a .env file. These are two separate jobs, and docker compose config shows you the final result.

How it works#

There are two separate jobs, and mixing them up causes most bugs.

Job 1: Setting variables inside a container. The environment: key and the env_file: key put variables into the container’s process, where the app reads them (for example process.env.LOG_LEVEL). If both set the same name, environment wins. A value set in the image with ENV is the weakest.

Job 2: Filling placeholders in the compose file. When Compose reads compose.yaml, it replaces ${VAR} with a value from your shell or from a file called .env in the project folder. This happens before any container exists, and it does not by itself pass anything to a container.

Both read at the moment the container is created. Changing a value later changes nothing in a running container until it is recreated.

MechanismWho reads itReaches the container?
environment:Compose, at create timeYes
env_file:Compose, at create timeYes
.env in the project folderCompose, to fill ${VAR}Only if you reference it
Shell variableCompose, to fill ${VAR} (beats .env)Only if you reference it

A worked example, start to finish#

Say .env contains APP_TAG=1.0 and DB_PASSWORD=change-me, and the file from step 3 is in use.

  1. You run docker compose up -d. Compose reads .env and replaces ${APP_TAG} and ${DB_PASSWORD}, so the image becomes myapp:1.0.
  2. Compose creates the container with LOG_LEVEL=info (the default) and DB_PASSWORD=change-me in its environment.
  3. You edit .env to APP_TAG=1.1 and run docker compose up -d again. Compose sees the image reference changed and recreates the container.
  4. You run LOG_LEVEL=debug docker compose up -d. The shell value wins over the default, the configuration changed, and the container is recreated with debug.

At each point docker compose config shows exactly what Compose will use.

Step 1: Set variables directly#

yaml
services:
  app:
    image: myapp:1.0
    environment:
      LOG_LEVEL: info
      DATABASE_HOST: db

These go straight into the container.

Step 2: Load variables from a file#

yaml
services:
  app:
    image: myapp:1.0
    env_file:
      - app.env

app.env holds one NAME=value per line. Use it when a service has many settings.

Step 3: Fill placeholders from the project .env file#

Create a file named .env next to compose.yaml:

bash
APP_TAG=1.0
DB_PASSWORD=change-me

Then reference the values with ${VAR}:

yaml
services:
  app:
    image: myapp:${APP_TAG}
    environment:
      DB_PASSWORD: ${DB_PASSWORD}
      LOG_LEVEL: ${LOG_LEVEL:-info}

${LOG_LEVEL:-info} uses info when LOG_LEVEL is unset or empty. ${DB_PASSWORD:?missing} stops with an error instead, which is safer for required values. Compose reads .env on its own, so it is not passed to the container unless you list it in environment or env_file.

Step 4: Keep .env out of git#

bash
echo ".env" >> .gitignore

Commit a .env.example with fake values so others know which names to set. Also ignore app.env if it holds secrets.

Step 5: Check the result#

bash
docker compose config

This prints the final file with every ${VAR} replaced. It also prints secrets in plain text, so do not paste its output into a chat or ticket.

What you should see: image: myapp:1.0 and your values in place. A missing variable shows as an empty string and a warning that the variable is not set, which means the name in .env does not match.

To see what a running container received (see Run commands inside a container):

bash
docker compose exec app env

What you should see: a list of NAME=value lines including LOG_LEVEL and DATABASE_HOST.

Check it worked#

docker compose config shows no warnings about unset variables, and docker compose exec app env lists the values you expect. Change a value in .env, run docker compose up -d, and Compose recreates the container and the new value appears.

Edge cases and gotchas#

  • .env must be in the right folder. Compose looks in the project directory, normally where you run the command. From another folder, pass --env-file path/to/.env.
  • A shell variable beats .env. If DB_PASSWORD is exported in your shell, that value wins and .env is ignored for it. Run docker compose config to see which one was used.
  • A literal dollar sign needs $$. In compose.yaml, $ starts a placeholder. Write $$ for a real one. In a .env value, single quotes make the content literal.
  • Quote values with # or spaces. An unquoted # can start a comment, so PASS=ab #cd loses the end. Use single quotes around the value.
  • Names are case sensitive. db_password and DB_PASSWORD are different. The container sees exactly the name you set.
  • Secrets are readable on the host. docker inspect and docker compose config show them. Restrict who can run Docker on the machine, and keep .env readable only by you with chmod 600 .env.
  • A running container does not update. Edit the value, then run docker compose up -d. A plain restart does not re-read the file.

Troubleshooting#

SymptomLikely causeFix
The "DB_PASSWORD" variable is not set. Defaulting to a blank string.The name is missing from .env or misspelledAdd it, and check the case
App sees the old valueThe container was not recreateddocker compose up -d
Value is cut at #An unquoted comment characterWrap the value in single quotes
Value with $ looks wrongCompose treated $ as a placeholderUse $$ in compose.yaml
env file ... not foundenv_file path is wrong or the file does not existCreate it, or fix the path relative to compose.yaml
.env ignored when run from another folderCompose reads the project directoryUse --env-file
Wrong value usedA shell variable overrides .envunset VAR, or check with docker compose config
Variable set in .env but not visible in the appIt fills placeholders only, and was not listed under environmentReference it in environment: or env_file:
variable is not set warning for a name you definedThe name has a typo, or .env is in another folderCompare names and run from the project folder

Real-world scenario#

A team keeps one compose.yaml and deploys it to a staging and a production server. The file has no passwords: it references ${DB_PASSWORD} and ${APP_TAG}. Each server has its own .env, readable only by the deploy user.

When production needs a new image, the deploy script edits APP_TAG and runs docker compose up -d. A teammate once pasted the output of docker compose config into a chat to debug an issue, and it contained the production password. They rotated it the same hour. Since then the team shares .env.example instead, and the longer guide Environment variables and secrets is the first link in their runbook. The blog guide Manage secrets in self-hosted Docker covers other storage options.

Quick reference#

GoalHow
Set a value directlyenvironment: with NAME: value
Load many valuesenv_file: [app.env]
Fill a placeholder${VAR} in compose.yaml, value from shell or .env
Default / required${VAR:-default} / ${VAR:?message}
Literal dollar sign$$
Other folder or filedocker compose --env-file path/to/.env up -d
Show the final file (contains secrets)docker compose config
See a container’s environmentdocker compose exec app env

Security and safety notes#

  • Never commit .env or any file with real passwords (see Environment variables and secrets). If one was committed, rotate those secrets: deleting the file does not remove it from git history.
  • Do not print docker compose config into shared logs or CI output.

Next#

Make containers come back after a crash or reboot with Docker restart policies.

Check what you learned4 questions
1What is the project dotenv file used for in Compose?
2You edited a value and the running container still has the old one. What is the fix?
3How do you see the final compose file with every ${VAR} filled in?
4A password contains a literal dollar sign and Compose shows it mangled in the file. How do you write one literal dollar?

Frequently asked questions

What is the difference between env_file and the .env file?

env_file hands variables to the container at runtime. The project .env file is read by Compose itself to fill ${VAR} placeholders inside compose.yaml. They are separate mechanisms.

Should I commit .env to git?

No. It usually holds passwords and keys. Commit a .env.example with placeholder values and add .env to .gitignore.

Which value wins if the same variable is set in several places?

For container values, an environment entry beats env_file. For ${VAR} placeholders, a variable exported in your shell beats the project .env file. Run docker compose config to see the final result.

Are environment variables a safe place for secrets?

They keep secrets out of the image and git, but anyone who can run docker inspect or docker compose config on the host can read them. Protect the host, and rotate any value that leaks.

Sources

View MD Edit
Share
Helpful?
Progress is saved in this browser only.

Keep going: guides and tutorials

View MD Edit
Share
Helpful?
Run this on your own server

Levelrail deploys apps from git with health-checked releases and one-click rollback.

docker pull ghcr.io/glincker/levelrail:latest Install Levelrail From GLINR Studios