Docker › Swarm

Replicate services and move tasks with Docker Swarm

Deploy two Nginx replicas and see how Docker Swarm replaces tasks, moves them between workers, routes ingress traffic, and rolls back an update.

Replicate services and move tasks with Docker Swarm

Docker Swarm replaced an exited Nginx task on a single node. With two workers in the swarm, draining one moved the task to the other, and the manager still served the page through ingress.

Deploy two replicas on one manager

A service describes the image, replica count, and placement rules. The manager creates tasks from that specification and assigns them to nodes. The assigned node runs the container for each task. A replicated service aims for a fixed number across the swarm. A global service runs one task per eligible node. How Swarm services work

Start with one dedicated Linux host for the manager. The placement exercise later in the post needs two more hosts on the same private lab network. The observations here came from three independent Docker Engine 29.5.2 daemons on a single Docker Desktop Linux VM. Each daemon ran on Linux/arm64 and the containers ran Nginx 1.30.8. The HTTP requests originated inside the private lab network.

A port published in ingress mode listens on every IP address assigned to the node. That differs from publishing a single container only on loopback with -p 127.0.0.1:8080:80. On a host with a public IP, block access from outside the lab network with a private network, a cloud firewall, or rules in the DOCKER-USER chain. Traffic to published ports is diverted before it reaches ufw, so ufw rules alone won’t block it. Ingress routing mesh · Docker and ufw · Docker with iptables

Save the following files as index.html and stack.yml in the same directory on the manager. The stack command uses the legacy Compose v3 file format and ignores build. This stack refers to an Nginx image the nodes can pull from a registry and mounts the HTML using a Swarm config. Every replica gets the page at the same path. Deploy a stack to a swarm · Swarm configs

1
2
3
4
5
6
7
8
9
10
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Hello Docker</title>
</head>
<body>
  <h1>Hello from my Docker image</h1>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
version: "3.8"

services:
  web:
    image: nginx:1.30-alpine
    configs:
      - source: index_html
        target: /usr/share/nginx/html/index.html
    ports:
      - target: 80
        published: 8080
        protocol: tcp
        mode: ingress
    deploy:
      replicas: 2
      restart_policy:
        condition: any
        delay: 3s
      update_config:
        parallelism: 1
        delay: 2s
        order: stop-first
      rollback_config:
        parallelism: 1

configs:
  index_html:
    file: ./index.html

Replace MANAGER_IP with the manager’s private address and run these commands on that host. Repeat docker stack services until the replica count reaches 2/2, then check the NODE column and request the page.

1
2
3
4
5
6
7
MANAGER_IP=192.168.50.10
docker swarm init --advertise-addr "$MANAGER_IP"
docker stack config -c stack.yml
docker stack deploy -c stack.yml hello
docker stack services hello
docker service ps hello_web
curl -fsS "http://${MANAGER_IP}:8080/"

Both tasks ran on the manager in the lab. The HTTP response contained <h1>Hello from my Docker image</h1>. The first number in 2/2 is the running replica count and the second is the desired count. Check the task list to see which nodes are running those replicas.

Change the desired count and replace a task

On the manager, scale the service to three and wait for 3/3 before scaling it back to two. The lab reached 2/2 → 3/3 → 2/2. Scaling changes the running service specification. The stack file still declares two replicas, so redeploying it applies that value. Scale a Swarm service

1
2
3
4
5
docker service scale hello_web=3
docker stack services hello
# Run after the service reaches 3/3
docker service scale hello_web=2
docker stack services hello

With both tasks still running on the manager, list the service’s containers and copy one container ID into CONTAINER_ID. The next command sends QUIT to Nginx at PID 1 for a graceful exit. The end of each container name in docker ps is its task ID. The replacement can take a few seconds to appear, so rerun docker service ps hello_web until that task shows Shutdown and Complete and a new task ID is Running.

1
2
3
4
5
docker ps --filter label=com.docker.swarm.service.name=hello_web
CONTAINER_ID='replace-with-one-container-id'
docker exec "$CONTAINER_ID" kill -QUIT 1
docker service ps hello_web
docker stack services hello

In the lab, task 8zd8bis540r9 exited with code 0. With restart_policy.condition: any, the manager created task eage40x27dqw on the same node. The other task, o4lf48z5c268, kept running. This time the desired count stayed at two throughout.

Trigger a replacement with an HTTP health check

Before adding workers, copy stack.yml to stack-health.yml on the manager. Remove ports from services.web and remove update_config and rollback_config from deploy. Add the two keys below under services.web. Keep the existing replicas and restart_policy.

1
2
3
4
5
6
7
command: ["sh", "-c", "echo ok > /usr/share/nginx/html/healthz && exec /docker-entrypoint.sh nginx -g 'daemon off;'"]
healthcheck:
  test: ["CMD", "wget", "-q", "-T", "2", "-O", "/dev/null", "http://127.0.0.1/healthz"]
  interval: 3s
  timeout: 3s
  retries: 2
  start_period: 5s

From the manager, run docker stack deploy -c stack-health.yml hz. Use docker ps --filter label=com.docker.swarm.service.name=hz_web to check that both containers are healthy. Copy one container ID into HEALTH_CONTAINER_ID.

1
2
3
4
5
6
HEALTH_CONTAINER_ID='replace-with-one-healthy-container-id'
docker service ps hz_web
docker exec "$HEALTH_CONTAINER_ID" rm /usr/share/nginx/html/healthz
docker exec "$HEALTH_CONTAINER_ID" wget -q -T 2 -O /dev/null http://127.0.0.1/healthz
docker exec "$HEALTH_CONTAINER_ID" wget -qO- http://127.0.0.1/
docker service ps hz_web

The docker service ps output at the end of the block may not show a change yet. Rerun docker service ps hz_web until the task for the container you edited shows Shutdown and Complete and a new task is Running. Once the new container shows as healthy in docker ps and docker stack services hz reports 2/2, run docker stack rm hz on the manager.

A separate stack tested an HTTP health check. Each task wrote its own /healthz file at startup. Deleting the file in one container made its probe return HTTP 404 and exit code 1, while a request to / in that same container still returned the page. After the probe failures, Swarm replaced that task. The new task passed its check, the other task kept its ID, and the service returned to 2/2. The old task appeared as complete with an empty error field, so compare task IDs and history when tracing a replacement. How Swarm tasks terminate

The lab observed this replacement with restart_policy.condition: any. The Nginx image’s stop signal is SIGQUIT, so the container exited with code 0 and the old task was recorded as complete. The on-failure condition restarts only containers that exit with a nonzero code, so check this difference if you change the condition. With standalone containers under Compose, a failing HTTP health check doesn’t lead to a restart. restart_policy · Health checks and restarts in Docker Compose

Update one task at a time and roll back

Swarm configs are immutable. Save the page below as index-v2.html alongside the original. The commands create a second config and swap it into the running service. Keep the original config for rollback. The stack sets update_config.parallelism: 1 to update one task at a time and stop-first to stop each old task before starting its replacement. Rotate a Swarm config

1
2
3
4
5
6
7
8
9
10
11
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Hello Docker</title>
</head>
<body>
  <h1>Hello from my Docker image</h1>
  <p>version 2</p>
</body>
</html>

Run the commands on the manager. Right after docker service update reports convergence, the status can still read updating during the 2-second update_config.delay. Repeat the status check until it shows completed and both replicas are running before requesting the page. After rollback, wait for rollback_completed and check the page again.

1
2
3
4
5
6
7
8
9
10
11
12
13
docker config create hello_index_v2 index-v2.html
docker service update \
  --config-rm hello_index_html \
  --config-add source=hello_index_v2,target=/usr/share/nginx/html/index.html \
  --update-parallelism 1 hello_web
docker service ps hello_web
docker service inspect --format '{{.UpdateStatus.State}}' hello_web
curl -fsS "http://${MANAGER_IP}:8080/"

docker service rollback hello_web
docker service ps hello_web
docker service inspect --format '{{.UpdateStatus.State}}' hello_web
curl -fsS "http://${MANAGER_IP}:8080/"

The lab made six requests after the update had converged. All six returned v2. After manual rollback had converged, all six requests returned v1. Those request windows began after the respective transitions finished.

Drain a worker and trace ingress

For this exercise, the lab nodes need TCP 2377, TCP and UDP 7946, and UDP 4789 on the private network. Use the firewall approach described earlier to restrict ports 8080 and 8081 to the lab network as well. On the manager, run docker swarm join-token worker to get the join command. Run the displayed command on each worker and share the token only with the workers you’re enrolling. Back on the manager, check docker node ls for two workers in the Ready and Active states. Ports between Swarm hosts · Swarm networking requirements

Save this file as stack-worker.yml beside index.html on the manager. After deployment, wait for 1/1 in docker stack services wk and check that docker service ps wk_web shows a running task on a worker before sending the request. The node.role == worker constraint keeps this service’s task on a worker. An HTTP request to the manager’s private address on port 8081 still reaches the task because the ingress routing mesh forwards it across the swarm. Swarm ingress routing mesh

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
version: "3.8"

# Same page, but tasks may only run on worker nodes.
services:
  web:
    image: nginx:1.30-alpine
    configs:
      - source: index_html
        target: /usr/share/nginx/html/index.html
    ports:
      - target: 80
        published: 8081
        protocol: tcp
        mode: ingress
    deploy:
      replicas: 1
      placement:
        constraints:
          - node.role == worker
      restart_policy:
        condition: any
        delay: 3s

configs:
  index_html:
    file: ./index.html
1
2
3
4
docker stack deploy -c stack-worker.yml wk
docker stack services wk
docker service ps wk_web
curl -fsS "http://${MANAGER_IP}:8081/"

On the manager, read the NODE column to find the worker currently running the task. Put that name in FIRST_WORKER and the other worker’s name in SECOND_WORKER. After the first drain, wait for 1/1 and a new running task on the second worker before sending the request. After the second drain, wait for Pending before reactivating the workers. Drain a Swarm node

1
2
3
4
5
6
7
8
9
10
11
12
13
14
FIRST_WORKER='replace-with-worker-running-the-task'
SECOND_WORKER='replace-with-other-worker'
docker node update --availability drain "$FIRST_WORKER"
docker stack services wk
docker service ps wk_web
curl -fsS "http://${MANAGER_IP}:8081/"

docker node update --availability drain "$SECOND_WORKER"
docker stack services wk
docker service ps --no-trunc wk_web

docker node update --availability active "$FIRST_WORKER"
docker node update --availability active "$SECOND_WORKER"
docker stack services wk
ChangeObservation
Drain the worker running the taskTask yqnigwtwad4t was replaced by zj056682xnvc on the other worker. The service returned to 1/1 and port 8081 on the manager served the page.
Drain both workersThe service fell to 0/1. The new task stayed Pending because no eligible node could take it.
Set both workers to activeThe service returned to 1/1.

Plan for storage and manager quorum

The default local volume driver manages volumes on each node. A replacement task on another node can mount a volume with the same name without seeing the original data. This example uses a Swarm config to distribute static HTML. A service that writes data needs a storage plan that covers task placement on other nodes. Volumes and bind mounts in Swarm services

Quorum requires a majority of the managers. With three managers, at least two must be able to communicate. If the swarm loses quorum, existing tasks can keep running, but managers can’t change services or schedule replacement tasks. This lab changed worker availability in a controlled way within one VM. Physical host failure and manager quorum loss were outside its scope. Swarm manager administration guide

To clean up, remove the lab stacks from the manager. Skip wk if you skipped the worker exercise. Once the services are gone, remove the separately created v2 config if you ran the update.

1
2
3
4
docker stack rm wk
docker stack rm hello
docker service ls
docker config rm hello_index_v2

To dismantle the dedicated swarm, run docker swarm leave on each lab worker first, then docker swarm leave --force on the lab manager.

This post is licensed under CC BY 4.0 by the author.