Lesson 7 of 24Real apps
Compose for Local Development
Turn compose.yaml into a fast dev loop: watch mode, override files, profiles, one-off tasks, and reading the merged config when things go wrong.
On your first week at a new job, the README says "run docker compose up and open localhost:3000". It works, but every code change means a rebuild, the database migrations are a separate tribal-knowledge command, and half the team keeps a private compose.override.yaml that nobody else has seen. The basics from Docker Compose get the stack running; this lesson is about making it pleasant to work in every day. You will learn how Compose syncs your edits into containers, how several files merge into one, how to keep optional tools out of the way, and the one command that answers "what is Compose actually doing?".
Two ways to get your edits into a container
A production image copies your source in at build time. In development you want a save in your editor to show up in the running app within a second. There are two tools for this, and they behave very differently.
A bind mount maps a host folder over a path in the container. The container sees your files directly, both ways, live. Compose watch (the develop.watch section) instead watches your files on the host and copies changed ones into the container, or rebuilds the image when a file such as the lockfile changes.
services:
api:
build: ./api
command: uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload
ports: ["8000:8000"]
develop:
watch:
- action: sync
path: ./api/app
target: /app/app
ignore:
- __pycache__/
- action: rebuild
path: ./api/uv.lock
web:
build: ./web
ports: ["3000:3000"]
develop:
watch:
- action: sync
path: ./web/src
target: /app/src
- action: rebuild
path: ./web/package-lock.json
- action: sync+restart
path: ./web/next.config.ts
target: /app/next.config.tsEach rule has a path on the host (relative to the project directory) and an action:
| Action | What Compose does | Use it for |
|---|---|---|
sync | Copies the changed file to target in the running container | Source code your dev server already hot-reloads |
rebuild | Builds a new image and replaces the container, like up --build for that service | Lockfiles, Dockerfile changes, anything installed at build time |
sync+restart | Copies the file, then restarts the container | Config read only at startup (Nginx config, framework config) |
sync+exec | Copies the file, then runs a command you give in exec: inside the container | Regenerating something after a change |
restart | Restarts the container without syncing | A change that only needs a fresh process |
Start it with docker compose up --watch, which builds, starts, and watches in one go with logs in your terminal. docker compose watch does the same but interleaves the sync and rebuild events with the logs, which is handy when you want to see what watch is doing. The newer actions (sync+exec, restart) arrived in later Compose releases, so check the Compose file reference if an older install rejects them.
Compose watches ./web/src on the host. The save matches the sync rule.
A few rules trip people up:
ignorepatterns are relative to that rule'spath, not the project root.node_modules/under a rule for./webmeans./web/node_modules/.- Watch respects
.dockerignore, and it skips.gitand common editor temp files on its own. - Watch only works for services with
build:. A service that only hasimage:is not watched. - Sync copies files with tools inside the container, so the image needs basic utilities (
stat,mkdir,rmdir) and the container'sUSERmust be able to write totarget. If you switched to a non-root user, copy the source withCOPY --chown=app:appor sync fails with permission errors. initial_sync: truemakes Compose bring the container's files up to date at the start of a watch session, so edits you made while watch was off are not lost.
When a bind mount is still the right tool
Watch is one-way: host to container. Bind mounts are two-way, which matters when something inside the container writes files you want on your laptop: generated migration files, code formatters run in the container, snapshot tests that write .snap files, or a debugger that expects the exact same paths. Bind mounts also need no rules at all.
The cost is file sharing performance. On Linux a bind mount is just the same filesystem, so it is free. On macOS and Windows, Docker runs in a Linux VM, and every file access through a bind mount crosses from the VM to your host filesystem. Docker Desktop's file sharing has improved a lot, but a dev server that scans 50,000 files in node_modules on every request can still feel slow. Watch avoids that because the container reads its own local copy.
A common setup: watch for source code, a bind mount for one folder the container must write back to (say ./api/migrations).
The node_modules and .venv trap
The dangerous bind mount is the obvious one: ./web:/app. It puts your whole host folder over /app, including your host's node_modules, or your host's .venv. Those contain compiled native code (esbuild, sharp, psycopg wheels) built for macOS or Windows. The Linux container tries to load them and crashes with an error about a missing binary for linux-arm64 or an invalid ELF header. Worse, if you have no host node_modules, the mount hides the one the image installed, and the app cannot find any packages.
The classic fix is an anonymous volume on that one path:
services:
web:
build: ./web
volumes:
- ./web:/app
- /app/node_modulesThe second entry has no host side. Docker creates a volume for that path and, on first creation, copies the image's node_modules into it. The bind mount covers everything else. For Python, mount /app/.venv the same way, or put the virtualenv outside the source tree (UV_PROJECT_ENVIRONMENT=/opt/venv) so the mount never touches it.
Here is the part most people learn the hard way. That volume persists between runs of the same container. Add a package to package.json, rebuild the image, and docker compose up reuses the old anonymous volume with the old packages: "module not found" for the package you just installed. Recreate it:
docker compose up --build --renew-anon-volumes web(-V is the short form.) Watch sidesteps this whole class of bug: you sync only src/, and a lockfile change triggers a rebuild, so packages always come from the image.
./web:/app plus an anonymous volume at /app/node_modules. You add zod to package.json, run docker compose up --build, and the app fails with Cannot find module 'zod'. Why?Several files, one model
Real projects rarely have one Compose file. Compose reads compose.yaml and, if it exists in the same folder, compose.override.yaml automatically. That makes the override file the natural place for dev-only settings: bind mounts, debug ports, --reload commands. Teams split it two ways. Either the override is committed and production uses -f compose.yaml alone, or the override is gitignored for personal tweaks and a compose.override.example.yaml is committed.
Pass -f and Compose reads only the files you list, in order, each one merged on top of the last:
docker compose -f compose.yaml -f compose.ci.yaml up --waitYou can set the same list with COMPOSE_FILE (separated by : on macOS and Linux, ; on Windows), which is how CI jobs usually do it.
The merge rules are not "later file wins" for everything. They depend on the kind of value:
| Kind of key | Examples | Merge rule |
|---|---|---|
| Single values | image, command, entrypoint, healthcheck.test, mem_limit | Later file replaces |
| Sequences | ports, expose, dns, tmpfs | Combined; an identical port entry is not duplicated |
| Maps keyed by name | environment, labels | Merged by key; later file wins for the same key |
| Mounts | volumes, devices | Merged by container path; later file wins for the same path |
The ports rule surprises people. If the base has "8000:8000" and the override has "9000:8000", the service publishes both. When you really want to replace a list, use the !override tag, and to delete something the base file set, use !reset:
services:
api:
ports: !override
- "9000:8000"
environment:
SENTRY_DSN: !reset nullRun the model below. It applies the same rules to two small files.
Press Run (⌘ Enter) to see what happens.What does this print?
base = ["8000:8000"] override = ["9000:8000"] merged = base + [p for p in override if p not in base] print(len(merged), merged)
include and extends
Two more tools split big stacks:
include:at the top level pulls in another Compose file as its own sub-project. Relative paths inside it resolve from its folder, and it can load its own.env. This suits a platform team that ownsinfra/compose.yaml(Postgres, Redis, Kafka) while product teams include it. Duplicate service names between files are a conflict, not a merge, so do not useincludeto override things.extends:on a service copies another service's definition (from the same file or another file) and lets you change fields. It is for sharing a base definition, such as aworkerand aschedulerthat both run your API image with the same env.
include:
- infra/compose.yaml
services:
api:
build: ./api
worker:
extends:
service: api
command: python -m app.workerProfiles in depth
The Docker Compose lesson showed a tools profile for Adminer. In practice profiles hold three kinds of things: tools (Adminer, Mailpit to catch outgoing email, a Redis UI), optional workers (the search indexer you only need when working on search), and heavy dependencies (a local Kafka or an observability stack).
services:
api:
build: ./api
db:
image: postgres:17
mailpit:
image: axllent/mailpit
ports: ["8025:8025"]
profiles: ["tools"]
indexer:
build: ./api
command: python -m app.indexer
profiles: ["search"]
depends_on: [db]The rules:
- A service with no
profiles:key always starts. Keep the core stack unprofiled. - Enable profiles with repeated flags (
--profile tools --profile search) or theCOMPOSE_PROFILESvariable, comma-separated.--profile "*"enables everything. - Naming a profiled service on the command line starts it even if its profile is off, along with its dependencies.
docker compose run --rm indexerworks without--profile search. - A dependency that is itself behind a disabled profile does not start. Keep shared dependencies unprofiled or in the same profile.
COMPOSE_PROFILES=tools,search docker compose up -dMany developers put COMPOSE_PROFILES=tools in their .env so their favourite tools always come up without changing the shared file.
One-off tasks: run, exec, and init steps
Migrations, seeds, shells, and test runs are commands, not long-running services. Compose gives you two ways to run them:
docker compose exec api alembic upgrade headruns inside the already runningapicontainer. Fast, shares its state, fails ifapiis not up.docker compose run --rm api alembic upgrade headstarts a new container from the service definition (same image, env, volumes, networks), runs the command, and removes it. It also starts the service's dependencies first (skip with--no-deps).
run does not publish the service's ports: by default, so two runs never fight over port 8000. If you need them, say so with --service-ports. Debugging with a breakpoint is the common case:
docker compose run --rm --service-ports api python -m pdb -m app.mainTo run migrations and seeds automatically before the API starts, make them their own service and depend on its success:
services:
migrate:
build: ./api
command: alembic upgrade head
depends_on:
db:
condition: service_healthy
api:
build: ./api
depends_on:
migrate:
condition: service_completed_successfullymigrate runs once, exits, and api only starts if it exited with code 0. A failed migration stops the stack with a clear error instead of an API that crashes on missing tables. Compose 5.3 added native init containers through a pre_start: list on the service itself, which does the same job without a separate service. It is new, so check the Compose file reference for the exact syntax before you rely on it.
Put the startup of this stack in order.
- Tap the steps below in the right order.
docker compose config: see what Compose sees
Override files, include, profiles, .env interpolation, and extends all combine before anything runs. When the stack does something you did not expect, do not stare at the YAML. Ask Compose for the final model:
docker compose config # the fully merged, interpolated modeldocker compose config --services # which services existdocker compose config --profiles # which profiles are defineddocker compose config --environment # the variables used for interpolationdocker compose config -q # validate only; non-zero exit on errorsconfig shows every ${VAR} replaced, every relative path made absolute, and every override applied. It answers "why is the API on two ports?", "which DATABASE_URL won?", and "why did my override not apply?" (often: you ran with -f, so compose.override.yaml was not read). Run docker compose config -q in CI to catch broken files early.
Make missing variables fail loudly too. ${DB_URL} with no value quietly becomes an empty string, and the app starts with a broken connection string. A guard stops Compose before anything runs:
services:
api:
environment:
DATABASE_URL: ${DATABASE_URL:?set DATABASE_URL in .env}
LOG_LEVEL: ${LOG_LEVEL:-info}Match each problem to the tool that solves it.
Dev containers and Testcontainers
Two neighbours of Compose show up at many companies. You do not need to master them now, but you should recognise them.
A dev container is defined by .devcontainer/devcontainer.json. VS Code, JetBrains IDEs, and GitHub Codespaces read it and run your editor's backend inside a container, with the language server, linters, and terminal all on Linux. It can point at your Compose file (dockerComposeFile plus the service to attach to), so the stack and the dev environment are the same thing. Teams use it so a new hire gets a working setup in minutes on any OS.
Testcontainers is a library (Python, Java, Go, Node, .NET) that starts real throwaway containers from your test code: a real Postgres for repository tests, real Kafka for consumer tests, each on a random free port and removed at the end. It replaces "mock the database" and "the shared test database someone broke". Compose runs your app for humans; Testcontainers runs dependencies for tests.
- Compose watch
- The
develop.watchsection: Compose syncs changed files into containers, restarts them, or rebuilds the image based on rules. - compose.override.yaml
- A file Compose merges over compose.yaml automatically when no
-fis given; the usual home for dev-only settings. - anonymous volume
- A volume with no name or host path, often used to shield a path like
/app/node_modulesfrom a bind mount. It persists until renewed. - !override / !reset
- Compose YAML tags that replace a value outright or remove it, bypassing the normal merge rules.
- service_completed_successfully
- A
depends_oncondition that waits for a one-shot service to exit with code 0. - docker compose config
- Prints the final merged and interpolated model Compose will apply. The first debugging step.
- Testcontainers
- A library that starts real disposable containers, such as Postgres, from inside test code.