YAML Anchors in Docker Compose

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:)