Use env variables in Docker Compose file
Use env variables in Docker Compose file
Some people might think you can only use or set environment variable of the service in docker compose eg.:
my-service:
image: lts-alpine
environment:
MY_SECRET_KEY: ${MY_SECRET_KEY}
But the same ${}
syntax can be used to set a version of Docker image of PostgreSQL, like in this example below:
my-service:
image: postgres:${POSTGRES_VERSION:-13}-alpine
If nothing is set, version 13 is the fallback value. Now you can set POSTGRES_VERSION
environment via your shell. Or leverage the .env
file of Docker:
POSTGRES_VERSION=16
When running: docker compose --env-file .env up
, Docker should now use PostgreSQL v16 Alpine as Docker image.
Bonus: The docker-compose.yml
filename is an old filename, use compose.yml
from now. Same for other Compose files like compose.override.yml
.
More info: https://docs.docker.com/compose/environment-variables/set-environment-variables/ and https://docs.docker.com/compose/environment-variables/set-environment-variables/