In Docker Compose, pass variables to a container with environment: or env_file:, and prefer the top-level secrets: element for sensitive values, which mounts them as files under /run/secrets/. Keep .env files out of Git and out of images, and never put secrets in ARG or ENV instructions of a Dockerfile.
Read the key from the environment
services:
app:
image: example/app:latest
environment:
STRIPE_SECRET_KEY_FILE: /run/secrets/stripe_secret_key
secrets:
- stripe_secret_key
secrets:
stripe_secret_key:
file: ./secrets/stripe_secret_key.txt # git-ignoredLocal development
Compose reads a .env file in the project directory to interpolate ${VAR} in the Compose file, and env_file: loads variables into a container. Both are plaintext and visible via docker inspect for environment variables. File-based secrets are mounted read-only in memory-backed storage at /run/secrets/<name>, so the app reads the file instead of an environment variable. Git-ignore the secrets directory and .env.
Production
For multi-host production use your orchestrator's secrets (Swarm secrets, Kubernetes Secrets, or a cloud secret manager) rather than files on a host. Use BuildKit secret mounts (RUN --mount=type=secret) for credentials needed during image builds, so they never land in image layers or build history.
Mistakes to avoid
- Writing
ENV API_KEY=...orARG API_KEYin a Dockerfile: the value is stored in image layers and history, retrievable by anyone with the image. - Committing
.envordocker-compose.ymlwith literal values, or copying.envinto an image withCOPY . .(add it to.dockerignore). - Passing secrets via
environment:and assuming they are hidden;docker inspectand/procreveal them to anyone with access to the container. - Publishing images to a public registry after a build that embedded credentials.
When an AI agent works on your Docker Compose project
Coding agents run inside your project folder, so they can read the same .env file your app reads. BotPassword injects keys at run time instead: the agent calls the run_with intent through the MCP server and the process gets the variables it needs while the agent sees only redacted output. Planned: bpw run, a CLI form of the same.
Frequently asked questions
How do I use secrets in Docker Compose?
Define a top-level secrets: entry backed by a file, reference it from the service, and read /run/secrets/<name> in your app. This avoids exposing values as environment variables.
Is an environment variable in Compose secure?
It is convenient but not strongly protected: values are visible through docker inspect and to processes in the container. Use file-based secrets for sensitive values.
Should I keep API keys in a .env file for Docker Compose?
A .env file that is git-ignored is fine for local development, but every process and every AI coding agent running in that folder can read it. Load secrets into the environment at run time from a password manager or secrets manager instead, so no plaintext file sits in the project.