# Developing with Docker: hot reload, debugging, tests and CI

See code changes instantly with bind mounts and Compose watch, attach a debugger, run tests in the image CI uses, and build images in CI with a shared cache.

Course: [Docker](https://devops.rajeev.pro/courses/docker), lesson 13. About 35 minutes, intermediate. Source: https://devops.rajeev.pro/courses/docker/13-developer-experience

## What you will learn

- Reload code changes in a running container with a bind mount or Compose watch
- Choose between the sync, sync+restart and rebuild watch actions
- Debug a containerised app with logs, exec, a published debugger port and a throwaway tools container
- Run tests inside a container, so laptop and CI use the same environment
- Build and push images in CI with a cache that survives between runs

## Hot reloading

Before file syncing, a developer rebuilt an image after every one-line change. That slowed the feedback loop and
made simple edits expensive. A bind mount or Compose Watch can deliver changed files to the running container;
the app's own watcher can then reload them. In this lesson, you'll set up hot reload, debug a running service,
run tests with its dependencies, and reuse build caches in CI.

**A bind mount** (lesson 6) shares the folder itself:

```sh
$ docker run --rm -p 127.0.0.1:3000:3000 -v "$PWD/src":/app/src hello-dev npm run dev
```

Mount only the source folder, not the whole project: mounting `.` over `/app` hides the `node_modules` the
image installed for Linux behind your laptop's own.

**Compose watch** syncs only the paths you list, and knows when a rebuild is needed instead. A small Node app:

```yaml
# compose.yaml
services:
  app:
    build: .
    ports:
      - "127.0.0.1:3000:3000"
    develop:
      watch:
        - action: sync
          path: ./src
          target: /app/src
        - action: rebuild
          path: package.json
```

The image runs `node --watch src/server.js`, Node's built-in reloader. Then:

```sh
$ docker compose watch
Watch enabled
$ curl -s localhost:3000
hello v1
$ sed -i 's/hello v1/hello v2, synced/' src/server.js       # or save in your editor
$ curl -s localhost:3000
hello v2, synced
$ docker compose logs app | tail -3
app-1  | listening on 3000
app-1  | Restarting 'src/server.js'
app-1  | listening on 3000
```

> **Figure.** Animated. docker compose watch is running. In the editor, src/server.js changes from hello v1 to hello v2, synced, and is saved. The sync action copies the file into the container at /app/src/server.js without rebuilding. node --watch inside the container prints Restarting src/server.js and listens on 3000 again, and curl localhost:3000 now answers hello v2, synced. A change to package.json would trigger the rebuild action instead.
>
> Code is synced in and reloaded by the app; dependency changes rebuild the image.

| Action         | On change                                   | Use for                                                                      |
| -------------- | ------------------------------------------- | ---------------------------------------------------------------------------- |
| `sync`         | copy the files into the container           | code, when the app reloads itself (`node --watch`, `uvicorn --reload`, Vite) |
| `sync+restart` | copy, then restart the container            | config files, apps with no watcher                                           |
| `rebuild`      | build a new image and replace the container | `package.json`, `requirements.txt`, the Dockerfile                           |

Compiled languages like Go can use `rebuild` on the source folder, or a dev image running a watcher such as
`air`.

## Debugging

Start with the least invasive evidence. Logs show what the app printed, `inspect` exposes Docker's recorded
state, and `exec` lets you check a running container. A one-off `run` can reveal the actual environment without
changing the long-lived service. Use a debugger only when logs and state are not enough. Keep its port bound to
loopback, because anyone who can reach it may execute code in the process. For minimal images without a shell,
attach a temporary tools container rather than adding debugging packages to the production image.

Most problems are found with tools you already know:

```sh
$ docker compose logs -f app                 # what did it print?
$ docker compose exec app sh                 # look around inside
$ docker inspect shop-api-1 --format '{{json .State}}'    # exit code, OOMKilled, health log
$ docker compose run --rm app env            # what configuration does it really get?
```

For a step-through debugger, start the runtime in debug mode, publish the port **on loopback only** and attach
your editor:

```yaml
    command: ["node", "--inspect=0.0.0.0:9229", "src/server.js"]
    ports:
      - "127.0.0.1:9229:9229"
```

`0.0.0.0` inside the container is needed so the published port reaches it; `127.0.0.1` on the host keeps
everyone else out. Python's `debugpy` and Java's JDWP work the same way. For an image with no shell (lesson
7), attach a tools container to its namespaces:
`docker run --rm -it --pid container:api --network container:api alpine:3.22 sh`.

> **A debug port is a remote shell.** Anyone who can reach a debugger port can run code in your process. Publish it on `127.0.0.1` only, and keep debug flags in the development Compose file, never in the production image.

## Tests in containers

Run tests in a consistent container environment so local and CI runs use the same dependencies. This reduces
“works on my laptop” differences, but it does not make every test deterministic: test data, time and external
services still need control. Use a one-off container for unit tests that need no database. Start dependencies
with health checks for integration tests, and remove temporary volumes afterward when the suite owns that data.

```sh
$ docker compose run --rm --no-deps app npm test
# tests 1
# pass 1
# fail 0
```

`run --rm` starts a one-off container from the service's configuration and removes it afterwards; `--no-deps`
skips starting the database when the tests don't need it. For integration tests, let Compose start the
dependencies (`depends_on` with health checks, lesson 9), and run `docker compose down -v` at the end so
every run starts from a clean database.

An integration test checks the app across a real boundary, such as a database connection. A healthy dependency
must be ready before the test begins; a running container is not always ready to accept requests. Use a health
check and wait for the dependency condition rather than adding an arbitrary sleep. Keep test data isolated, and
only remove volumes that belong to that test run. That way a failed test remains repeatable without erasing a
developer's local database.

A multi-stage Dockerfile can include a test stage, so a failing test fails the build:

```dockerfile
FROM build AS test
RUN go test ./...
```

```sh
$ docker build --target test .
```

## Docker in CI

CI runners start empty every time, so without help every build starts from zero. The CI/CD course builds a
full pipeline; the Docker part looks like this in GitHub Actions:

```yaml
      - uses: docker/setup-buildx-action@v3
      - uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}
      - uses: docker/build-push-action@v6
        with:
          push: true
          tags: ghcr.io/${{ github.repository }}:sha-${{ github.sha }}
          cache-from: type=gha
          cache-to: type=gha,mode=max
```

`cache-from` and `cache-to` store BuildKit's layer cache in GitHub's cache service, so the
dependency-install layers from lesson 7 are reused between runs. `mode=max` also caches the build stage's
layers, not just the final image's. Other CI systems use a registry cache (`type=registry,ref=…:buildcache`).
Tag with the commit SHA (lesson 8), scan before pushing (lesson 11), and pin actions to a full commit SHA as
the CI/CD course's security lesson explains.

> **In production.** Keep development settings (watch, bind mounts, debug ports) in `compose.yaml` or a `compose.override.yaml` that production never uses. The image CI builds and tests is the exact image you deploy: never rebuild it for production.

> **Video.** [Building a Docker Image Pipeline Using GitHub Actions](https://www.youtube.com/watch?v=6Roj4l4MdtE) (Docker)

## Mission: A two-second edit loop

Containerise a tiny Node server, set up Compose watch so saving a file reloads it without a rebuild, prove it with curl, then run the test suite in the same image with docker compose run.

- You need: Docker with the Compose plugin
- You'll have: curl showing your edit within seconds, and the tests passing inside the container

```sh
$ mkdir -p src test
$ printf "require('node:http').createServer((q, s) => s.end('hello v1\\\\n')).listen(3000, () => console.log('listening on 3000'));\n" > src/server.js
$ printf '{ "name": "hello", "scripts": { "dev": "node --watch src/server.js", "test": "node --test" } }\n' > package.json
$ printf "require('node:test')('adds', () => require('node:assert').strictEqual(1 + 1, 2));\n" > test/server.test.js
$ printf 'FROM node:22-alpine\nWORKDIR /app\nCOPY package.json ./\nRUN npm install --omit=dev\nCOPY . .\nCMD ["npm", "run", "dev"]\n' > Dockerfile
$ # write compose.yaml from this lesson, then in a second terminal:
$ docker compose watch
$ curl -s localhost:3000
hello v1
$ sed -i 's/hello v1/hello v2/' src/server.js && sleep 2 && curl -s localhost:3000
hello v2
$ docker compose run --rm --no-deps app npm test | grep -E '^# (pass|fail)'
# pass 1
# fail 0
$ docker compose down
```

No rebuild between the two `curl`s: the file was synced and Node restarted itself. Change `package.json` and
watch Compose rebuild instead.

## Try it

- Add a develop.watch section to a Compose file and run `docker compose watch`.
- Edit a source file and time how long the change takes to show up.
- Change package.json and watch Compose rebuild the image instead.
- Run your tests with `docker compose run --rm app npm test`.
- Start Node with `--inspect=0.0.0.0:9229`, publish 9229 on 127.0.0.1 and attach your editor.
- Read the Docker build step of a CI workflow and find where its cache is stored.

## Quiz

1. What does a Compose watch rule with action sync do when you save a file?
   - Rebuilds the image
   - **Copies the changed file into the running container; the app's own watcher reloads it** (answer)
   - Restarts Docker
   - Commits the file
   Why: sync is the fastest loop. Use sync+restart for apps without a watcher, and rebuild for changes such as package.json that need a new image.

2. Why can a bind mount of your whole project break a Node container?
   - Bind mounts are read-only
   - **It hides the image's node_modules, built for Linux, behind your laptop's folder** (answer)
   - Node can't read mounted files
   - It makes the image larger
   Why: Mount only the source folder, or add an anonymous volume for /app/node_modules. Compose watch avoids the problem by syncing only the paths you list.

3. Why run the tests inside a container?
   - It is required by npm
   - **Laptop and CI then use the same OS, runtime version and dependencies, so "works on my machine" disappears** (answer)
   - Tests run faster in containers
   - To hide test failures
   Why: docker compose run --rm app npm test, or a test stage in the Dockerfile (docker build --target test).

4. Why should a debugger port be published as 127.0.0.1:9229:9229?
   - Debuggers need loopback
   - **A debugger can run any code in the process; it must never be reachable from the network** (answer)
   - It is faster
   - 9229 is reserved
   Why: Remote debugging equals remote code execution. Bind it to your own machine only, and never enable it in production images.

5. Every CI run rebuilds the image from scratch. What fixes it?
   - A bigger runner
   - **A build cache stored outside the runner, such as cache-from/cache-to type=gha or a registry cache** (answer)
   - Removing the Dockerfile
   - docker system prune
   Why: CI runners start empty. Exporting BuildKit's cache lets unchanged layers, such as dependency installs, be reused between runs.

## Resources

- [Docker Docs: Compose watch](https://docs.docker.com/compose/how-tos/file-watch/) (Docker Docs)
- [Docker Docs: cache storage backends](https://docs.docker.com/build/cache/backends/) (Docker Docs)
- [Docker Docs: GitHub Actions with Docker](https://docs.docker.com/build/ci/github-actions/) (Docker Docs)
- [Node.js: debugging guide](https://nodejs.org/en/learn/getting-started/debugging) (Node.js)
