TExcelTAD
Home › Docker Compose › YAML Anchors & Extensions

YAML Anchors & Extensions

Compose files repeat themselves. Five services with the same logging options, three with the same environment block, two with the same healthcheck settings. extends handles whole services, but for smaller pieces there's a lighter tool that's built into YAML itself: anchors and aliases. Compose adds extension fields (x-…) as a tidy place to keep those reusable pieces.

Anchors, aliases and merge keys

Three bits of YAML syntax, none of them specific to Compose:

Syntax Name Meaning
&name anchor "remember this value under name"
*name alias "insert the remembered value here"
<<: *name merge key "copy the keys of this mapping in here; my own keys win"

The YAML parser resolves these before Compose sees the file. Compose only ever sees the expanded result, so anything Compose can do with a hand-written value, it can do with an aliased one.

x- extension fields

Compose rejects unknown top-level keys, with one exception: any key starting with x- is ignored. That makes x- keys the natural home for anchored fragments:

compose · try it yourself
x-logging: &default-logging
  driver: json-file
  options:
    max-size: 10m
    max-file: "3"

x-env: &common-env
  TZ: UTC
  LOG_FORMAT: json

services:
  web:
    image: ghcr.io/acme/shop:4.2
    logging: *default-logging
    environment:
      <<: *common-env
      ROLE: web
  worker:
    image: ghcr.io/acme/shop:4.2
    command: ["celery", "-A", "shop", "worker"]
    logging: *default-logging
    environment:
      <<: *common-env
      LOG_FORMAT: text
name: demo
services:
  web:
    environment:
      LOG_FORMAT: json
      ROLE: web
      TZ: UTC
    image: ghcr.io/acme/shop:4.2
    logging:
      driver: json-file
      options:
        max-file: "3"
        max-size: 10m
    networks:
      default: null
  worker:
    command:
      - celery
      - -A
      - shop
      - worker
    environment:
      LOG_FORMAT: text
      TZ: UTC
    image: ghcr.io/acme/shop:4.2
    logging:
      driver: json-file
      options:
        max-file: "3"
        max-size: 10m
    networks:
      default: null
networks:
  default:
    name: demo_default
x-env:
  LOG_FORMAT: json
  TZ: UTC
x-logging:
  driver: json-file
  options:
    max-file: "3"
    max-size: 10m
  • logging: *default-logging inserted the whole mapping.
  • <<: *common-env merged TZ and LOG_FORMAT into each environment, and the local keys (ROLE, and LOG_FORMAT: text in the worker) won over the merged ones.
  • The x- blocks are kept, at the end of the output, untouched. Compose carries them along so other tools can read them, but never acts on them.

A whole service template

A fragment can hold a complete partial service, which gives you extends-like reuse inside one file:

compose · try it yourself
x-app: &app
  image: ghcr.io/acme/shop:${SHOP_TAG:-4.2}
  restart: unless-stopped
  environment:
    DATABASE_URL: postgres://shop@db:5432/shop
  depends_on: [db]

services:
  web:
    <<: *app
    command: ["gunicorn", "shop.wsgi"]
    ports: ["8000:8000"]
  worker:
    <<: *app
    command: ["celery", "-A", "shop", "worker"]
  scheduler:
    <<: *app
    command: ["celery", "-A", "shop", "beat"]
  db:
    image: postgres:17
name: demo
services:
  db:
    image: postgres:17
    networks:
      default: null
  scheduler:
    restart: unless-stopped
    command:
      - celery
      - -A
      - shop
      - beat
    environment:
      DATABASE_URL: postgres://shop@db:5432/shop
    image: ghcr.io/acme/shop:4.2
    networks:
      default: null
    depends_on:
      db:
        condition: service_started
        required: true
  web:
    restart: unless-stopped
    command:
      - gunicorn
      - shop.wsgi
    environment:
      DATABASE_URL: postgres://shop@db:5432/shop
    image: ghcr.io/acme/shop:4.2
    networks:
      default: null
    depends_on:
      db:
        condition: service_started
        required: true
    ports:
      - mode: ingress
        target: 8000
        published: "8000"
        protocol: tcp
  worker:
    restart: unless-stopped
    command:
      - celery
      - -A
      - shop
      - worker
    environment:
      DATABASE_URL: postgres://shop@db:5432/shop
    image: ghcr.io/acme/shop:4.2
    networks:
      default: null
    depends_on:
      db:
        condition: service_started
        required: true
networks:
  default:
    name: demo_default
x-app:
  depends_on:
    - db
  environment:
    DATABASE_URL: postgres://shop@db:5432/shop
  image: ghcr.io/acme/shop:4.2
  restart: unless-stopped

Notice that ${SHOP_TAG:-4.2} in the fragment was interpolated in each service, just as if you had written it three times.

Warning: the merge key is shallow. If a service writes <<: *app and then its own environment:, the service's environment replaces the fragment's whole environment mapping; it does not merge into it. That's different from override files, which merge mappings key by key. To combine both, merge at the inner level too: environment: {<<: *app-env, ROLE: web}.

The difference, shown with PyYAML, which implements the same YAML merge rules:

python · try it yourself
import yaml

doc = """
x-app: &app
  image: shop:4.2
  environment: {TZ: UTC, LOG_FORMAT: json}
x-env: &env {TZ: UTC, LOG_FORMAT: json}

shallow:
  <<: *app
  environment: {ROLE: web}

deep:
  <<: *app
  environment:
    <<: *env
    ROLE: web
"""
data = yaml.safe_load(doc)
print("shallow:", data["shallow"]["environment"])
print("deep:   ", data["deep"]["environment"])
shallow: {'ROLE': 'web'}
deep:    {'TZ': 'UTC', 'LOG_FORMAT': 'json', 'ROLE': 'web'}

In shallow, TZ and LOG_FORMAT are gone. That's a classic source of "why is my timezone wrong in production?".

Service-level extensions

x- keys are also allowed inside services (and networks, volumes…). Compose ignores them but keeps them in the output, which makes them a good place for metadata that your own scripts read:

compose · try it yourself
services:
  web:
    image: ghcr.io/acme/shop:4.2
    x-owner: team-storefront
    x-oncall: "#storefront-alerts"
name: demo
services:
  web:
    image: ghcr.io/acme/shop:4.2
    networks:
      default: null
    x-oncall: '#storefront-alerts'
    x-owner: team-storefront
networks:
  default:
    name: demo_default

A plain unknown key such as owner: would be rejected by schema validation (services.web.owner false schema). Prefer labels for metadata that should reach the running container (docker inspect shows labels; x- keys never leave the file).

Limits of anchors

Anchors don't cross files. Each YAML file is parsed on its own, so an override file can't use an anchor defined in compose.yaml:

compose · try it yourself
x-env: &common-env
  TZ: UTC

services:
  web:
    image: ghcr.io/acme/shop:4.2

# --- compose.override.yaml
services:
  web:
    environment: *common-env
go-yaml load error in composer at L3.C18: unknown anchor 'common-env' referenced

The error comes from the YAML parser (unknown anchor), before Compose even looks at services. For sharing across files use extends or include.

Other limits:

  • Anchors must be defined before they're used (top to bottom).
  • Merge keys only work on mappings. There's no way to merge lists (ports, command) with <<; an alias can only insert a whole list.
  • Overusing anchors makes a file hard to read: the reader has to jump around to know what a service really is. docker compose config prints the expanded file and is the quickest cure.

Which reuse tool when?

python · try it yourself
def pick(scope, across_files, whole_service, needs_merge_by_key):
    if scope == "application":
        return "include"
    if across_files and whole_service:
        return "extends (file: ...)"
    if across_files:
        return "override file (-f) or extends"
    if whole_service and needs_merge_by_key:
        return "extends (deep merge like override files)"
    return "x- fragment + anchor/alias/merge key"

cases = [
    ("same logging for 6 services",              ("service", False, False, False)),
    ("web/worker/beat share image+env",           ("service", False, True, True)),
    ("company-wide service template",             ("service", True, True, True)),
    ("monitoring stack owned by another team",    ("application", True, True, False)),
]
for what, args in cases:
    print(f"{what:<42} -> {pick(*args)}")
same logging for 6 services                -> x- fragment + anchor/alias/merge key
web/worker/beat share image+env            -> extends (deep merge like override files)
company-wide service template              -> extends (file: ...)
monitoring stack owned by another team     -> include

Swarm stacks accept x- fields and anchors too (the YAML is expanded the same way), so fragments are portable between Compose and Stack Files. Kubernetes manifests usually reach for Kustomize or Helm templates instead.

Learn more: extends · The Compose File · Override Files & Merging

Test yourself

Why are reusable fragments usually put under keys starting with x-?

  1. x- keys are faster
  2. Compose ignores top-level keys that start with x-, instead of rejecting them as unknown
  3. x- keys are merged into every service automatically
  4. YAML requires it for anchors

A service has <<: *app and its own environment: {ROLE: web}. The fragment also has an environment. What is the result?

  1. Both environments merged
  2. Only ROLE: web, the fragment's environment is replaced
  3. An error
  4. Only the fragment's environment

Can compose.override.yaml use an anchor defined in compose.yaml?

  1. Yes
  2. No, each file is parsed separately, so the anchor is unknown
  3. Only with include
  4. Only for x- keys