# Environment variables and secrets in Docker (.env, env_file)

> An environment variable is a named value given to a program at start time, which lets you keep secrets like passwords outside your code and images.

URL: https://levelrail.com/learn/deploy-operate/environment-variables-and-secrets/
Updated: 2026-11-27

Put passwords and API keys in a `.env` file that is not committed to git, and pass it to containers when they start with `--env-file` or Compose's `env_file`. Never write them into source code or a Dockerfile.

## How it works

An [environment variable](https://levelrail.com/learn/glossary/#environment-variable)) is a name and a value attached to a process when it starts. A program reads it with something like `process.env.API_KEY`. Because the value lives outside the code, the same image can run in development and production with different settings.

Docker sets variables when the container is created. There are several sources: `ENV` in a Dockerfile (baked into the image), `-e` or `--env-file` on `docker run`, and `environment:` or `env_file:` in Compose. If the same name appears twice, the more specific source at run time wins over the image default.

A worked example. Your app needs a database URL. You create `.env` with `DATABASE_URL=...`, add `env_file: .env` to the service, and run `docker compose up -d`. Compose reads the file on the host, creates the container with those variables set, and starts the app. The app reads the value at startup. If you edit `.env` later, the running container does not change, because its environment was fixed at creation.

One more detail: Compose also reads a file named `.env` in the project directory to fill `${VAR}` placeholders inside `compose.yaml` itself. That is separate from `env_file`, which passes values into the container. A name can be used for either purpose, so keep track of which one you mean.

Environment variables are convenient, not hidden. They are visible with `docker inspect`, in `/proc` for the process, and in some error pages and crash reports. They suit most small deployments. For higher sensitivity, look at [Docker secrets or a secrets manager](https://levelrail.com/blog/manage-secrets-self-hosted-docker/)).

## Step 1: Create a .env file

Create a file named `.env` next to your app:

```bash
DATABASE_URL=postgres://app:change-me@db:5432/app
API_KEY=replace-with-a-real-key
```

One `NAME=value` per line, no spaces around `=`. Lines starting with `#` are comments. Quotes are treated differently by different tools, so avoid them unless the value contains spaces and you have tested it.

What you should see: `cat .env` lists your names. Restrict who can read it with `chmod 600 .env`.

## Step 2: Keep it out of git

Add the file to `.gitignore` before your first commit:

```bash
echo ".env" >> .gitignore
```

Commit a `.env.example` with fake values so others know which names are needed. What you should see: `git status` does not list `.env`. Use `git check-ignore -v .env` to confirm which rule ignores it.

## Step 3: Pass it to a container

With plain Docker:

```bash
docker run -d --env-file .env myapp:latest
```

With Compose, add `env_file` to the service:

```yaml
services:
  web:
    image: myapp:latest
    env_file:
      - .env
```

Then start it with `docker compose up -d`. What you should see: the container starts and the app connects using the values.

## Step 4: Do not bake secrets into images

Anything written in a Dockerfile (`ENV`, `COPY .env`, build arguments) can end up in the image layers, and `docker history` shows build arguments and commands. Images get pushed and shared, so build them without secrets and supply values at run time.

What you should see: `docker history myapp:latest` lists layers without your key. If it appears, rotate the key and rebuild.

## Check it worked

Run a throwaway check that only prints the variable name, not its value:

```bash
docker compose exec web sh -c 'test -n "$API_KEY" && echo "API_KEY is set"'
```

You should see `API_KEY is set`. Also run `git status` and confirm `.env` is not listed. The `.env` file's mode should read `-rw-------` in `ls -l .env`.

## Edge cases and gotchas

- **Spaces and quotes in values.** In an `env_file`, Compose may keep or strip quotes depending on the version. A trailing space becomes part of the value. Print the variable inside the container to confirm what the app really gets.
- **A dollar sign in a password.** In `compose.yaml` values, `$` starts interpolation, and you write `$$` for a literal one. A random password containing `$` can be cut short silently.
- **The wrong `.env` is loaded.** Compose reads `.env` from the project directory, not the current directory in some cases. Run `docker compose config` to see the resolved result.
- **Changes not picked up.** Containers keep their creation-time environment. Recreate with `docker compose up -d`, or `--force-recreate` if nothing seems to change.
- **Secrets in logs and crash pages.** Some frameworks print environment on debug pages. Turn debug mode off in production and avoid logging config objects.
- **Secrets in shell history.** `docker run -e API_KEY=abc` stores the value in your shell history and the process list. Prefer `--env-file`.
- **Build-time versus run-time.** `ARG` values are used while building and remain visible in image history. Use BuildKit secret mounts for build-time secrets.
- **Backups include secrets.** Copying the project folder to a backup copies `.env` too. Encrypt backups or exclude the file and store it separately.

## Troubleshooting

| Symptom | Likely cause | Fix |
| --- | --- | --- |
| Variable is empty in the app | Typo in the name or no `env_file` entry | Run `docker compose config` and `docker compose exec web env` |
| `variable is not set. Defaulting to a blank string` | Compose placeholder `${VAR}` with no value | Define it in `.env` or the shell |
| Old value still used | Container not recreated | `docker compose up -d`, add `--force-recreate` if needed |
| Value is cut off after a `$` | Interpolation in Compose values | Write `$$` for a literal dollar sign |
| `env file .env not found` | File missing or wrong path | Create it or fix the path in `env_file` |
| Value has stray quotes | Quote handling differs by tool | Remove quotes, or test with `docker compose exec web env` |
| `.env` shows up in `git status` | It was committed or not ignored yet | Add to `.gitignore`, run `git rm --cached .env`, then rotate secrets |
| App cannot connect to the database | Wrong host name inside the container | Use the Compose service name, not `localhost` |

## Rotating a leaked secret

1. Create a new secret in the service that issued it.
2. Put the new value in `.env` and recreate the containers.
3. Revoke the old secret.
4. Look through logs for use of the old one.

Removing a secret from git history does not make it safe again. Always rotate it.

## Real-world scenario

You deploy a small API on a VPS. The first version had `API_KEY` written in `config.js`, and the repo is public. A scanner emails you that a key is exposed.

You treat the key as leaked. In the provider's dashboard you create a new key and revoke the old one. You add `.env` to `.gitignore`, run `git rm --cached` on any env file that was committed, and move the key into `.env` on the server with `chmod 600`. You add `env_file: .env` to the service and run `docker compose up -d`. Then you run the exec check from above, and the container reports `API_KEY is set`.

Later you find the key also appears in `docker history` because an earlier Dockerfile used `ARG API_KEY`. You rebuild the image without it, push it and delete the old tag from the registry. Last, you read your provider's access logs for use of the old key between exposure and revocation. See the blog guide on [managing secrets in self-hosted Docker](https://levelrail.com/blog/manage-secrets-self-hosted-docker/)) for tools that go beyond env files, and [Docker Compose environment variables](https://levelrail.com/learn/docker/docker-compose-environment-variables/)) for the Compose details.

## Quick reference

```bash
chmod 600 .env                       # only you can read it
echo ".env" >> .gitignore            # never commit it
docker run -d --env-file .env IMAGE  # plain Docker
docker compose config                # see resolved values (contains secrets)
docker compose up -d                 # recreate to pick up changes
docker compose exec web env | cut -d= -f1   # list names, not values
git check-ignore -v .env             # confirm it is ignored
```

## Security and safety notes

- Rotate any secret that touched git, a log, a screenshot or a public image.
- `docker compose config` and `docker inspect` print secret values. Do not paste their output into issues or chat.
- Do not commit `.env`, and do not copy it into an image.
- Limit who is in the `docker` group. Access to Docker is access to every container's environment.

## Related lessons

- [Docker Compose environment variables](https://levelrail.com/learn/docker/docker-compose-environment-variables/)): how Compose reads and merges them.
- [Write your first Dockerfile](https://levelrail.com/learn/docker/write-your-first-dockerfile/)): what belongs in an image and what does not.
- [Linux file permissions explained](https://levelrail.com/learn/server-basics/linux-file-permissions-explained/)): why `chmod 600` matters here.
- [Deploy an app with Docker Compose](https://levelrail.com/learn/deploy-operate/deploy-an-app-with-docker-compose/)): where env_file fits in a real project.

## Next

Protect your data as well: [Backups and the 3-2-1 rule](https://levelrail.com/learn/deploy-operate/backups-and-the-3-2-1-rule/)).

## Frequently asked questions

### Is it safe to put a secret in a Dockerfile ENV line?

No. The value is stored in the image and anyone who can pull the image can read it. Pass secrets when the container starts instead.

### What do I do if I committed a secret by mistake?

Treat it as leaked. Create a new secret, switch your apps to it, revoke the old one, then clean the history if you can.

### Why does my container still have the old value after I edited .env?

Environment variables are fixed when a container is created. Recreate it with docker compose up -d so Compose reads the file again.

### Can other people on the server read my container's environment variables?

Anyone who can run docker inspect on the container, which usually means members of the docker group or root, can see them. Treat access to the Docker socket as access to your secrets.


## Sources

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