# 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.

URL: https://levelrail.com/learn/docker/docker-compose-environment-variables/
Updated: 2026-11-27

In Docker Compose, set an [environment variable](https://levelrail.com/learn/glossary/#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.

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](https://levelrail.com/learn/docker/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

| 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](https://levelrail.com/learn/deploy-operate/environment-variables-and-secrets/)) is the first link in their runbook. The blog guide [Manage secrets in self-hosted Docker](https://levelrail.com/blog/manage-secrets-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 `.env` or any file with real passwords (see [Environment variables and secrets](https://levelrail.com/learn/deploy-operate/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.

## Related lessons

- [Docker Compose basics](https://levelrail.com/learn/docker/docker-compose-basics/)): the file these variables live in
- [Environment variables and secrets](https://levelrail.com/learn/deploy-operate/environment-variables-and-secrets/)): where secrets belong
- [Run commands inside a container](https://levelrail.com/learn/docker/run-commands-inside-a-container/)): inspect a running container
- [Docker restart policies](https://levelrail.com/learn/docker/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](https://levelrail.com/learn/docker/docker-restart-policies/)).

## 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

- [Docker docs, environment variables in Compose](https://docs.docker.com/compose/how-tos/environment-variables/)
