brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: share config between services with YAML anchors and x- fields

Yaml
~/tips/tip-docker-compose-anchors

x-common: &common

Defines a settings block once and reuses it in several services of one compose file.

Five services, the same restart policy, the same logging options, the same environment. Copy-pasting that block is how typos get in.

Compose understands plain YAML anchors. You name a block with &, then reuse it with * and merge it with <<. Top-level keys that start with x- are ignored by Compose, which makes them a good place to park the shared block.

x-common: &common
  restart: unless-stopped
  logging:
    driver: json-file
    options:
      max-size: "10m"

services:
  web:
    <<: *common
    image: nginx
  worker:
    <<: *common
    image: myworker

Both services get the restart policy and the log rotation. Anything you set next to the merge key overrides the shared value.

It also means a change to your logging settings is one edit instead of five. Compose does not care about the name after x-, so pick something descriptive like x-common or x-logging.

The caveat: merge works on mappings only, not on lists. If you use fragments, write environment as KEY: value and not as a list of KEY=value. Anchors are resolved before variables, so you cannot build an anchor out of a variable. Run docker compose config to see the merged result.

Further reading: Fragments in Compose, On this site: RUN –mount=type=cache keeps pip and apt downloads between builds, On this site: put optional services behind a Compose profile

More Yaml tips yamllint -f parsable config.yaml yamllint -d relaxed docker-compose.yml iif(condition, if_true, if_false, if_none) Sensor is available Today_at() makes time-of-day checks in Home Assistant templates easy All Yaml tips (10) All topics

Link