YAML Anchors in Docker Compose

MohammadHasan Akbari
2 min readFeb 28, 2025

Sometimes, you want to have a Docker Compose file with many services, and you can say that most of the services have configurations that are relatively similar to each other.

Well, under normal circumstances, you might want to have a Docker Compose file for your services like this:

services:
service-one:
image: service-one:latest
networks:
- custom-network
environment:
- one=1
logging:
driver: json-file
deploy:
replicas: 2
restart: always
dns:
- 8.8.8.8

service-two:
image: service-two:latest
networks:
- custom-network
environment:
- one=1
logging:
driver: json-file
deploy:
replicas: 2
restart: always
dns:
- 8.8.8.8

networks:
custom-network:
driver: bridge

I should mention that there’s an easier way to handle this :)

That is, using YAML Anchors in Docker Compose. YAML Anchors allow you to reuse a section of data in multiple places in the YAML file. By using the “&” and “*” symbols, you can define data once and avoid repetition.

For example, we could have a Docker Compose file like this:

x-service-common: &service-common
networks:
- custom-network
environment:
- one=1
logging:
driver: json-file
deploy:
replicas: 2
restart: always
dns:
- 8.8.8.8

services:
service-one:
image: service-one:latest
<<: *service-common

service-two:
image: service-two:latest
<<: *service-common

networks:
custom-network:
driver: bridge

In YAML:

  • “&” is used to define an anchor (reference).
  • “*” is used to refer to that anchor and use its data.

Thank you for your time:)

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response