Docker Compose retrieves environment variables from a .env file located in the same directory as your docker-compose.yml file. This is the default and most common method.
How it works:
Placement:
Create a file named .env in the root directory of your Docker Compose project, alongside your docker-compose.yml file.
Content:
Define your environment variables within this .env file using a simple key-value pair format, one variable per line:
Code
VARIABLE_NAME=variable_value
ANOTHER_VAR=another_value
Referencing in docker-compose.yml: In your docker-compose.yml file, you can then reference these variables using the ${VARIABLE_NAME} syntax for interpolation:
Code
version: '3.8'
services:
web:
image: "my-app:${APP_VERSION}"
environment:
- DB_HOST=${DATABASE_HOST}
Automatic Loading: When you run docker compose up (or docker-compose up with older versions), Docker Compose automatically detects and loads the variables from the .env file, substituting them into your docker-compose.yml configuration before creating and starting the services.