4.8 KiB
| title | description | keywords |
|---|---|---|
| Environment variables precedence | Scenario Overview illustrating how environment variables are resolved in Compose | compose, environment, env file |
This page contains information on how interpolation works when using environment variables in Compose.
When you set the same environment variable in multiple files, there’s a precedence rule used by Compose. It aims to resolve the value for the variable in question.
The order of precedence is as follows:
- Passed from the command line
docker compose run --env <KEY[=[VAL]]>. - Passed from/set in
compose.yamlservice's configuration, from the environment key. - Passed from/set in
compose.yamlservice's configuration, from the env_file key. - Passed from/set in Container Image in the ENV directive.
Example scenario
The following table uses TAG, an environment variable defining the version for an image, as an example.
The columns
Each column represents a context from where you can set or pass TAG, or environment variables in general.
Table column's description:
run --envsets the environment variable using the command line instructiondocker compose run -e <KEY[=[VAL]]>.compose.yaml:environmentkey. Inenvironmentkey from the service section in thecompose.yamlfile.compose.yaml:env_filekey. Inenv_filekey from the service section in thecompose.yamlfile.- Image
ENV-ENVdirective in the Dockerfile for the image. Host OSenvironment. The environment where the Docker Engine is running..envfile. The.envfile in the project root.- Resolved as. Gives the final result of how
TAGis resolved for each scenario according to the precedence rule.
The rows
Each row represents a combination of contexts where TAG is set or passed simultaneously.
| # | run --env |
compose.yaml:environment key |
compose.yaml:env_file key |
Image ENV |
Host OS environment |
.env file |
Resolved as |
|---|---|---|---|---|---|---|---|
| 1 | - | - | - | - | TAG=1.4 |
TAG=1.3 |
- |
| 2 | - | - | - | TAG=1.5 |
TAG=1.4 |
TAG=1.3 |
TAG=1.5 |
| 3 | TAG |
- | - | TAG=1.5 |
TAG=1.4 |
TAG=1.3 |
TAG=1.4 |
| 4 | - | - | TAG |
TAG=1.5 |
- | TAG=1.3 |
TAG=1.3 |
| 5 | TAG |
- | - | TAG=1.5 |
- | TAG=1.3 |
TAG=1.3 |
| 6 | TAG=1.8 |
- | - | TAG=1.5 |
TAG=1.4 |
TAG=1.3 |
TAG=1.8 |
| 7 | - | TAG |
- | TAG=1.5 |
TAG=1.4 |
TAG=1.3 |
TAG=1.4 |
| 8 | TAG |
TAG=1.7 |
- | TAG=1.5 |
TAG=1.4 |
TAG=1.3 |
TAG=1.4 |
| 9 | TAG=1.8 |
TAG=1.7 |
- | TAG=1.5 |
TAG=1.4 |
TAG=1.3 |
TAG=1.8 |
| 10 | - | TAG |
- | TAG=1.5 |
TAG=1.4 |
TAG=1.3 |
TAG=1.4 |
| 11 | TAG=1.8 |
- | TAG=1.6 |
TAG=1.5 |
TAG=1.4 |
TAG=1.3 |
TAG=1.8 |
| 12 | TAG=1.8 |
TAG=1.7 |
TAG=1.6 |
TAG=1.5 |
TAG=1.4 |
TAG=1.3 |
TAG=1.8 |
| 13 | - | - | TAG=1.6 |
TAG=1.5 |
TAG=1.4 |
- | TAG=1.6 |
| 14 | - | TAG=1.7 |
- | TAG=1.5 |
TAG=1.4 |
- | TAG=1.7 |
Note
The columns
Host OSenvironment and.envfile is listed only for lookup. These columns can't result in a variable in the container by itself.