TExcelTAD
Home › Docker Compose › develop & watch

develop & watch

The traditional way to develop inside containers is a bind mount of the whole source tree. It works, but it has rough edges: slow file access on macOS and Windows, host node_modules or .venv folders leaking into the container, file-ownership trouble on Linux, and changes to dependencies that still need a manual rebuild.

Compose Watch is the alternative. You describe, per service, which host paths matter and what should happen when they change. docker compose watch (or docker compose up --watch) then follows those paths and keeps the containers in step: copying changed files in, restarting, or rebuilding the image.

The develop section

compose · try it yourself
# $ docker compose config --no-path-resolution
services:
  web:
    build: ./web
    ports: ["3000:3000"]
    develop:
      watch:
        - action: sync
          path: ./web/src
          target: /app/src
          ignore:
            - "**/*.test.js"
        - action: rebuild
          path: ./web/package.json
name: demo
services:
  web:
    develop:
      watch:
        - path: ./web/src
          action: sync
          target: /app/src
          ignore:
            - '**/*.test.js'
        - path: ./web/package.json
          action: rebuild
    networks:
      default: null
    build:
      context: ./web
      dockerfile: Dockerfile
    ports:
      - mode: ingress
        target: 3000
        published: "3000"
        protocol: tcp
networks:
  default:
    name: demo_default

Each watch rule has a host path, an action, and, for actions that copy files, a container target. ignore takes patterns like .dockerignore, relative to path. Paths in .dockerignore are ignored automatically too, and so are .git and editor temp files.

The actions

Action On change, Compose… Use for
sync copies the changed files into the running container source code with a dev server that hot-reloads (Vite, nodemon, Flask debug, rails s)
sync+restart copies, then restarts the container config files read only at startup (nginx.conf, settings.py for some apps)
sync+exec copies, then runs a command in the container reload signals: nginx -s reload, kill -HUP 1
restart restarts the container, no copy files the container gets another way (env files)
rebuild builds a new image and recreates the container dependency manifests (package.json, requirements.txt, go.mod), the Dockerfile

A complete example with every action:

compose · try it yourself
# $ docker compose config --no-path-resolution
services:
  web:
    build: ./web
    develop:
      watch:
        - action: sync
          path: ./web/src
          target: /app/src
          initial_sync: true
        - action: sync+exec
          path: ./web/locales
          target: /app/locales
          exec:
            command: ["kill", "-HUP", "1"]
        - action: sync+restart
          path: ./web/nginx.conf
          target: /etc/nginx/conf.d/default.conf
        - action: restart
          path: ./web/.env.local
        - action: rebuild
          path: ./web/package.json
name: demo
services:
  web:
    develop:
      watch:
        - path: ./web/src
          action: sync
          target: /app/src
          initial_sync: true
        - path: ./web/locales
          action: sync+exec
          target: /app/locales
          exec:
            command:
              - kill
              - -HUP
              - "1"
        - path: ./web/nginx.conf
          action: sync+restart
          target: /etc/nginx/conf.d/default.conf
        - path: ./web/.env.local
          action: restart
        - path: ./web/package.json
          action: rebuild
    networks:
      default: null
    build:
      context: ./web
      dockerfile: Dockerfile
networks:
  default:
    name: demo_default

initial_sync: true copies the whole folder once when watch starts, so files changed while watch wasn't running don't go missing.

Compose validates the rules. A sync without a target makes no sense, and is rejected:

compose · try it yourself
services:
  web:
    build: ./web
    develop:
      watch:
        - action: sync
          path: ./web/src
services.web.develop.watch: target is required for non-rebuild actions: invalid compose project

What happens on a change

A model of the dispatch logic: for each changed file, find the matching rule and the action; several files changed at once are batched, and the most expensive action wins (a rebuild makes a sync pointless).

python · try it yourself
import fnmatch, posixpath

rules = [
    {"action": "sync",    "path": "web/src",          "target": "/app/src", "ignore": ["**/*.test.js"]},
    {"action": "sync+restart", "path": "web/nginx.conf", "target": "/etc/nginx/conf.d/default.conf"},
    {"action": "rebuild", "path": "web/package.json"},
]
COST = {"sync": 1, "sync+exec": 2, "restart": 2, "sync+restart": 3, "rebuild": 4}

def match(rule, file):
    """None: rule doesn't cover the file; False: covered but ignored; True: act."""
    if not (file == rule["path"] or file.startswith(rule["path"] + "/")):
        return None
    rel = posixpath.relpath(file, rule["path"])
    return not any(fnmatch.fnmatch(rel, p) or fnmatch.fnmatch(rel, p.replace("**/", ""))
                   for p in rule.get("ignore", []))

def handle(batch):
    actions = []
    for f in batch:
        rule = next((r for r in rules if match(r, f) is not None), None)
        if rule is None:
            print(f"  {f:<28} not watched (no rule)")
            continue
        if not match(rule, f):
            print(f"  {f:<28} skipped (ignore pattern)")
            continue
        dest = posixpath.join(rule["target"], posixpath.relpath(f, rule["path"])) if "target" in rule else ""
        print(f"  {f:<28} {rule['action']:<13} {dest}")
        actions.append(rule["action"])
    if actions:
        print("  =>", max(actions, key=COST.get))

for batch in (["web/src/App.jsx"],
              ["web/src/App.jsx", "web/src/App.test.js", "README.md"],
              ["web/src/api.js", "web/package.json"]):
    print("change:", ", ".join(batch))
    handle(batch)
change: web/src/App.jsx
  web/src/App.jsx              sync          /app/src/App.jsx
  => sync
change: web/src/App.jsx, web/src/App.test.js, README.md
  web/src/App.jsx              sync          /app/src/App.jsx
  web/src/App.test.js          skipped (ignore pattern)
  README.md                    not watched (no rule)
  => sync
change: web/src/api.js, web/package.json
  web/src/api.js               sync          /app/src/api.js
  web/package.json             rebuild
  => rebuild

Running it

bash
$ docker compose up --watch          # start everything and watch, logs in the same terminal
$ docker compose watch               # watch only, quieter output
$ docker compose watch web           # only one service

Sample output after saving two files:

text
[+] Running 3/3
 ✔ Container demo-db-1   Running
 ✔ Container demo-web-1  Started
Watch enabled
Syncing service "web" after 1 changes were detected
Syncing service "web" after 1 changes were detected
Rebuilding service(s) ["web"] after changes were detected...
[+] Building 6.4s (10/10) FINISHED
service(s) ["web"] successfully built

Requirements and gotchas

  • The image needs the tools the action uses. sync+exec runs its command inside the container, so kill or nginx must exist there; minimal (distroless) images often have no shell tools at all.
  • The container user must be able to write target. If the image runs as node (UID 1000) but /app belongs to root, syncing fails. Use COPY --chown=node:node . /app in the Dockerfile.
  • Watch only covers services with a build, because rebuild needs something to build. Services from plain images (Postgres, Redis) run normally and aren't watched.
  • Don't combine watch with a bind mount of the same path. It works, but you get the drawbacks of both.
  • Sync is one-way: host → container. Files the container writes (generated code, lock files) don't come back. Run such commands on the host, or bind-mount just that output folder.

Watch vs bind mounts

Bind mount Watch
File access speed on macOS/Windows slow for big trees native speed (files live in the container)
Host artefacts leaking in (node_modules, .venv) yes, needs workarounds no, only watched paths
Dependency changes manual rebuild automatic rebuild
Container → host changes yes no
Works without a build yes no

Since develop only matters for development, many teams keep it in compose.override.yaml (see Override Files & Merging). Swarm rejects the key (services.<name>: additional property 'develop' is not allowed), which is another reason to keep it out of the base file you deploy.

Learn more: A Development Workflow · Building Images · Bind Mounts & tmpfs

Test yourself

Which watch action fits requirements.txt?

  1. sync
  2. sync+restart
  3. restart
  4. rebuild

What does sync need besides path?

  1. exec
  2. target: the container path to copy to
  3. ignore
  4. initial_sync

Your app writes a generated file into /app/src inside the container. Does it appear on the host with watch?

  1. Yes, sync is two-way
  2. No, watch only syncs host to container
  3. Only with initial_sync
  4. Only with sync+exec