Docker Compose — Anchors and Aliases

1 minute read

YAML anchors (&) and aliases (*) are core YAML features that let you reuse any value or block.

Basic Anchor and Alias

# Define an anchor
x-image: &default-image node:20-alpine

services:
  api:
    image: *default-image      # Reuse via alias
  worker:
    image: *default-image      # Same image

Resolves to:

services:
  api:
    image: node:20-alpine
  worker:
    image: node:20-alpine

Block Anchors with Merge

x-deploy: &deploy-config
  deploy:
    resources:
      limits:
        cpus: "0.5"
        memory: 512M
      reservations:
        cpus: "0.25"
        memory: 256M

services:
  api:
    <<: *deploy-config
    image: myapi:latest

  worker:
    <<: *deploy-config
    image: myworker:latest

Anchor for Lists

x-networks: &app-networks
  networks:
    - frontend
    - backend

services:
  api:
    image: myapi:latest
    <<: *app-networks

  web:
    image: nginx:alpine
    <<: *app-networks

Override After Merge

x-common: &common
  restart: unless-stopped
  environment:
    LOG_LEVEL: info

services:
  api:
    <<: *common
    image: myapi:latest
    environment:             # Overrides the merged environment entirely
      LOG_LEVEL: debug
      PORT: "3000"

Important: <<: merge does a shallow merge. Nested maps (like environment:) are replaced entirely, not deep-merged.

Deep Merge Workaround

For deep merging, use multiple anchors:

x-env-base: &env-base
  LOG_LEVEL: info
  NODE_ENV: production

services:
  api:
    image: myapi:latest
    environment:
      <<: *env-base
      PORT: "3000"       # Added to base env vars

Anchor Naming Best Practices

Pattern Example
By function &logging, &healthcheck
By component &node-service, &python-service
Clear prefix x-logging: &logging

Summary

Feature Syntax Purpose
Anchor &name Define reusable value
Alias *name Reference anchor value
Merge <<: *name Merge map into current
Multi-merge <<: [*a, *b] Merge multiple maps
Override Local key Wins over merged value

Quick Reference

Item Detail
&name Define an anchor
*name Reference (alias) an anchor
«: *name Merge a map anchor
Shallow merge Nested maps replaced entirely
Deep merge Anchor on the nested map itself