Home/Engineer/Docker / Containers/Docker Swarm: Building a Clu…
Docker / ContainersIntermediatelinuxdockerswarmcluster

Docker Swarm: Building a Cluster and Deploying, Scaling, and Rolling Back Services

Build a manager/worker cluster with Docker Swarm and practice service deployment, scaling, rolling updates, overlay networks, and secrets from an operations perspective.

Contents
  1. What is Docker Swarm?
  2. Cluster Setup
  3. Service Deployment and Scaling
  4. Routing Mesh and Publish Mode
  5. Overlay Networks
  6. Rolling Updates and Rollback
  7. Stack — Multi-service Deployments with Compose
  8. Secrets and Configs
  9. Operations Cheat Sheet
  10. Recap

What is Docker Swarm?

Docker Swarm is the container orchestrator built into the Docker Engine. It groups multiple hosts into a single virtual Docker Engine so you can distribute services across them, and it provides scaling, rolling updates, and self-healing with no extra install.

  • Simpler than Kubernetes: You keep using the familiar docker CLI and Compose syntax almost as-is
  • Built-in features: service discovery, load balancing (routing mesh), rolling updates, secrets
  • A good fit for small-to-medium clusters, or when operational simplicity matters

If you need a large-scale or complex ecosystem (autoscaling, custom controllers, a rich ecosystem), Kubernetes is the de facto standard. Choose Swarm knowing its place: the easiest next step from Compose to multi-host.


Cluster Setup

Initialize the manager node

Bash
# (--advertise-addr IP)
docker swarm init --advertise-addr 192.168.1.10
# Swarm initialized. To add a worker ... docker swarm join --token SWMTKN-1-...

Join worker nodes

Bash
# init join run
docker swarm join --token SWMTKN-1-xxxx 192.168.1.10:2377

To look up the join token again:

Bash
docker swarm join-token worker #
docker swarm join-token manager #

List nodes

Bash
docker node ls
# ID          HOSTNAME   STATUS   AVAILABILITY   MANAGER STATUS
# abc * ...   node1      Ready    Active         Leader
# def ...     node2      Ready    Active
RoleResponsibility
ManagerRaft consensus for cluster state, scheduling, API
WorkerRuns assigned tasks (containers) only

For availability, run an odd number of managers (3 or 5). Raft needs a majority, so 3 managers can tolerate 1 failure. Two managers are actually more vulnerable to a single failure.


Service Deployment and Scaling

Swarm’s unit of deployment is not a container but a service. A service runs as multiple replica tasks.

Bash
# nginx 3 , 80 external
docker service create --name web --replicas 3 -p 80:80 nginx:1.27

docker service ls
docker service ps web # check

Scaling

Bash
docker service scale web=5
# or
docker service update --replicas 5 web

Verify self-healing

Even if you kill a container or a node drops out, Swarm maintains the desired replica count.

Bash
docker rm -f <task-container> # quit
docker service ps web #

Routing Mesh and Publish Mode

When you publish a service with -p 80:80, traffic that arrives on port 80 of any node is distributed to replicas through the routing mesh. Packets are forwarded automatically even if no replica is running on that node.

Bash
# ingress: +
docker service create --name web -p 80:80 nginx

# host:
docker service create --name web \
  --publish published=80,target=80,mode=host nginx

Overlay Networks

Service-to-service communication across hosts goes over overlay networks. Services on the same network can reach each other by service name via DNS.

Bash
docker network create --driver overlay --attachable appnet

docker service create --name api --network appnet myapi:1.0
docker service create --name web --network appnet -p 80:80 myweb:1.0
# web 'http://api:8080' ( VIP )

Rolling Updates and Rollback

Bash
docker service create --name web --replicas 4 \
 --update-parallelism 1 \ # 1
 --update-delay 10s \ # 10
 --update-failure-action rollback \ # failed when
  nginx:1.26

# replace →
docker service update --image nginx:1.27 web

#
docker service rollback web
OptionMeaning
--update-parallelismNumber of tasks to update at once
--update-delayWait time between batches
--update-failure-actionOn failure: pause / continue / rollback
--update-orderstart-first (new first) / stop-first

Stack — Multi-service Deployments with Compose

A stack packages multiple services into one file for deployment. The deploy: section is Swarm-specific.

YAML
# stack.yml
version: "3.9"
services:
  web:
    image: myweb:1.0
    ports: ["80:80"]
    networks: [appnet]
    deploy:
      replicas: 3
      update_config: { parallelism: 1, delay: 10s }
      restart_policy: { condition: on-failure }
      placement:
 constraints: [node.role == worker] #
  api:
    image: myapi:1.0
    networks: [appnet]
    deploy:
      replicas: 2
      resources:
        limits: { cpus: "0.5", memory: 256M }
networks:
  appnet: { driver: overlay }
Bash
docker stack deploy -c stack.yml myapp
docker stack services myapp
docker stack ps myapp
docker stack rm myapp

Secrets and Configs

Swarm encrypts secrets and configs in the Raft log and mounts them only into running containers at /run/secrets/<name>.

Bash
echo "S3cr3t!23" | docker secret create db_pass -

docker service create --name api \
  --secret db_pass myapi:1.0
# : cat /run/secrets/db_pass

Secrets are exposed as files (tmpfs), not environment variables, which lowers the risk of env-var leakage. In Compose, reference them with a secrets: section and external: true.


Operations Cheat Sheet

Bash
docker service logs -f web #
docker node update --availability drain node2 #
docker node update --availability active node2 #
docker node rm node2 # ( drain )
docker swarm leave #
docker swarm leave --force #
SymptomCheck
Service stuck PendingResource limits or placement constraints not met
Node DownDocker daemon status; firewall on ports 2377/7946/4789
Services cannot talkSame overlay network? DNS (service name) working?

Recap

TopicKey point
Initializationdocker swarm init / join
Manager countOdd number (3 or 5); Raft majority
Deploy unitservice → replica tasks
Load balancingRouting mesh (ingress)
Service communicationOverlay network + service-name DNS
UpdatesRolling (parallelism/delay) + automatic rollback
Multi-servicedocker stack deploy (deploy section)
Secretssecret → file mount at /run/secrets

Swarm is the smoothest path for Compose users moving to multiple hosts. Keep an odd number of managers, connect services with overlay networks, and use rolling updates and secrets—you can run a solid small cluster with nothing extra to install.

#docker#swarm#cluster#orchestration#scaling
Editorial note

AI tools may assist drafting. Check the evidence in each guide for whether commands were run and which environment was used. Confirm the current docs for your version before applying instructions, and email us about errors. email us

Topic-related official docs (auto-linked · not per-claim sources)Docker documentation ↗

Questions & answers

Ask a question about this guide. We'll review and reply.