Docker Swarm is Docker's native cluster orchestration solution. It provides service orchestration integrated with Docker tooling and uses a subset of legacy Compose v3 rather than the full current Compose specification. It suits small teams and single-cluster deployments.
When do you need orchestration?#
单机 Compose Swarm / K8s
───────────── ─────────────
1 台机器 多台机器
可设重启策略 服务任务故障重新调度
固定端口 负载均衡
单机更新 可配置滚动更新(是否无中断需验证)
可手动扩副本 跨节点副本调度(Swarm 无内置 HPA)Getting started with Swarm#
Initialize the cluster
The following is only an example for a planned test cluster. Inter-node management/overlay communication and firewall policies are required, and managers should be planned around quorum requirements. Join tokens are sensitive credentials and must be transferred securely. Replace the documentation addresses with reachable node addresses.
# 初始化 Swarm 管理器节点
docker swarm init
# 输出含 join 命令,用于其他机器加入集群:
# docker swarm join --token <worker-join-token> 192.0.2.10:2377
# 在其他机器上执行 join 命令
docker swarm join --token <worker-join-token> 192.0.2.10:2377
# 查看集群节点
docker node ls
# ID HOSTNAME STATUS AVAILABILITY MANAGER STATUS
# abc123 * node-1 Ready Active Leader
# def456 node-2 Ready Active
# ghi789 node-3 Ready ActiveDeploy a service
# 创建服务(类似 docker run,但跑在集群上)
docker service create \
--name web \
--replicas 3 \
--publish 80:80 \
nginx:alpine
# 查看服务
docker service ls
docker service ps web
# 输出显示 3 个副本分别跑在哪些节点上Stack Deploy: migrate compatible Compose v3 configuration#
Common service fields can be reused, but stack deploy uses legacy Compose v3. Modern features such as develop/watch/profiles and build cannot be migrated directly. Build images ahead of time and publish them to a registry accessible to all nodes.
# stack.yaml(legacy Compose v3 示例,按 CLI 支持验证)
version: "3.8"
services:
web:
image: nginx:alpine
ports:
- "80:80"
deploy:
replicas: 3
update_config:
parallelism: 1
delay: 10s
restart_policy:
condition: on-failure
resources:
limits:
memory: 256M
healthcheck:
test: ["CMD", "wget", "-q", "--spider", "http://localhost/"] # 确认镜像提供 wget
interval: 30s
api:
image: myapi:latest
deploy:
replicas: 2
environment:
NODE_ENV: production# 部署为 Swarm Stack
docker stack deploy -c compose.yaml myapp
# 查看 stack 状态
docker stack ls
docker stack services myapp
docker stack ps myapp
# 更新(镜像变化或 yaml 变化后)
docker stack deploy -c compose.yaml myapp
# 删除
docker stack rm myappKey point: Sharing a file works only for compatible fields. First inspect the output and warnings from docker stack config, then check images, secret/config sources, networks, placement, and volumes. Success with single-host Compose does not prove that cluster deployment behavior is correct.
Swarm vs Compose: feature comparison#
| Feature | Compose (single host) | Swarm (cluster) |
|---|---|---|
deploy.replicas |
Multiple replicas on one host | Multiple replicas across nodes |
deploy.update_config |
Not supported | Rolling update controls |
deploy.placement |
Not supported | Scheduling by node labels |
| Load balancing | Manual | Built-in VIP + DNS RR |
| Failover | Manual | Automatic |
| Secrets | File injection supported; protecting the source is your responsibility | Swarm secrets provide encrypted Raft storage and distribution |
| Configs | Bind mounts | Declarative configuration injection |
Swarm-specific configuration
services:
api:
deploy:
replicas: 3
# 更新策略
update_config:
parallelism: 1 # 每次更新 1 个副本
delay: 10s
failure_action: rollback
# 节点调度
placement:
constraints:
- node.role == worker
- node.labels.zone == eastSwarm networking: Overlay + Ingress#
节点 A (manager) 节点 B (worker) 节点 C (worker)
┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐
│ web 副本 1 │ │ web 副本 2 │ │ web 副本 3 │
│ api 副本 1 │ │ │ │ api 副本 2 │
└──────────────────┘ └──────────────────┘ └──────────────────┘
│ │ │
└──────────────────────────────┼──────────────────────────────┘
│
Overlay Network
(跨节点的虚拟二层网络)Ingress network: Accessing port 80 on any node automatically routes the request to a healthy replica of the web service. The routing mesh provides ingress forwarding; external load balancing, TLS, and healthy-traffic policies may still be needed.
When should you move from Swarm to K8s?#
| Current requirement | Tool |
|---|---|
| 1-5 machines, no dedicated operations staff | Docker Compose (single host) / Swarm |
| Cross-node failover + simple scaling | Swarm |
| Growing scale with ecosystem, scheduling, or governance requirements | Evaluate Kubernetes against your operational capabilities; there is no fixed node-count threshold |
| Automatic scaling (HPA) | Kubernetes |
| Comprehensive RBAC/multitenancy | Kubernetes |
| A team with existing K8s experience | Kubernetes |
| A Service Mesh (such as Istio) | Kubernetes |
Tool selection depends on availability, scheduling, governance, and team capabilities. Swarm builds on Docker service operations, while Kubernetes offers different controllers and an ecosystem of its own. Learning time cannot be guaranteed in a fixed number of minutes or weeks.
Where to learn next#
graph LR
A["Docker 基础 / (run/build/compose)"] --> B["Swarm / (stack deploy)"]
B --> C["Kubernetes / (kubectl/helm)"]
A2["Podman 基础"] --> D["Pod + Quadlet"]
D --> CThe Docker and Podman learning paths eventually converge on K8s. Whichever engine you use to build images and run local tests, production can still remain on a single host or use another orchestrator. Whether to adopt Kubernetes depends on your requirements.
Failure handling and data boundaries#
Swarm scheduling can recreate tasks after a node failure, but a local volume does not automatically replicate its data to another node. Data services need shared storage, replication, or explicit placement and recovery plans. Losing a majority quorum of managers affects scheduling and management. Rolling-update settings such as start-first, health checks, and failure_action do not guarantee reversible database migrations or uninterrupted traffic. Removing a stack stops its services; check the lifecycle of each volume and external secret/config separately.
References & further reading
Adapted from technical notes. Examples use generic names.
Continue along a reading path
Docker: from running containers to application orchestration
- 01Docker basics: images, containers, and the daemon
- 02The Docker command line: images, containers, volumes, and networks
- 03Dockerfiles and image builds
- 04Compose: defining multi-service applications
- 05Docker networking and storage
- 06Docker in production: resources, security, and recovery
- 07Declaring Docker and containers on NixOS
- 08Swarm: from service replicas to cluster orchestration
- 09Docker and Podman: architecture, compatibility, and coexistence