In a single-host deployment, a host failure affects every container on that machine. Docker Swarm groups multiple Docker hosts into a cluster that places containers on nodes and manages service replicas and updates. This guide also explains why cluster management requires a majority of managers to be available.
This article uses a 3 manager + 2 worker learning cluster to demonstrate Swarm’s basic concepts and operations. Use five dedicated lab VMs or hosts; do not initialize a swarm on a Docker host that runs other workloads. Actual production architectures must consider availability zones, network partitions, resources, backups, monitoring, and upgrades; this learning topology cannot be directly applied.
Common commands at a glance#
Run the commands that list nodes, deploy stacks, or manage services on a manager node.
| Command | What it does |
|---|---|
docker swarm init | Initialize the cluster on the first manager |
docker swarm join | Join a new node to the cluster |
docker node ls | List nodes and their status |
docker stack deploy --with-registry-auth -c stack.yaml myapp | Deploy or update myapp |
docker stack services myapp | List services and replica counts in the stack |
docker service ps myapp_flask | Check task and scheduling status for the Flask service |
docker service logs --tail 50 myapp_flask | Read recent Flask service logs from a manager node |
docker service scale myapp_flask=4 | Scale the Flask service to four replicas |
docker service rollback myapp_flask | Roll back the Flask service to its previous configuration |
docker stack rm myapp | Remove the test stack |
First Understand node, service, task, and container#
node: A Docker host in the cluster. Nodes have two roles:
- manager: Maintains cluster state, accepts service definitions, schedules tasks. Managers use the Raft protocol to maintain consistency, requiring a quorum (majority) to perform management operations.
- worker: Executes tasks assigned by managers. Workers don’t participate in management decisions, only run containers.
service: A description of desired state, like “run 3 Flask containers”. Services have two modes:
- replicated: Specify replica count; Swarm schedules that many tasks in the cluster.
- global: One task per node (e.g., monitoring agents).
task: An instance of a service, containing container definition and scheduling information. After a task is assigned to a node, that node starts the corresponding container.
container: The actual container running a task on a node.
flowchart TD
accTitle: Swarm services, tasks, and containers
accDescr: A service defines the desired state. Swarm creates tasks and assigns them to nodes. A node starts the container for each assigned task.
service["Service · 2 desired replicas"] --> first["Task A"]
service --> second["Task B"]
first -->|Assigned to a node| nodeA["Node A · Container A"]
second -->|Assigned to a node| nodeB["Node B · Container B"]Manager Quorum and Learning Topology#
Managers use the Raft protocol to maintain cluster state. Raft requires a quorum (majority) to make decisions:
| Total managers | Tolerated failures | Needed alive (quorum) |
|---|---|---|
| 1 | 0 | 1 |
| 2 | 0 | 2 (losing one loses quorum) |
| 3 | 1 | 2 |
| 4 | 1 | 3 (same as 3, but more wasteful) |
| 5 | 2 | 3 |
A group of 3 or 4 managers can tolerate only 1 failure, so typically use an odd number of managers.
This article uses a 3 manager + 2 worker topology:
- 3 managers:
manager-1,manager-2,manager-3 - 2 workers:
worker-1,worker-2
Note: Managers can also run tasks by default. To prevent managers from running application workload, separate constraints are needed.
The examples create and remove practice resources named web, redis, flask, my-overlay, and myapp. Run them only in a dedicated learning swarm, and check that these names are unused first. If you choose different names, update every later inspection and cleanup command. Never run the cleanup commands against services that already exist in your cluster.
Initialize Cluster and Join Nodes#
In a shell on the first manager, set MANAGER_IP to its IP address reachable by the other nodes, then initialize the swarm. Replace the example address with the real address on the lab network; do not copy the placeholder as-is.
# On manager-1
MANAGER_IP=192.0.2.10
docker swarm init --advertise-addr "$MANAGER_IP"192.0.2.10 is a documentation-only example address, not an address for a real cluster. Replace it with manager-1’s actual IP on the network shared by the nodes, and run later commands in the same shell session.
--advertise-addr specifies the IP other nodes use to connect to this manager. Initialization prints the worker join command. Run docker swarm join-token manager to get the manager join command.
View join tokens:
# worker join token
docker swarm join-token worker
# manager join token
docker swarm join-token managerImportant: Join tokens are credentials for joining the cluster; do not publish them. If leaked, use docker swarm join-token --rotate worker or docker swarm join-token --rotate manager to rotate. After rotation, old tokens are invalid, but already-joined nodes are unaffected.
In a shell on each of manager-2 and manager-3, set MANAGER_IP to the first manager’s actual address and MANAGER_TOKEN to the token printed by docker swarm join-token manager. A token is a credential; do not put it in an article, script, or commit. Enter it in each node’s shell and join immediately.
# On manager-2 and manager-3
MANAGER_IP=192.0.2.10
MANAGER_TOKEN='paste the manager token here'
docker swarm join --token "$MANAGER_TOKEN" "$MANAGER_IP:2377"In a shell on each of worker-1 and worker-2, set the manager address and the separate WORKER_TOKEN printed by docker swarm join-token worker. Do not put real tokens in the repository or shared logs.
# On worker-1 and worker-2
MANAGER_IP=192.0.2.10
WORKER_TOKEN='paste the worker token here'
docker swarm join --token "$WORKER_TOKEN" "$MANAGER_IP:2377"View nodes:
docker node lsYou should see 5 nodes: 3 managers (one is Leader), 2 workers.
Firewall and ports: Swarm requires these ports open between nodes (only to the trusted cluster network):
- TCP 2377: Cluster management communication
- TCP/UDP 7946: Inter-node communication
- UDP 4789: Overlay network data channel (VXLAN)
Do not expose these ports to the public internet.
Use docker service to Understand Desired State#
Deploy a simple Nginx service:
docker service create --name web --replicas 3 nginx:1.30-alpineView services:
docker service lsView service task distribution:
docker service ps webWait for three tasks to reach Running. Check the NODE column to see their placement. Three replicas can share a node.
Scale to 5 replicas:
docker service scale web=5View docker service ps web again; 2 new tasks appear.
Stop the service:
docker service rm webBuild Image and Prepare Stack File#
Swarm won’t execute build on nodes; images must be built and pushed to a registry beforehand.
Build and push Flask image locally (placeholder example; replace with your registry):
cd flask-redis
docker build -t registry.example.com/yourname/flask-redis:1.0 .
docker login registry.example.com
docker push registry.example.com/yourname/flask-redis:1.0Check that all nodes can reach this registry. Run docker login registry.example.com on the manager issuing the deployment so Docker can pass the credentials for a private image.
stack.yaml: Use the Compose file version 3 format supported by docker stack deploy
version: '3.8'
services:
flask:
image: registry.example.com/yourname/flask-redis:1.0
deploy:
replicas: 2
update_config:
parallelism: 1
delay: 10s
restart_policy:
condition: on-failure
ports:
- "8000:8000"
environment:
REDIS_HOST: redis
REDIS_PORT: 6379
networks:
- app-net
redis:
image: redis:7.4-alpine
deploy:
replicas: 1
placement:
constraints:
- node.role == manager
command: redis-server --save 60 1
networks:
- app-net
networks:
app-net:
driver: overlayThis file is for docker stack deploy, not the local docker compose command used earlier. Although both commands read Compose-style YAML, they do not use exactly the same parser or support the same fields:
docker composeuses the Compose Specification. The current format does not need a top-levelversionfield; if present, it is ignored.docker stack deploystill uses the legacy Compose file version 3 format, so this example keepsversion: '3.8'. Here3.8is the file format version, not the Docker Engine version.
This example uses only fields checked for Stack compatibility. The Compose Deploy Specification also defines deploy, but supported properties can vary between deployment tools.
update_config defines update strategy: update 1 replica at a time, 10-second interval.
placement.constraints restricts Redis to manager nodes (demonstration only; actual deployment should combine with data persistence).
Stack does not use depends_on to guarantee that Redis is ready, and this file does not configure a startup wait for Flask. The Redis counter is stored only in the task container’s writable layer, with no volume; it is not guaranteed to survive task replacement or rescheduling. This is a multi-service connectivity demo, not persistent data storage. See the data persistence guide for named volumes and data lifecycles.
This Stack file maps host port 8000 to container port 8000; the standalone docker service exercise in the previous section uses host port 8001. These are separate exercises, and the standalone flask and redis services should already be removed before deploying the Stack. After deployment, connect to port 8000 on a reachable Swarm node, not the previous exercise’s 8001.
Connect Services Through overlay#
Use the image you just pushed. Replace the example image reference with yours. Run these commands on a manager after signing in to the registry.
Create an overlay network:
docker network create --driver overlay my-overlayOverlay networks span nodes; services connected to this network can access each other by service name.
Deploy Flask and Redis services to this network (assuming images are pushed to a registry accessible by all nodes):
docker service create --name redis --network my-overlay redis:7.4-alpine
docker service ps redis
docker service logs --tail 50 redisWait for the Redis task to reach Running and for its logs to show that it is ready to accept connections before creating Flask. Running only means the container process started; it does not mean Redis is ready. Requests from this Flask example may fail while Redis is unavailable. A long-running application should implement connection retries and recovery.
docker service create --with-registry-auth --name flask --network my-overlay \
--replicas 2 -p 8001:8000 \
-e REDIS_HOST=redis -e REDIS_PORT=6379 \
registry.example.com/yourname/flask-redis:1.0Flask service can access Redis via the redis service name; Swarm automatically handles service discovery and load balancing.
This exercise publishes Flask on port 8001 through the routing mesh. From a trusted client that can reach a cluster node, open http://NODE_IP:8001 after the tasks are running. Replace NODE_IP with the IP of any swarm node. The mapping makes port 8001 reachable through the routing mesh; do not expose it directly to the public internet.
Remove both practice services on a manager before moving to the Stack. Wait until the services are gone before removing the network.
docker service rm flask redis
docker network rm my-overlayDeploy, Update, and Clean Up Stack#
Deploy Stack:
docker stack deploy --with-registry-auth -c stack.yaml myappView Stack services:
docker stack services myappView task distribution:
docker service ps myapp_flask
docker service ps myapp_redisBefore the first Flask request, inspect the Redis service logs and wait for Ready to accept connections. A Redis task showing Running in the Stack does not mean Redis can already process requests; the Flask counter request may fail before Redis is ready.
If a task fails to start, read the Flask service logs from a manager node. This command combines logs from the service’s tasks and works for services using the json-file or journald logging driver.
docker service logs --tail 50 myapp_flaskSee the single-container logging example for how --tail works.
The Stack file publishes 8000:8000, unlike the standalone service exercise above, which uses host port 8001. From a trusted client, replace the example NODE_IP with the address of any reachable node and check the Flask response. The node can be a manager or worker and does not need to be running a Flask task:
NODE_IP=192.0.2.20
curl "http://$NODE_IP:8000"192.0.2.20 is another documentation-only example address; replace it with a real node address.
Scale Flask:
docker service scale myapp_flask=4To keep four replicas, also set deploy.replicas to 4 in stack.yaml. The next deploy uses the file’s declared replica count.
Update image: build new version and push to registry, modify image tag in stack.yaml, redeploy:
docker stack deploy --with-registry-auth -c stack.yaml myappSwarm rolls out updates according to update_config. Check update status:
docker service ps myapp_flaskIf update fails, roll back:
docker service rollback myapp_flaskDelete Stack:
docker stack rm myappThe stack removal also removes its own overlay network. Use docker stack ls to check that myapp is gone.
This removes only the Stack; it does not make nodes leave the swarm. Swarm state remains on each node. When you finish, shut down or delete the VMs if they were dedicated disposable lab machines. If you need to remove nodes that must be kept, follow the official node-removal procedure for managers and workers one at a time. Do not force a node to leave or clean up a cluster that runs other services.
Easily Misunderstood Boundaries#
Deployment scope of Compose and Stack. docker compose up manages containers on one host. docker stack deploy deploys services to a Swarm cluster. depends_on does not guarantee startup order in a stack, so applications need to check whether their dependencies are ready.
Manager quorum doesn’t equal application high availability: Losing quorum means the cluster can’t perform management operations, but already-running tasks may continue. Application high availability also requires considering data, networking, load balancing, and failover.
Local volumes are node-local: volumes created in Stacks are node-local volumes; replicas may be scheduled to other nodes that can’t access them. Distributed storage requires volume plugins or external solutions.
Registry credentials don’t go in YAML: Run docker login on the manager issuing the deployment command and use --with-registry-auth for private images so workers can authenticate. Swarm secrets are for data passed to running services.
latest tag problems: Different nodes may have different versions of latest. Production deployments use explicit version tags or digests.
References#
- Swarm mode overview
- Swarm key concepts
- Getting started with Swarm mode
- Join nodes to a swarm
- docker swarm join-token
- Deploy services to a swarm
- Deploy a stack to a swarm
- Manage swarm service networks
- Administer and maintain a swarm
- docker swarm init
- docker stack deploy
- docker service logs
- docker stack rm
- Compose Deploy Specification