To use variables in a docker-compose.yml or compose.yml file you can do this:
- Reference the variable in the file
docker-compose.yml:
# docker-compose.yml
version: '3.8'
name: "my_project"
services:
db:
image: postgres:$docker_image_version # <- this is the variable
restart: always
environment:
POSTGRES_PASSWORD: example
- Define a
.env file in the same directory as docker-compose.yml:
# .env
docker_image_version="16-alpine3.19"
- Check that the variables are correctly replaced:
docker compose config
You should see that the variable will be replaced:
name: my_project
services:
db:
environment:
POSTGRES_PASSWORD: example
image: postgres:16-alpine3.19
networks:
default: null
restart: always
networks:
default:
name: my_project_default
- Start the containers;
docker compose up -d
- Check the running containers:
docker compose ps
You should see something like:
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
my_project-db-1 postgres:16-alpine3.19 "docker-entrypoint.sh postgres" db 5 seconds ago Up 5 seconds 5432/tcp
In the output you can see that it is running the version set in the .env file: 16-alpine3.19
Source: Docker compose documentation