前言 / Introduction

If you’re tired of rebuilding Docker images every time you change a file — it’s time to watch.

如果你跟我一樣,總是在開發的過程中,深陷 rebuild 的迴圈中,那一定要試試 — Watch

What’s --watch, and Why Should I Care?

In Docker Compose v2.24+, you can now use --watch to:

  • Detect file changes
  • Rebuild or sync files automatically
  • Avoid restarting manually every. single. time.

It’s like having a mini hot-reload system for your containers — perfect for fast iteration.

--watch 就像是一個小服務,無時無刻地監控著你的 container,幫助你快速重建。

What Can It Do?

--watch has two main configuration options: Action and Path. These options let you control how Docker responds to file changes and where to look for them. Let’s break down what each one does.

--watch 就兩個參數 ActionPath ,使用上非常簡單。

Actions Configuration

ActionDescription
rebuildCompletely rebuilds the image and recreates the container when files change
syncPerforms hot loading by copying changed files directly into the running container without rebuilding
buildRebuilds the image only but doesn’t recreate or restart the containers
sync+restartSyncs files to the container and then restarts the container (faster than rebuild)

Path Configuration

ConfigurationDescription
pathSpecifies which directory or files to monitor for changes (source location)
targetDefines where synced files should be placed inside the container (destination location)

Multiple watch configurations can be specified for different paths and actions.

Example Setup: Hot Reload Your App Like a Pro

Here’s how I set up my docker-compose.yml:

services:
  app:
    build: .
    command: python app.py
    watch:
      - path: ./app/src/**/*.py
        action: rebuild
      - path: ./static
        action: sync
        target: /app/static
      - path: ./config/*.json
        action: sync+restart
        target: /app/config

What happens here?

  • Python source code → rebuild container
  • Static assets → sync (no rebuild needed)
  • JSON config → sync + restart

You can start it with:

docker compose up --watch

Or run it in the background:

docker compose up -d --watch

A Few Gotchas (Don’t Skip These)

  • Your image must include: stat, mkdir, rmdir
  • Your container user must have write permission on target dirs
  • Want it clean? Add this to your Dockerfile:
COPY --chown=appuser:appgroup ./app /app
USER appuser

這邊要特別注意,你的 container 在建置的時候,需要有上述這些權限,才能正確使用。

Final Thoughts

I used to hit docker compose down && up more times than I’d like to admit. With --watch, I can focus more on code and less on container wrangling.

If you haven’t tried it yet — give it a go in your next side project. It’s small change, big relief 😌

docker compose down && up 中反覆操中感到厭煩,直到遇上 --watch,總算讓開發的過程變得愉悅許些。

如果你還沒試過,請給他一次機會!


Reference