Cloud Native › Compose

Modularizing monorepo stacks with Docker Compose include

Keep relative paths and .env interpolation intact across monorepo folders with Docker Compose include, verified on Compose v5.7.1 vs -f and extends.

Modularizing monorepo stacks with Docker Compose include

Merging Compose files across monorepo directories with docker compose -f breaks build.context, env_file, and bind-mount paths because Compose resolves every relative path against the first file’s directory. Top-level include keeps each module’s own directory and .env interpolation intact while sharing one default network—though on Compose v5.7.1, duplicate service names merge silently instead of failing, so precedence rules matter.

All configurations and command outputs in this post were verified on macOS (ARM64) with Docker Engine 29.9.3 and Docker Compose v5.7.1 using real local containers (postgres:16-alpine, a custom alpine:3.21 API image, and nginx:1.27-alpine). Remote Git/OCI include sources and nested include chains were outside this test scope.


Why -f multi-file merging breaks relative paths

In a monorepo, teams naturally keep each service’s compose.yaml, Dockerfile, .env, and init scripts inside its own directory. Consider this layout with an infra/ folder and a services/api/ folder:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
monorepo-shop/
├── compose.yaml                       # Root entry point (name: monorepo-shop)
├── infra/
│   ├── compose.yaml                   # db (postgres:16-alpine) + ./init.sql + named volume
│   ├── init.sql                       # Creates products table and 2 seed rows
│   └── observability/
│       └── compose.yaml               # metrics (nginx:1.27-alpine, profiles: [monitoring])
└── services/
    └── api/
        ├── compose.yaml               # api (build: ., env_file: .env, ${API_PORT:-18639})
        ├── compose.override.yaml      # Used for path-array override
        ├── Dockerfile                 # alpine:3.21 + psql + busybox httpd
        ├── .env                       # API_PORT=18630, APP_ENV=local, API_BANNER=monorepo-api-v1
        └── www/cgi-bin/products       # Queries Postgres and returns text/plain

The first instinct is usually to pass multiple -f flags from the repository root. That fails immediately during config validation:

1
2
3
$ docker compose -f compose.yaml -f infra/compose.yaml -f services/api/compose.yaml config
env file /tmp/compose-include-lab/.env not found: stat /tmp/compose-include-lab/.env: no such file or directory
# EXIT=1

With -f, Docker Compose anchors every relative path to the first -f file’s directory (or --project-directory). As a result, env_file: .env and build.context: . inside services/api/compose.yaml, along with ./init.sql inside infra/compose.yaml, all resolve against the repository root instead of their own folders.

Even if you create an empty root .env to get past config, the resolved model still points build.context to the root (/tmp/compose-include-lab) and init.sql to /tmp/compose-include-lab/init.sql. Running a build fails right away:

1
2
3
4
$ touch .env
$ docker compose -f compose.yaml -f infra/compose.yaml -f services/api/compose.yaml build
failed to solve: failed to read dockerfile: open Dockerfile: no such file or directory
# EXIT=1

Passing --project-directory doesn’t fix this either—it accepts only one directory for the entire command, so sibling modules like infra/ and services/api/ still collide.


Preserving module paths and .env context with include

Top-level include changes the parsing order. Compose parses each included file as an independent sub-project first, using that file’s directory as its default project_directory. Relative build.context, bind mounts, env_file, and .env variable interpolation all finish inside the module’s own folder before Compose merges the resulting services, volumes, and networks into the root project (monorepo-shop).

flowchart TD
    Root["Root compose.yaml"]
    SubInfra["infra/compose.yaml<br/>dir: infra/"]
    SubApi["services/api/compose.yaml<br/>dir: services/api/ + .env"]
    SubObs["observability/compose.yaml<br/>profile: monitoring"]
    Merged["monorepo-shop project<br/>Shared default network"]

    Root --> SubInfra
    Root --> SubApi
    Root --> SubObs
    SubInfra --> Merged
    SubApi --> Merged
    SubObs --> Merged

Module files and root compose.yaml

Each module stays self-contained. The infra/compose.yaml file mounts ./init.sql and declares a healthcheck using the same patterns covered in seeding Postgres with initdb.d and Compose Watch and ordering startup with depends_on and healthcheck.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# infra/compose.yaml
services:
  db:
    image: postgres:16-alpine
    environment:
      POSTGRES_DB: shop
      POSTGRES_USER: shop_user
      POSTGRES_PASSWORD: shop_dev_password
    volumes:
      - db-data:/var/lib/postgresql/data
      - ./init.sql:/docker-entrypoint-initdb.d/init.sql:ro
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U shop_user -d shop"]
      interval: 3s
      timeout: 3s
      retries: 10

volumes:
  db-data:

services/api/compose.yaml references its local Dockerfile and .env, then waits on db from the included infrastructure module:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# services/api/compose.yaml
services:
  api:
    build:
      context: .
      dockerfile: Dockerfile
    env_file:
      - .env
    environment:
      DB_HOST: db
      DB_NAME: shop
      DB_USER: shop_user
      DB_PASSWORD: shop_dev_password
    ports:
      - "${API_PORT:-18639}:8080"
    depends_on:
      db:
        condition: service_healthy
# services/api/.env
API_PORT=18630
APP_ENV=local
API_BANNER=monorepo-api-v1

At the repository root, the shorthand syntax wires all three modules together:

1
2
3
4
5
6
7
# compose.yaml (shorthand)
name: monorepo-shop

include:
  - infra/compose.yaml
  - infra/observability/compose.yaml
  - services/api/compose.yaml

When you need to override a module’s base directory or swap its interpolation .env file, use the long-form object syntax (path, project_directory, env_file):

1
2
3
4
5
6
7
8
# compose.yaml (long form)
name: monorepo-shop

include:
  - infra/compose.yaml
  - path: services/api/compose.yaml
    project_directory: services/api
    env_file: services/api/.env.local

include.env_file only controls YAML variable interpolation (such as ${API_PORT}). When I set API_PORT=18635 in services/api/.env.local and checked docker compose config, the published host port changed to "18635", while the container’s runtime API_PORT injected by services.api.env_file: .env remained "18630".

Verifying shared networking and live requests

Starting the shorthand root file builds services/api, loads infra/init.sql, and places both containers on the same default bridge network:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$ docker compose up -d --build --wait
$ docker compose ps
NAME                  IMAGE                COMMAND                  SERVICE   CREATED          STATUS                    PORTS
monorepo-shop-api-1   monorepo-shop-api    "httpd -f -p 8080 -h…"   api       1 second ago     Up Less than a second     0.0.0.0:18630->8080/tcp, [::]:18630->8080/tcp
monorepo-shop-db-1    postgres:16-alpine   "docker-entrypoint.s…"   db        14 seconds ago   Up 13 seconds (healthy)   5432/tcp

$ curl -i -sS http://localhost:18630/cgi-bin/products
HTTP/1.1 200 OK
Content-Type: text/plain

banner=monorepo-api-v1 env=local
1,Mechanical Keyboard,149000
2,USB-C Hub,59000

$ docker network inspect monorepo-shop_default --format '{{range .Containers}}{{.Name}} ({{.IPv4Address}}){{"\n"}}{{end}}'
monorepo-shop-db-1 (172.29.0.2/16)
monorepo-shop-api-1 (172.29.0.3/16)

Without any external network boilerplate, api resolves db over monorepo-shop_default, reads the two seeded rows, and serves them on port 18630 from services/api/.env.


Name collision precedence and safe override patterns in Compose v5.7.1

Duplicate service names merge silently on Compose v5.7.1

Older Compose v2.20 guides often state that declaring the same service name in the root file or across two include entries raises a conflict error. On Docker Compose v5.7.1, that’s no longer what happens—all three duplicate-name cases I tested exited with status 0 and merged silently:

  1. Root compose.yaml or compose.override.yaml vs. an included file: The root definition wins and overrides matching fields such as API_BANNER.
  2. Two separate include entries defining the same service (worker): The earlier include entry wins. In the test run, the first entry’s image: alpine:3.21 and WHO: from-inc-a stayed intact, while the second entry’s conflicting image and WHO values were silently ignored. Non-conflicting keys (ONLY_A, ONLY_B) merged together.

In short, field precedence on Compose v5.7.1 follows root / compose.override.yaml > earlier include > later include.

Watch out for silent overrides: With -f, later files override earlier files. Across separate include entries, the direction flips—the earlier entry wins and conflicting fields in later entries drop without warning. If two teams happen to name a service worker or redis, Compose will quietly blend them. Enforce distinct service names per module and inspect docker compose config in CI.

Explicit overrides with path: [base, override]

When you intentionally want to override an included module, don’t duplicate the service across separate include items. Pass a list to path inside a single include object instead:

1
2
3
4
5
6
7
# services/api/compose.override.yaml
services:
  api:
    environment:
      API_BANNER: monorepo-api-override
    ports:
      - "18632:8080"
1
2
3
4
5
6
7
8
# compose.yaml
name: monorepo-shop

include:
  - infra/compose.yaml
  - path:
      - services/api/compose.yaml
      - services/api/compose.override.yaml

Inside a path array, later files override earlier files just like -f. Map fields like environment replace matching keys (API_BANNER), while list fields like ports append (18630 plus 18632).

1
2
3
4
5
$ docker compose up -d --wait
$ curl -sS http://localhost:18632/cgi-bin/products
banner=monorepo-api-override env=local
1,Mechanical Keyboard,149000
2,USB-C Hub,59000

Combining include with profiles

You don’t have to boot every included module on every run. Combining include with profiles (see splitting Docker Compose stacks with profiles and overrides) keeps optional stacks out of default startup:

1
2
3
4
5
6
7
8
# infra/observability/compose.yaml
services:
  metrics:
    image: nginx:1.27-alpine
    profiles:
      - monitoring
    ports:
      - "18631:80"

A plain docker compose up -d starts only api and db. Adding --profile monitoring brings up metrics on the same monorepo-shop_default network, where it can reach api by service name immediately:

1
2
3
4
5
6
7
8
9
10
11
$ docker compose --profile monitoring up -d --wait
$ docker compose --profile monitoring ps --format "table {{.Name}}\t{{.Service}}\t{{.Status}}\t{{.Ports}}"
NAME                      SERVICE   STATUS                        PORTS
monorepo-shop-api-1       api       Up 1 second                   0.0.0.0:18630->8080/tcp, [::]:18630->8080/tcp
monorepo-shop-db-1        db        Up About a minute (healthy)   5432/tcp
monorepo-shop-metrics-1   metrics   Up Less than a second         0.0.0.0:18631->80/tcp, [::]:18631->80/tcp

$ docker compose exec metrics wget -qO- http://api:8080/cgi-bin/products
banner=monorepo-api-v1 env=local
1,Mechanical Keyboard,149000
2,USB-C Hub,59000

Comparing -f, extends, and include

All three mechanisms reuse Compose definitions, but they operate at different boundaries:

Dimension-f multi-file mergeextends (service inheritance)include (sub-project composition)
Unit of reuseConfig layers in one projectSingle service templateFull sub-project (services, volumes, networks, secrets)
Relative path baseFirst -f file’s directoryextends.file directoryEach module’s project_directory
Sub-directory .env interpolationNo (root .env only)No (falls back to default values)Yes (overrideable via env_file:)
Top-level volumes & networksMergedNot imported (must redeclare at root)Merged automatically (shared default network)
Override precedenceLater -f winsCalling service winsroot / compose.override.yaml > earlier include > later include (later wins inside path list)
Best fitSame-directory env overlays (compose.prod.yaml)Shared logging, limits, or healthcheck templatesMonorepo and multi-team domain/infra modules

Testing extends against the same infra/compose.yaml and services/api/compose.yaml on Compose v5.7.1 confirmed two clear limits. While extends preserved build.context, ./init.sql, env_file, and depends_on, it failed in two places:

  1. Missing top-level volumes: Without manually redeclaring volumes: db-data: in the root file, docker compose config exited with code 1 (service "db" refers to undefined volume db-data: invalid compose project).
  2. No sub-directory .env interpolation: Even after redeclaring db-data at the root, ${API_PORT:-18639} ignored services/api/.env (18630) and fell back to 18639.

When not to use include

Skip include in three situations:

  • Environment overlays in one directory: If compose.yaml and compose.prod.yaml live side by side, -f and compose.override.yaml are simpler and keep override order obvious.
  • Shared service boilerplate: If you only want to share logging drivers, CPU/memory limits, or healthcheck defaults across services, use extends or YAML anchors (x-common).
  • Mixed older Compose versions: include requires Compose v2.20+. If any CI runner or developer machine runs an older binary, standardize Compose versions before splitting files.

Operational caveats and checklist

Before rolling include out across a monorepo, run through these four checks:

  • Guard against silent name collisions: On Compose v5.7.1, duplicate service names across include entries won’t error out—the first entry silently wins. Run docker compose config --services and diff docker compose config whenever you add a module.
  • Separate include.env_file from services.*.env_file: The former drives ${VAR} substitution at parse time; the latter injects runtime environment variables into the container. Mixing them up causes host ports and app settings to drift.
  • Remember list appending in path: [base, override]: Keys inside environment replace earlier values, while list fields like ports or volumes append. Use variable substitution or !override if you need to replace a list completely.
  • Include active profiles on teardown: When tearing down a stack that uses optional profiles, run docker compose --profile monitoring down -v so profile-scoped containers and volumes don’t get left behind.

References

How to use Docker Compose's include top-level element
Reference external Compose files using the include top-level element
This post is licensed under CC BY 4.0 by the author.