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.
- Updated Nov 27, 2026
- Markdown
Pass settings to containers with environment, env_file and a project dotenv file, and check the result.
- 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.
| Mechanism | Who reads it | Reaches the container? |
|---|---|---|
environment: | Compose, at create time | Yes |
env_file: | Compose, at create time | Yes |
.env in the project folder | Compose, to fill ${VAR} | Only if you reference it |
| Shell variable | Compose, 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.
- You run
docker compose up -d. Compose reads.envand replaces${APP_TAG}and${DB_PASSWORD}, so the image becomesmyapp:1.0. - Compose creates the container with
LOG_LEVEL=info(the default) andDB_PASSWORD=change-mein its environment. - You edit
.envtoAPP_TAG=1.1and rundocker compose up -dagain. Compose sees the image reference changed and recreates the container. - You run
LOG_LEVEL=debug docker compose up -d. The shell value wins over the default, the configuration changed, and the container is recreated withdebug.
At each point docker compose config shows exactly what Compose will use.
Step 1: Set variables directly#
services:
app:
image: myapp:1.0
environment:
LOG_LEVEL: info
DATABASE_HOST: dbThese go straight into the container.
Step 2: Load variables from a file#
services:
app:
image: myapp:1.0
env_file:
- app.envapp.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:
APP_TAG=1.0
DB_PASSWORD=change-meThen reference the values with ${VAR}:
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#
echo ".env" >> .gitignoreCommit 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#
docker compose configThis 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):
docker compose exec app envWhat 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#
.envmust 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. IfDB_PASSWORDis exported in your shell, that value wins and.envis ignored for it. Rundocker compose configto see which one was used. - A literal dollar sign needs
$$. Incompose.yaml,$starts a placeholder. Write$$for a real one. In a.envvalue, single quotes make the content literal. - Quote values with
#or spaces. An unquoted#can start a comment, soPASS=ab #cdloses the end. Use single quotes around the value. - Names are case sensitive.
db_passwordandDB_PASSWORDare different. The container sees exactly the name you set. - Secrets are readable on the host.
docker inspectanddocker compose configshow them. Restrict who can run Docker on the machine, and keep.envreadable only by you withchmod 600 .env. - A running container does not update. Edit the value, then run
docker compose up -d. A plainrestartdoes not re-read the file.
Troubleshooting#
| Symptom | Likely cause | Fix |
|---|---|---|
The "DB_PASSWORD" variable is not set. Defaulting to a blank string. | The name is missing from .env or misspelled | Add it, and check the case |
| App sees the old value | The container was not recreated | docker compose up -d |
Value is cut at # | An unquoted comment character | Wrap the value in single quotes |
Value with $ looks wrong | Compose treated $ as a placeholder | Use $$ in compose.yaml |
env file ... not found | env_file path is wrong or the file does not exist | Create it, or fix the path relative to compose.yaml |
.env ignored when run from another folder | Compose reads the project directory | Use --env-file |
| Wrong value used | A shell variable overrides .env | unset VAR, or check with docker compose config |
Variable set in .env but not visible in the app | It fills placeholders only, and was not listed under environment | Reference it in environment: or env_file: |
variable is not set warning for a name you defined | The name has a typo, or .env is in another folder | Compare 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#
| Goal | How |
|---|---|
| Set a value directly | environment: with NAME: value |
| Load many values | env_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 file | docker compose --env-file path/to/.env up -d |
| Show the final file (contains secrets) | docker compose config |
| See a container’s environment | docker compose exec app env |
Security and safety notes#
- Never commit
.envor 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 configinto shared logs or CI output.
Related lessons#
- Docker Compose basics: the file these variables live in
- Environment variables and secrets: where secrets belong
- Run commands inside a container: inspect a running container
- Docker restart policies: the next setting to add to a service
Next#
Make containers come back after a crash or reboot with Docker restart policies.
Check what you learned
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
Keep going: guides and tutorials
- Deploy a Docker Compose App Self-Hosted: Web, Redis and Rollback Deploy a Docker Compose app on your own server with Levelrail: a web service and Redis, a bad release that does not take traffic, and a compose rollback.
- Docker Container Restarting in a Loop: 5 Causes, Fixed Five real reasons a Docker container keeps restarting, each reproduced with its exit code, the command that finds it and the fix. Then the same crash on Levelrail.
- Deploy an Express App to a VPS With Docker and Health Checks Deploy a Node.js Express API to your own server with no Dockerfile. Covers the port rule, a health route, secrets, deploy failure codes and rollback.