Chapter 4 · Lesson 4 of 18
Deploy and operate

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.

By the end you will

Keep passwords and API keys in an env file outside git and images, and rotate a leaked one.

Time
18 min
Level
Beginner
Check
4 questions
You need
  • Docker and Docker Compose installed

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

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#

SymptomLikely causeFix
Variable is empty in the appTypo in the name or no env_file entryRun docker compose config and docker compose exec web env
variable is not set. Defaulting to a blank stringCompose placeholder ${VAR} with no valueDefine it in .env or the shell
Old value still usedContainer not recreateddocker compose up -d, add --force-recreate if needed
Value is cut off after a $Interpolation in Compose valuesWrite $$ for a literal dollar sign
env file .env not foundFile missing or wrong pathCreate it or fix the path in env_file
Value has stray quotesQuote handling differs by toolRemove quotes, or test with docker compose exec web env
.env shows up in git statusIt was committed or not ignored yetAdd to .gitignore, run git rm --cached .env, then rotate secrets
App cannot connect to the databaseWrong host name inside the containerUse 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 for tools that go beyond env files, and 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.

Next#

Protect your data as well: Backups and the 3-2-1 rule.

Check what you learned4 questions
1Why is a secret in a Dockerfile ENV line unsafe?
2You committed an API key by mistake. What is the right fix?
3You edited the env file but the container still has the old value. Why?
4Which command can reveal a container's environment variables to anyone with Docker access?

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

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