Docker Compose — Compose Include

1 minute read

The include directive (Compose v2.20+) lets you split a large compose file into modular, reusable pieces.

Why Include?

Before:
  compose.yml (500+ lines, hard to maintain)

After:
  compose.yml          ← main orchestration
  compose.db.yml       ← database services
  compose.monitoring.yml ← monitoring stack
  compose.cache.yml    ← caching services

Basic Include

compose.yml:

include:
  - compose.db.yml
  - compose.cache.yml

services:
  api:
    build: ./api
    ports:
      - "3000:3000"
    depends_on:
      db:
        condition: service_healthy

compose.db.yml:

services:
  db:
    image: postgres:16
    environment:
      POSTGRES_PASSWORD: secret
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 5s
      retries: 5
    volumes:
      - db-data:/var/lib/postgresql/data

volumes:
  db-data:

compose.cache.yml:

services:
  cache:
    image: redis:7
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 5s
      retries: 5

Include with Path

include:
  - path: ./infra/compose.db.yml
  - path: ./infra/compose.cache.yml
    env_file: ./infra/.env.cache

Include with Project Directory

include:
  - path: ./infra/compose.db.yml
    project_directory: ./infra

The project_directory changes the base path for relative paths in the included file.

Include vs Multiple -f Files

Feature include: docker compose -f a.yml -f b.yml
In compose.yml Yes No (CLI only)
Self-contained Yes Requires CLI args
Merge behavior Side by side Override/merge
Version v2.20+ Always available

Real-World Structure

project/
├── compose.yml                  # Main entry point
├── compose.override.yml         # Dev overrides (auto-loaded)
├── infra/
│   ├── compose.db.yml           # Database services
│   ├── compose.cache.yml        # Cache services
│   └── compose.monitoring.yml   # Monitoring stack
└── services/
    ├── api/
    └── web/

Summary

Feature Detail
Directive include: in compose.yml
Version Compose v2.20+
Format List of paths or objects
project_directory Base path for included file
env_file Per-include env file

Quick Reference

Item Detail
include: Import other compose files
Version Compose v2.20+
path: Path to included file
project_directory: Base path for relative paths
env_file: Per-include environment file
vs -f include is self-contained in compose.yml