Module 6 Lesson 4: Extension Fields and YAML Anchors
Dry out your YAML. Learn how to use anchors, aliases, and extension fields to avoid repeating the same configuration across multiple services.
Module 6 Lesson 4: Extension Fields and YAML Anchors
As your docker-compose.yml grows from 2 services to 20, you will notice a lot of repetition. Every service might have the same environment variables, the same logging config, and the same network.
To avoid "Copy-Paste Errors," we use YAML Anchors and Extension Fields.
1. Extension Fields (x-)
You can define custom blocks at the top level of your file that Docker Compose ignores, but you can "Reference" later. These must start with x-.
x-common-config: &common # The '&' creates the anchor
restart: always
networks:
- backend
environment:
DEBUG: "true"
services:
web:
<<: *common # The '<<: *' merges the anchor here
image: my-web
api:
<<: *common # The same config, without typing it again!
image: my-api
2. Overriding the Anchor
If a service needs mostly the same things as the anchor but one difference, you just define the difference below the merge:
db:
<<: *common
environment:
DEBUG: "false" # This overwrites the "true" from the anchor
3. Why Use This? (The DRY Principle)
DRY stands for "Don't Repeat Yourself."
- If you need to change the
LOG_LEVELfor all 20 services, you only have to change it in one place (the extension field). - This reduces the chance of someone forgetting to update one specific service during a deployment.
4. Cleaning Up the File
Notice how much shorter your file becomes!
- It is easier to read.
- It is easier to audit.
- It is easier to maintain.
Exercise: The Anchor Architect
- Create a Compose file with 3 services:
worker-a,worker-b, andworker-c. - Define an extension field
x-worker-basethat includes:- An image (
busybox). - A command (
sleep 3600). - A restart policy (
on-failure).
- An image (
- Use the
<<: *syntax to apply this base to all three workers. - For
worker-c, override the command tosleep 5000. - Run
docker-compose config. Look at the output. Did Docker correctly "Expand" your anchors into a full file?
Summary
YAML anchors and extension fields are the "Variables" and "Functions" of the DevOps world. They keep your configuration clean, predictable, and scalable as your architecture grows in complexity.
Next Lesson: Environment splitting: Multi-file configuration (base + override).