# Manage secrets on servers and containers (env files, Compose secrets)

> Managing secrets means storing passwords and keys in protected files outside git, passing them to containers in the least exposed way, and rotating them after any leak.

URL: https://levelrail.com/learn/security/manage-secrets-on-servers-and-containers/
Updated: 2026-11-27

A secret is any value that grants access: a database password, an API key, a signing key, a deploy token. On a server and in containers, the goal is simple. Keep secrets out of git, readable only by the account that needs them, and passed to the app in the way that exposes them least. When one leaks, replace it, since hiding it afterward does not make it safe again. This lesson extends [environment variables and secrets](https://levelrail.com/learn/deploy-operate/environment-variables-and-secrets/)). A longer walkthrough is in the blog post [manage secrets for self-hosted Docker](https://levelrail.com/blog/manage-secrets-self-hosted-docker/)).

## How it works

There are three common places a secret can live, with rising protection:

1. **Environment variables from an env file.** Easy, and good enough for many small servers. The value sits in the container's configuration, so `docker inspect` shows it to anyone who can use Docker, and any process in the container can read it from its environment.
2. **Compose secrets (file mounts).** Docker mounts a file at `/run/secrets/<name>` inside the container, read-only. The app reads the file. The value does not appear in the environment or in `docker inspect`.
3. **A dedicated secrets manager.** A separate service that hands out secrets on demand and logs access. Worth it when many people and systems need them, and beyond this lesson.

Anyone who can talk to the Docker socket can effectively read all of these, so access to Docker is itself a privileged power. See [run containers as non-root](https://levelrail.com/learn/security/run-containers-as-non-root/)) for the related risks.

## Step 1: Keep the file out of git

Before you create any secret file, make sure git will not pick it up. Add it to `.gitignore` first, then create it:

```bash
echo ".env" >> .gitignore
echo "secrets/" >> .gitignore
git check-ignore -v .env
```

Commit a template instead, such as `.env.example`, with the variable names and fake values like `change-me`. The rules for this are in [gitignore and keeping secrets out of git](https://levelrail.com/learn/git/gitignore-and-keeping-secrets-out-of-git/)).

## Step 2: Lock down the file

```bash
install -m 600 /dev/null .env
nano .env
ls -l .env
```

`install -m 600` creates an empty file that only its owner can read or write, so the contents are never briefly world readable. Write values like this, replacing every `change-me`:

```text
POSTGRES_PASSWORD=change-me-long-random-value
API_KEY=change-me
```

If the app runs under a specific account, set the owner with `sudo chown deploy:deploy .env`. A secret file readable by `others` is the most common mistake: `ls -l` should show `-rw-------`. See [Linux file permissions](https://levelrail.com/learn/server-basics/linux-file-permissions-explained/)) for the notation. Generate random values with `openssl rand -base64 32` instead of inventing them.

## Step 3: Pass the env file to Compose

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

`env_file` loads the variables into the container without writing them in the YAML. This differs from `${VAR}` substitution inside `compose.yaml`, which Compose fills from the shell or the project `.env`. Both are covered in [Docker Compose environment variables](https://levelrail.com/learn/docker/docker-compose-environment-variables/)). Remember that this route puts the value in the container environment.

## Step 4: Use Compose secrets for sensitive values

Store each secret in its own file and declare it:

```yaml
services:
  db:
    image: postgres:16
    environment:
      POSTGRES_PASSWORD_FILE: /run/secrets/db_password
    secrets:
      - db_password

secrets:
  db_password:
    file: ./secrets/db_password.txt
```

```bash
install -d -m 700 secrets
install -m 600 /dev/null secrets/db_password.txt
```

Inside the container, the password is the content of `/run/secrets/db_password`. The `_FILE` suffix is a convention supported by many official images: instead of `POSTGRES_PASSWORD`, they accept a variable that points at a file. Check the image's documentation to see which variables support it. If the image does not, your own entrypoint can read the file and export the variable for that one process.

## Step 5: Rotate after a leak

Assume a secret is exposed if it was committed, pasted in a chat or ticket, printed in a log, or readable by someone who should not have it. Then:

1. Create a new value at the provider or database first.
2. Update the env or secret file on the server.
3. Recreate the container (`docker compose up -d`) so it reads the new value.
4. Revoke the old value.
5. Only then clean up git history, if you want to.

Also check places a secret hides: shell history, CI logs and `docker inspect`. Use `history | grep -i password` as a quick look, and avoid putting secrets on command lines (`mysql -pSECRET`) because they show in the process list. A leaked key in a public repository is found by bots quickly, so rotate immediately.

## Check it worked

```bash
ls -l .env secrets/
git status --short
docker inspect --format '{{.Config.Env}}' myapp-app-1
docker compose exec db ls -l /run/secrets/
```

The first shows modes `600`. `git status` must not list the files. The `inspect` output tells you whether a secret appears as an environment variable. The last command shows the mounted secret files from inside the container.

## Edge cases and gotchas

- **Build arguments.** Values passed with `ARG` or copied into an image stay in image layers and history. Never bake secrets into an image. Use runtime secrets.
- **Logs.** Apps that print their full config or environment on startup leak secrets into logs. Check logs after the first start.
- **Quotes in env files.** Compose treats quotes and `#` in `.env` values in its own way. A password with special characters can be cut. Prefer file secrets for those.
- **Backups.** Secret files are copied by backups. Protect the backup target as well. See [backups against ransomware](https://levelrail.com/learn/security/backups-against-ransomware/)).
- **Shared servers.** If other users have shell access, even a 600 file owned by another account is the only barrier. Keep admin access narrow.
- **Same secret everywhere.** Reusing one password across services means one leak breaks all of them. Generate one per service.

## Troubleshooting

| Symptom | Likely cause | Fix |
| --- | --- | --- |
| `permission denied` reading /run/secrets/x | File mode on the host too strict for the container user | Make the container user able to read, or adjust ownership |
| App cannot connect after changing the password | Database still has the old password | Update the database user too, secrets in data volumes persist |
| `.env` shows up in `git status` | File was tracked before ignoring | `git rm --cached .env`, then commit, then rotate secrets |
| Variable is empty in the container | Wrong file path or variable name | Check `docker compose config` |
| `variable is not set. Defaulting to a blank string` | `${VAR}` has no value in the environment | Set it in `.env` or export it |
| Secret visible in `docker inspect` | Passed as an environment variable | Move to a file secret and `_FILE` |
| `secrets file not found` | Path in `file:` is wrong | Use a path relative to the compose file |

## Quick reference

```bash
install -m 600 /dev/null .env
echo ".env" >> .gitignore
openssl rand -base64 32
docker compose config
docker inspect --format '{{.Config.Env}}' <container>
docker compose exec <service> ls -l /run/secrets/
```

## Related lessons

- [Environment variables and secrets](https://levelrail.com/learn/deploy-operate/environment-variables-and-secrets/)): the concepts behind this lesson.
- [Gitignore and keeping secrets out of git](https://levelrail.com/learn/git/gitignore-and-keeping-secrets-out-of-git/)): stop secrets reaching the repository.
- [Docker Compose environment variables](https://levelrail.com/learn/docker/docker-compose-environment-variables/)): env_file versus substitution.
- [Run containers as non-root](https://levelrail.com/learn/security/run-containers-as-non-root/)): limit what a compromised container can read.
- [Backups against ransomware](https://levelrail.com/learn/security/backups-against-ransomware/)): protect copies of your secret files.

## Next

Continue with [Run containers as non-root](https://levelrail.com/learn/security/run-containers-as-non-root/)).

## Frequently asked questions

### Is an .env file safe for secrets?

It is acceptable on a single server if the file is owned by the right user, set to chmod 600 and never committed to git. The values still show up in docker inspect when passed as environment variables.

### What are Docker Compose secrets?

Compose can mount a file into a container at /run/secrets/<name>. The app reads the file, so the value does not appear in the environment or in docker inspect output.

### What is the _FILE convention?

Many official images accept a variable like POSTGRES_PASSWORD_FILE that holds a path. The image reads the secret from that file instead of from the environment.

### What should I do if a secret leaked to git?

Treat it as public. Rotate the secret first, then remove it from the repository. Deleting the commit does not help if anyone has already cloned or read it.


## Sources

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