Chapter 10 · Lesson 5 of 10
Server security

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.

By the end you will

Store secrets in permission-restricted files, pass them to containers through env_file or Compose secrets and rotate them after a leak.

Time
20 min
Level
Intermediate
Check
4 questions
You need
  • A server with Docker and Docker Compose
  • A Compose project that uses a password or API key

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. A longer walkthrough is in the blog post manage secrets for 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 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.

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:

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

SymptomLikely causeFix
permission denied reading /run/secrets/xFile mode on the host too strict for the container userMake the container user able to read, or adjust ownership
App cannot connect after changing the passwordDatabase still has the old passwordUpdate the database user too, secrets in data volumes persist
.env shows up in git statusFile was tracked before ignoringgit rm --cached .env, then commit, then rotate secrets
Variable is empty in the containerWrong file path or variable nameCheck docker compose config
variable is not set. Defaulting to a blank string${VAR} has no value in the environmentSet it in .env or export it
Secret visible in docker inspectPassed as an environment variableMove to a file secret and _FILE
secrets file not foundPath in file: is wrongUse 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/

Next#

Continue with Run containers as non-root.

Check what you learned4 questions
1Which permissions suit a file that holds secrets on a single-user server?
2A password is passed with environment: in Compose. Where can it be read?
3Where does Docker mount a Compose secret named db_password inside the container?
4What is the first step when an API key was committed to a public repository?

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

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