Sub topic 4
Preparing the Dockerfile and build section
Compose Watch can only update a service if it knows how to rebuild it. This chapter covers what the Dockerfile and the build section must provide before you add any watch rules. It assumes you can read a Dockerfile, know what a layer is, and have written a Compose file with build, ports, and command. You don't need to know the watch actions yet. Later chapters cover those.
Why the build section is required
Watch has two jobs. It copies changed files into a running container, and it rebuilds the image when a change is too big to copy. The second job needs a build recipe. Compose can only rebuild a service that has a build section, so watch works only on services built from your own source.
A service that only names a pre-built image has nothing for Compose to rebuild, and no source in your project that maps to the container's files.
services:
db:
image: postgres:16 # no build section: watch ignores this service
web:
build: . # watch can manage this serviceIf a service has no build section, Compose skips it for watch. It can still run in the same project, but its files are never synced.
The working model
A watched service has three parts that must agree with each other.
- The image contains your dependencies and a copy of your source, as of the last build.
- The running container starts from that image, and its process reads files at some path.
- The watch rules say how a host path maps onto that container path.
Watch treats the image as the baseline and applies small updates on top. Copied files live in the container's writable layer, not in the image. If you recreate the container, those updates are lost and you get the image's copy of the source again. This is why the image must contain a recent copy of your source. It is also why a rebuild rule exists, as the way to bring the image up to date.
Layout choices that make watch work
The Dockerfile has to satisfy a few conventions. None of them are specific to watch, but watch fails in confusing ways when you skip them.
Install dependencies in their own layer
Docker caches each instruction as a layer and reuses it if its inputs have not changed. If you copy the whole project before installing, any source edit invalidates the install layer. Copy only the dependency manifest first, install, then copy the rest.
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
CMD ["npm", "start"]Here the npm install layer is rebuilt only when package.json or the lock file changes. This matters for the rebuild action. When you change package.json, the rebuild runs the install again, and when you edit only source files, a rebuild reuses the cached install layer and finishes in seconds.
Use a WORKDIR and absolute targets
WORKDIR /app fixes where the application lives inside the container. Every watch target you write later should point under that directory. Use absolute paths such as /app/src so the rule does not depend on how a relative path resolves.
Keep host dependencies out of the build context
The COPY . . line copies everything in the build context into the image. If your host has a node_modules directory, it comes along. It may contain binaries compiled for your host operating system, and it overwrites the modules that npm install just installed for Linux. A .dockerignore file in the build context prevents this.
node_modules
.git
npm-debug.logThe file name is .dockerignore, at the root of the build context. It affects what COPY and the build send to the daemon. It does not affect watch's own ignore list, which is a separate setting covered in a later chapter.
Make the process pick up changes
Watch copies files. It does not make your application re-read them. If the process loads source once at startup, the new file sits in the container and nothing changes. For Node.js, run the app under a file watcher such as nodemon, or use a framework dev server that reloads on its own. Frameworks like React or Vite dev servers have this built in. Compiled languages need a rebuild step instead.
A complete minimal project
This project makes the pieces concrete. Create the following files.
package.json:
{
"name": "watch-demo",
"version": "1.0.0",
"scripts": {
"start": "nodemon src/index.js"
},
"devDependencies": {
"nodemon": "^3.1.0"
}
}src/index.js:
const http = require("http");
const server = http.createServer((req, res) => {
res.end("Hello from the container\n");
});
server.listen(3000, () => console.log("listening on 3000"));compose.yaml:
services:
web:
build: .
ports:
- "3000:3000"The Dockerfile and .dockerignore are the ones shown above. Build and start it:
docker compose up --build -d
curl http://localhost:3000The curl call prints Hello from the container. The service is now built from a build section, the image contains the source and the Linux-installed dependencies, and the process runs under nodemon. This is the baseline. The next chapters add the develop.watch section on top of it.
Build section options that matter
build: . is shorthand. The long form gives you control over the context, the Dockerfile name, and the stage to build.
services:
web:
build:
context: .
dockerfile: Dockerfile
target: dev
ports:
- "3000:3000"| Option | Meaning | Watch-related note |
|---|---|---|
| `context` | Directory sent to the builder | Rebuilds re-send this directory, so keep it small with `.dockerignore` |
| `dockerfile` | Dockerfile path relative to the context | Needed if your file is not named `Dockerfile` |
| `target` | Stage of a multi-stage Dockerfile to build | Lets you build a `dev` stage with dev tools for watch |
If the build context is a subdirectory, such as context: ./web, remember that the COPY paths in the Dockerfile are relative to that context. The watch path values are relative to the project directory where the Compose file lives, not to the build context. Keep the two straight when you write rules.
Container requirements for syncing
To copy files in, Compose needs to run a few small operations inside the container, such as checking and creating directories. Standard base images such as node:20-alpine and Debian-based images have what is needed. Very minimal images, such as ones with no shell or core utilities, may not support sync. The process also needs permission to write to the target directory. If your Dockerfile switches to a non-root USER, make sure that user owns the application directory. Check the Compose documentation for your version for the exact requirements, because they have changed between releases.
FROM node:20-alpine
WORKDIR /app
COPY --chown=node:node package*.json ./
USER node
RUN npm install
COPY --chown=node:node . .
CMD ["npm", "start"]This variant runs as the built-in node user and gives it ownership of the files it needs to write. The WORKDIR is created by root, so on some base images you may also need to create and chown /app before switching users. Test by changing a file and checking the container.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Watch starts but a service is never updated | The service has only `image:` and no `build` section | Add a `build` section |
| Rebuilds take minutes on every change | `COPY . .` comes before `npm install`, so the install layer is never cached | Copy the manifest first, then install, then copy the source |
| App crashes with a native module error | Host `node_modules` was copied into the image | Add `node_modules` to `.dockerignore` |
| File is copied but the app does not change | The process does not reload on file changes | Run under `nodemon` or a dev server |
| Edits vanish after the container is recreated | Synced files were in the container layer, not the image | Add a `rebuild` rule, or run `docker compose up --build` |
| Permission denied while syncing | Non-root `USER` does not own the target directory | Use `--chown` or fix ownership in the Dockerfile |
Exercise
A teammate's Dockerfile has COPY . . followed by RUN npm install. Every time they edit one source file and the image is rebuilt, the install step runs again. Rewrite the three relevant lines so the install layer is reused when only source files change, and say which file changes will still trigger a fresh install.
Show answer
Use COPY package*.json ./, then RUN npm install, then COPY . .. The install layer is now cached on its inputs, which are the copied manifest files. A fresh install runs only when package.json or the lock file changes, because the cache for the COPY package*.json ./ layer is invalidated and every layer after it is rebuilt.
Exercise
Your Compose file defines db with image: postgres:16 and web with build: .. You add watch rules to both. Which service does watch manage, and why?
Show answer
Only web. Watch needs a build section so it can rebuild the image and so the container's files correspond to source in your project. The db service has no build recipe, so it is skipped.
Exercise
The image builds, docker compose up works, and a changed file shows up inside the container, but the browser still shows the old output. Name the most likely cause in this setup and one fix.
Show answer
The application process is not reloading when files change, so it keeps serving the code it loaded at startup. Run the app under a file watcher such as nodemon (for example "start": "nodemon src/index.js") or use a framework dev server with hot reload.