Docker Compose supports features built in to the YAML spec like &anchors
and *aliases
and <<
merges, which can be particularly useful with compose fragments and extensions.
Use these features to avoid repeating yourself.
name: example
x-defaults: &defaults # extension which defines an anchor fragment
pull_policy: always
restart: unless-stopped
dns: 8.8.8.8
dns_search: example.com
env_file: .env
extra_hosts:
- "somehost=192.0.2.1"
- "docker.host.internal=172.17.0.1"
environment:
VARIABLE1: "${STR_ONE}"
VARIABLE2: "${STR_TWO}"
networks:
- my-network
services:
web:
image: nginx:latest
ports:
- "8081:80"
<<: *defaults # YAML merge using an alias to reference the default anchor
db:
image: postgres:13
<<: *defaults
environment: # this is merged with the environment defined in *defaults
POSTGRES_USER: example
POSTGRES_DB: exampledb
POSTGRES_PASSWORD: "${DB_PASSWORD}"
networks:
my-network: