Skip to main content
Environment variables (for example, DATABASE_URL) can be provided to your containers in three ways. Pick the approach that best fits your deployment workflow.

Option 1: Directly in docker-compose.yml

Set variables inline in the environment block of each service:
docker-compose.yml
Avoid hardcoding secrets directly in docker-compose.yml if you commit the file to version control. Use Option 2 or 3 instead.

Option 2: Using a .env file

Reference a separate .env file with env_file. Docker reads the file and injects every variable into the container.
docker-compose.yml
Add .env to .gitignore to keep secrets out of version control.

Option 3: Combine both

Use env_file for shared variables and environment to override specific values per service. Variables defined in environment take precedence over values in the .env file.
docker-compose.yml
  • All environment variables must be defined before starting the containers. Services validate their required variables on startup and will exit immediately if any are missing.
  • When environment and env_file are both set, the environment block overrides values from the .env file.
  • DATABASE_URL, REDIS_URL, and storage credentials are shared across all three services — define them once in .env rather than repeating them per service.

Variable substitution

Docker Compose also supports substituting variables from the host shell or a .env file placed next to docker-compose.yml:
docker-compose.yml
This is useful when deploying from a CI/CD pipeline that injects secrets as environment variables rather than files.
See the full list of supported variables in the configuration reference.