In this lesson, you will learn how to eliminate repetitive boilerplate in your Docker Compose files by leveraging YAML anchors and file overrides to keep your configurations DRY (Don't Repeat Yourself).
Reducing Redundancy with YAML Anchors
When defining multiple services that share common settings—like logging drivers, network configurations, or shared environment variables—manually repeating those lines is prone to error. YAML provides anchors (&) and aliases (*) to handle this.
You define a "hidden" base configuration using an anchor, then "inject" it into other services. By convention, we use a top-level key like x-common-config (starting with x- keeps it ignored by Docker Compose as a real service):
x-shared-settings: &shared-settings
restart: always
networks:
- backend
services:
web:
<<: *shared-settings
image: nginx
api:
<<: *shared-settings
image: my-api
The <<: *shared-settings syntax merges all properties defined under the anchor into your service, instantly syncing shared configuration across your stack.
Scaling with Multiple Compose Files
While anchors work within a single file, you often need environment-specific tweaks (e.g., development vs. production). Instead of creating separate files, you can use overrides. By default, Docker Compose looks for docker-compose.yml, but you can target additional files with the -f flag.
For example:
docker-compose.yml: Contains the base architecture.docker-compose.prod.yml: Contains specific overrides, such as increased replicas or production-only volumes.
When you run docker-compose -f docker-compose.yml -f docker-compose.prod.yml up, Docker Compose reads the base file first and then "layers" the second file on top. Any keys defined in the second file will replace or append to those in the first. This approach keeps your base configuration clean while allowing you to inject production-grade constraints or environment variables only when necessary.
By combining internal anchors for structural reuse and file overrides for environmental flexibility, you ensure your infrastructure code remains readable, maintainable, and highly scalable.
Key Takeaway: Use YAML anchors to standardize repeating service attributes within a single file, and utilize multiple compose files to layer environment-specific overrides cleanly.