When you use docker compose, you can dynamically set the values in the compose file through environment variables that are inserted into the configuration at run time. This approach is very flexible and suitable for scenarios where configuration needs to be dynamically adjusted for different environments such as development/test/production. In docker compose file, you can refer to environment variables in the ${VARIABLE_NAME} format, which can be obtained at runtime from the following sources: The environment variables file can be created in the project root directory to define variables.env file. Command line parameters You can obtain the environment variable specified by parameter e by running the following command:
docker-compose
System environment variables Environment variables can be set directly in the operating system. If you currently have a simple docker compose file docker-compose.yml:
version: '3.8'
services:
web:
image: "nginx:latest"
ports:
- "${WEB_PORT}:80"
environment:
- NGINX_HOST=${NGINX_HOST}
If you need to create a.ev file definition variable in the project root directory:
WEB_PORT=8080
NGINX_HOST=example.com
When you run Docker-Compose up, Docker Compose automatically loads the variables in the.env file and inserts them into the docker-compose.yml file. Therefore, the values of WEB_PORT and NGINX_HOST are replaced with 8080 and example.com.
Environment variables can also be dynamically adjusted with command parameters:
WEB_PORT=9090 NGINX_HOST=another-example.com docker-compose up
This way you can override variable values defined in the.env file.
You can also set environment variables directly in the operating environment. Running on Linux or macOS:
export WEB_PORT=8080
export NGINX_HOST=example.com
When a variable is not defined, docker compose will report an error. To avoid this, you can set a default value for the variable in docker-Compose.
ports:
- "${WEB_PORT:-8080}:80"
${WEB_PORT:-8080} indicates that if WEB_PORT is not defined, the default value 8080 is used.
The value of the environment variable must be a string, and if you need to pass complex values, you need to ensure that the format is correct, avoid storing important information in the.env file, such as password password sensitive information. Sensitive information can be accessed using docker's secrets feature or environment variable management tools. Use environment variables through the docker compose file for more flexibility to adapt to different deployment environments.