Sub topic 11
Running a command after sync with sync+exec
This chapter covers the sync+exec action in Compose Watch. It copies changed files into a running container and then runs a command inside that same container. It assumes you can already do the following:
- Write a Compose file with
buildandports. - Add a
develop.watchsection with asyncrule. - Read the difference between
sync,rebuildandsync+restartfrom earlier chapters.
The problem it solves
sync copies files and does nothing else. That works when the process inside the container notices changes on its own, as a dev server with hot reload does. Many programs don't. They read a configuration file once, and they may support a reload command that applies new settings without a full restart.
sync+restart handles this by restarting the whole container. A restart is the right tool when the process has to start from scratch. It is wasteful when the program can reload in place:
- Every restart drops open connections.
- Every restart repeats the startup work.
- Every restart may clear in-memory state you wanted to keep.
sync+exec fills the gap. It does two things in order:
- It copies the changed files into the container, as
syncdoes. - It runs a command you choose inside the already running container.
The container is not stopped, so the main process keeps its PID and its state. Only the extra command runs.
The rule syntax
A sync+exec rule has the same path and target fields as a sync rule, plus an exec block that describes the command:
develop:
watch:
- action: sync+exec
path: ./config
target: /app/config
exec:
command: ["app", "reload"]The fields under exec are:
| Field | Meaning |
|---|---|
| `command` | The command to run inside the container. Required. |
| `user` | The user to run it as. Defaults to the container's user. |
| `working_dir` | The directory the command starts in. |
| `environment` | Extra environment variables for the command only. |
| `privileged` | Runs the command with extended privileges when set to `true`. |
These fields mirror the options of docker compose exec. Anything you would pass there to run a one-off command is available here.
The ignore and include filters from the earlier chapter work on sync+exec rules in the same way as on sync rules.
A worked example: reloading nginx
nginx is a good fit because it reloads its configuration when it receives nginx -s reload. The master process stays alive and swaps in new worker processes. You do not need to restart the container.
Create this layout:
project/
├── compose.yaml
├── Dockerfile
└── conf.d/
└── default.confThe Dockerfile builds an image from the official nginx image and bakes in the starting configuration. Watch requires a build section, so this step cannot be skipped even though no application code is compiled.
FROM nginx:alpine
COPY conf.d/ /etc/nginx/conf.d/The configuration returns a fixed text response. That makes a change easy to see with curl:
server {
listen 80;
location / {
default_type text/plain;
return 200 "version one\n";
}
}The Compose file adds the watch rule:
services:
web:
build: .
ports:
- "8080:80"
develop:
watch:
- action: sync+exec
path: ./conf.d
target: /etc/nginx/conf.d
exec:
command: nginx -s reloadStart it with watch enabled:
docker compose up --watchIn a second terminal, check the response:
curl http://localhost:8080You should see version one. Now edit conf.d/default.conf and change the returned text to version two. Save the file and run curl again. The response changes, and the container was never restarted. You can confirm that by checking the container's uptime:
docker compose psThe STATUS column keeps counting up from the original start time. With sync+restart the uptime would reset on every edit.
Why the order matters
The copy happens before the command. That ordering is the reason the action exists. If you ran nginx -s reload by hand while editing, you would have to make sure the file had landed first. Compose Watch does that sequencing for you.
If the copy fails, the command has nothing new to act on. Look at the watch output in your terminal when a reload seems to do nothing. Both the sync and the exec step report there.
Commands are not run through a shell
Compose runs the command directly inside the container. It does not hand it to a shell. A plain string such as nginx -s reload is split into words for you. Shell features are not available, including:
- pipes (
|) &&chaining- redirects (
>) - variable expansion like
$HOME
If you need those, name the shell explicitly with the list form:
exec:
command: ["sh", "-c", "nginx -t && nginx -s reload"]This version tests the new configuration first and reloads only if the test passes. A syntax error in the file then fails the test and leaves the old working configuration in place. That is safer than reloading blindly.
The shell must exist in the image. Minimal images such as distroless ones may not include sh. In that case use a direct command, or choose a different action.
Running as a different user or directory
By default the command runs as the container's configured user, which is often root in development images. You can narrow that down. The example below runs a helper script as the app user from a specific directory, with an extra variable set:
services:
api:
build: .
develop:
watch:
- action: sync+exec
path: ./config
target: /app/config
exec:
command: ["./scripts/reload.sh"]
user: app
working_dir: /app
environment:
- RELOAD_REASON=config-changeThe environment values apply to the exec'd command only. They do not change the environment of the main process.
sync+exec compared with sync+restart
Both actions copy files first. They differ in what happens next.
| Question | sync+restart | sync+exec |
|---|---|---|
| What runs after the copy? | The container is restarted. | Your command runs in the live container. |
| Does the main process restart? | Yes, always. | Only if your command makes it. |
| In-memory state | Lost. | Kept unless the command resets it. |
| Needs program support? | No. Any program restarts. | Yes. The program needs a reload command or signal. |
| Typical use | Config read once at startup. | Reloadable servers, migrations, cache clears. |
Choose sync+restart when the program has no reload mechanism. Choose sync+exec when it has one, or when the follow-up step is a separate task that does not involve the main process at all.
Other uses for the exec step
The command does not have to reload anything. It is a hook that runs after files change. Some examples:
- Run database migrations after a migration file is synced:
["python", "manage.py", "migrate"]. - Regenerate compiled assets or protocol code after a schema file changes.
- Clear an on-disk cache directory the application reads.
- Send a signal such as
kill -HUP 1, usingsh -c, to a process that handles it.
Keep the command quick and safe to repeat. A single save can lead to several runs in a row, and an editor that writes a temp file and renames it may trigger more than one event. Design the command so that running it twice gives the same result as running it once. Migrations and nginx -s reload both meet that standard.
Troubleshooting
When a change reaches the container but the behavior does not change, work through these checks in order:
- Is the file in the container? Run
docker compose exec web cat /etc/nginx/conf.d/default.conf. If the old content shows, the problem is in the sync step. Re-checkpath,targetand anyignorepatterns. - Does the command work by hand? Run it yourself with
docker compose exec web nginx -s reload. If it fails there, it fails in watch too, and the error text is easier to read. - Is the binary on the container's path? The command runs inside the container, not on your host. A tool you installed on your machine is not available unless the image contains it.
- Does the user have permission? A command run as a non-root
usermay be unable to signal a process owned by root. - Is the shell missing? A
["sh", "-c", ...]command fails on images with nosh. - Did the program really support reload? Some programs accept the signal but only reread part of their settings. Check the program's documentation.
Summary
sync+execcopies changed files and then runs a command in the running container.- The
execblock takescommand, and optionallyuser,working_dir,environmentandprivileged. - The command is not run through a shell, so use
["sh", "-c", "..."]for pipes and&&. - It suits programs that can reload in place. Use
sync+restartfor programs that cannot. - Make the command safe to run more than once.
Exercise
A Python service reads settings.toml only at startup and has no reload command. A teammate suggests sync+exec with the command kill 1. Which action would you use for settings.toml instead, and why?
Show answer
Use sync+restart. The program has no way to apply new settings while running, so it must start again, and sync+restart does that after copying the file. Killing PID 1 with sync+exec would stop the container's main process, which depends on the restart policy and is a fragile way to get the same result.
Exercise
You write command: nginx -t && nginx -s reload under exec, and the reload never happens. What is the likely cause, and what is the fix?
Show answer
Compose runs the command directly with no shell, so && is passed as an ordinary argument to nginx -t instead of chaining two commands. Use the list form with a shell: command: ["sh", "-c", "nginx -t && nginx -s reload"]. The image must contain sh.