extends
Override files layer whole configurations on top of each other. Sometimes you need something smaller: one service built from another. A web server and a background worker usually share the same image, environment, volumes and logging settings and differ only in their command. Writing all of that twice is how drift starts ("we fixed the timezone in web but forgot worker").
extends lets a service inherit the configuration of another service, from the same file or a different one, and then add or change what it needs.
Extending a service in the same file
services:
web:
image: ghcr.io/acme/shop:4.2
environment:
DATABASE_URL: postgres://shop@db:5432/shop
TZ: UTC
restart: unless-stopped
command: ["gunicorn", "shop.wsgi", "--bind", "0.0.0.0:8000"]
ports: ["8000:8000"]
worker:
extends: web
command: ["celery", "-A", "shop", "worker"]
ports: !reset []name: demo
services:
web:
restart: unless-stopped
command:
- gunicorn
- shop.wsgi
- --bind
- 0.0.0.0:8000
environment:
DATABASE_URL: postgres://shop@db:5432/shop
TZ: UTC
image: ghcr.io/acme/shop:4.2
networks:
default: null
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
TZ: UTC
image: ghcr.io/acme/shop:4.2
networks:
default: null
networks:
default:
name: demo_default
worker got the image, environment and restart policy from web, replaced the command, and used !reset [] to drop the inherited port (two containers can't publish host port 8000). The short form extends: web is the same as extends: {service: web}.
The inheritance uses the same rules as override files: single values are replaced, mappings like environment merged by key, ports appended, volumes merged by target. So extends is "merge the parent service with this one".
A base service that never runs
Often the parent is a template, not a real service. The trick is to keep it in a separate file that is not part of the project, so Compose doesn't try to start it:
# $ docker compose config --no-path-resolution
services:
web:
extends:
file: common/services.yaml
service: python-app
command: ["gunicorn", "app:app"]
depends_on: [db]
db:
image: postgres:17
# --- common/services.yaml
services:
python-app:
build: ./app
env_file: app.env
environment:
PYTHONUNBUFFERED: "1"
volumes:
- ./data:/data
# --- common/app.env
TZ=UTCname: demo
services:
db:
image: postgres:17
networks:
default: null
web:
command:
- gunicorn
- app:app
environment:
PYTHONUNBUFFERED: "1"
TZ: UTC
networks:
default: null
volumes:
- type: bind
source: common/data
target: /data
bind: {}
build:
context: common/app
dockerfile: Dockerfile
depends_on:
db:
condition: service_started
required: true
networks:
default:
name: demo_default
Three things happened that are easy to miss:
- Only
webanddbexist.python-applives incommon/services.yaml, which isn't loaded as part of the project, so it's never started. - Paths were rebased.
./appand./dataincommon/services.yamlare relative to that file, so they becamecommon/appandcommon/data. The same goes forenv_file. env_filewas read and its variables (TZ=UTC) were folded intoenvironment.
Tip: an alternative for a template that lives in the main file is a profile nobody activates, or a YAML fragment under an
x-key. Fragments are pure YAML and can't reach into other files;extendscan.
What is inherited, and what isn't
Almost everything is inherited, including depends_on. That can surprise you: if the template depends on a service, every service extending it does too, and that service must exist in the project:
services:
web:
extends:
file: common.yaml
service: base
image: ghcr.io/acme/shop:4.2
# --- common.yaml
services:
base:
environment:
TZ: UTC
depends_on: [cache]
cache:
image: redis:8service "web" depends on undefined service "cache": invalid compose project
cache is defined in common.yaml, but extends copies one service, not its neighbours. Either define cache in the main file too or remove the dependency from the template. Keep templates free of depends_on and links, and they'll stay reusable.
Chains and cycles
A service can extend a service that itself extends another: api-debug → api → python-base. Compose resolves the chain from the root. A cycle (a extends b, b extends a) is rejected with Circular reference, listing the chain.
Here's a model that resolves a chain the way Compose does, with the merge simplified to "later keys win":
services = {
"python-base": {"image": "python:3.13-slim", "environment": {"TZ": "UTC", "PYTHONUNBUFFERED": "1"}},
"api": {"extends": "python-base", "command": "gunicorn app:app", "environment": {"ROLE": "api"}},
"api-debug": {"extends": "api", "command": "flask run --debug", "environment": {"LOG_LEVEL": "debug"}},
"a": {"extends": "b"}, "b": {"extends": "a"},
}
def resolve(name, seen=()):
if name in seen:
raise ValueError("circular reference: " + " -> ".join(seen + (name,)))
svc = dict(services[name])
parent = svc.pop("extends", None)
if parent is None:
return svc
base = resolve(parent, seen + (name,))
merged = {**base, **svc}
merged["environment"] = {**base.get("environment", {}), **svc.get("environment", {})}
return merged
for name in ["api", "api-debug", "a"]:
try:
print(name, "=>", resolve(name))
except ValueError as e:
print(name, "=>", e)api => {'image': 'python:3.13-slim', 'environment': {'TZ': 'UTC', 'PYTHONUNBUFFERED': '1', 'ROLE': 'api'}, 'command': 'gunicorn app:app'}
api-debug => {'image': 'python:3.13-slim', 'environment': {'TZ': 'UTC', 'PYTHONUNBUFFERED': '1', 'ROLE': 'api', 'LOG_LEVEL': 'debug'}, 'command': 'flask run --debug'}
a => circular reference: a -> b -> a
extends vs the alternatives
| Need | Best tool |
|---|---|
| Same settings for several services in one file | YAML anchors / x- fragments or extends |
| A shared service template used by several projects | extends with file: |
| Different settings per environment | override files |
| Reuse a whole sub-application (its own services, networks, volumes) | include |
| Optional services | profiles |
extends was removed in the old file format version 3 and came back in the Compose Specification, so very old tutorials may tell you it doesn't exist. With current Compose it's fully supported. Swarm's docker stack deploy doesn't understand it, though: render the file with docker compose config first (see From Compose to Swarm).
Learn more: include · YAML Anchors & Extensions · Override Files & Merging
Test yourself
worker extends web and sets its own command. Which command does worker run?
- web's command
- worker's command
- Both, one after the other
- An error: command defined twice
A template in common/services.yaml has build: ./app. The main compose.yaml is in the project root. Which folder is built?
- ./app
- ./common/app
- The current directory
- It fails
Why can extending a template that has depends_on: [cache] fail?
- depends_on can't be inherited
- The extending service inherits the dependency, and cache must exist in the project
- extends doesn't support depends_on in the same file
- cache would be started twice