The env_file property loads environment variables from a named file into a Docker Compose service. It keeps usernames, passwords, ports, and similar configuration out of service definitions and source control, reducing security and maintenance problems. section 3.7
Configure the property by following these practical steps:
- Create a meaningfully named file such as .sql_server.conf, .env, or webapp.env; the filename itself is flexible. section 3.7
- Store variables such as POSTGRES_USER and POSTGRES_PASSWORD in the file. section 3.7
- Reference the file under a service's env_file property and prevent sensitive files from entering source control with Gitignore. section 3.7
- Document required variables and setup locations so new instances and team members can configure the system reliably. section 3.7
postgres:
build:
context: ./db
dockerfile: Dockerfile
env_file:
- ./.sql_server.conf
A compact Compose example shows a postgres service loading variables from ./.sql_server.conf. section 3.7
Application configuration
After Compose supplies the variables, application code can retrieve POSTGRES_USER and POSTGRES_PASSWORD with os.getenv and use them to build a database connection string. section 3.7

