Docker develop sync+restart action example

Sync+restart is one of the three available action of Docker's hot container replacement feature deciding what to happen with the container. It synchronizes the files with the host and then restarts the container.

If you don't want to restart the container use sync action instead.

Prerequisites

  • Installed Docker Compose version 2.23.0 or greater

If you already have Docker on your machine, please verify it's version:

docker compose version

Otherwise follow the official installation instructions.

Practical example

We have a containerized webserver that serves static content. However, we need to modify the server's configuration file. In that case the server must be restarted after that files get updated is changed.

The project looks like this (and available in GitHub):

.
├── docker-compose.yml
└── nginx
    ├── default.conf
    ├── Dockerfile
    └── www
        ├── favicon.ico
        ├── index.css
        ├── index.html
        └── index.js

Here's the Dockerfile:

FROM nginx:1.27.2-alpine

ADD ./www /etc/nginx/html
COPY ./default.conf /etc/nginx/conf.d/default.conf

First, change docker-compose.yml:

services:
    nginx:
        build: ./nginx
        container_name: nginx
        restart: always
        ports:
        - 80:80
        - 443:443
        develop:
            watch:
            # when the configuration file changes execute the action
            - path: ./nginx/default.conf
              action: sync+restart
              target: /etc/nginx/conf.d/default.conf

Then run docker in develop mode:

docker compose watch

Lastly, modify the default.conf and notice the terminal output:

Syncing "nginx" service after 1 changes were detected
[+] Restarting (1/1)
    Container nginx started

You may also check the effect via your browser by entering the following URL:

http://<ip-of-your-server>

After you are done with developing, stop the process with Ctrl+C and run the following to remove the unused containers:

docker compose down

Thank you for reading! Keep coding!