Variables in Docker Compose
There are multiple parts of Compose that deal with environment variables in one sense or another. Quick notes below will help you understand this and enable you to understand microsoft solution for microservices (eShopContainer) -
- Environment variable is indicated in compose file as ${VARIABLE}
- You can substitute environment variable by adding them to .env or by providing a path using the --env-file option.
- The .env file is loaded by default, passing the --env-file argument overrides the default file path.
- Both {VARIABLE} syntax are supported.
- ${VARIABLE:-default} evaluates to default if VARIABLE is unset or empty in the environment.
- ${VARIABLE-default} evaluates to default only if VARIABLE is unset in the environment.
- ${VARIABLE:?err} exits with an error message containing err if VARIABLE is unset or empty in the environment.
- ${VARIABLE?err} exits with an error message containing err if VARIABLE is unset in the environment.
- The .env file is placed at the base of the project directory.
- You can verify this with the convert command, which prints your resolved application config to the terminal.
By passing the file as an argument, you can store it anywhere and name it appropriately, for example, .env.ci, .env.dev, .env.prod
docker compose --env-file ./config/.env.dev up
Example
Create a file .env in your project directory and paste the following:
USER_NAME='user'
PASSWORD='password#123'
Create a file docker-compose.yml in your project directory and paste the following:
version: '3.2'
services:
my_rabbit:
container_name: my_rabbit
image: rabbitmq:3-management
ports:
- "5672:5672"
- "8080:15672"
environment:
RABBITMQ_DEFAULT_USER: ${USER_NAME}
RABBITMQ_DEFAULT_PASS: ${PASSWORD}
Now to test the substitution, use the convert command as below -
docker compose convert
Output