What Are Environment Variables in Docker?
Environment variables are key-value pairs that affect the processes of a running container. Unlike arguments that are baked into the image when it’s built, environment variables can be set at runtime. This is incredibly useful when you need to change the behavior of your containers across different environments without altering the Docker image itself.
Using Environment Variables in Docker Compose
In Docker Compose, you can define environment variables directly in your docker-compose.yml
file or in separate .env
files. Here’s a breakdown of how to use them:
1. Defining Environment Variables Inline
Within your docker-compose.yml
file, you can set environment variables using the environment
key:
version: '3'
services:
myservice:
image: myimage
environment:
- PGUSER=myuser
- PGPASSWORD=mypassword
- PGHOST=db
- PGDATABASE=mydatabase
- PGPORT=5432
In this example, the service myservice
will have access to the defined environment variables when it runs.
2. Using an .env
File
For more complex applications, or to avoid hardcoding sensitive information in your YAML file, you can use an .env
file. This is a simple text file containing environment variables:
PGUSER=myuser
PGPASSWORD=mypassword
To use the .env
file, just place it in the same directory as your docker-compose.yml
and Docker Compose will automatically read the variables from it.
3. Variable Substitution in Docker Compose
You can also use environment variables from your shell in the docker-compose.yml
file:
version: '3'
services:
myservice:
image: myimage
environment:
- PGUSER=${DB_USER}
- PGPASSWORD=${DB_PASS}
In this case, DB_USER
and DB_PASS
are set in your shell environment and will be substituted into the Docker Compose configuration at runtime.
Best Practices for Environment Variables
- Security: Never hardcode sensitive information like passwords in your
docker-compose.yml
file. Use an.env
file or your shell environment and ensure.env
files are added to.gitignore
. - Flexibility: Use environment variables for values that change between environments, such as development, testing, and production.
- Documentation: Document the required environment variables and their purpose, especially if the project is shared among multiple developers or teams.
,