Docker Swarm Introduction
Get started with Docker Swarm for container orchestration.
By EMEPublished: February 20, 2025
docker swarmorchestrationclusteringcontainers
A Simple Analogy
Docker Swarm is like a team of builders. One is the foreman (manager) coordinating work, and others are workers executing tasks.
Why Swarm?
- Orchestration: Manage multiple containers
- Load balancing: Distribute requests
- Fault tolerance: Restart failed containers
- Scaling: Add replicas easily
- Built-in: No external dependencies
Initialization
# Initialize swarm (first manager)
docker swarm init
# Get join token for workers
docker swarm join-token worker
# Add worker node (run on worker machine)
docker swarm join --token SWMTKN-xxx IP:2377
# List nodes
docker node ls
Deploying Services
# Create service
docker service create \
--name web \
--replicas 3 \
-p 80:8080 \
myapp:latest
# List services
docker service ls
# Scale service
docker service scale web=5
# Check service status
docker service ps web
# Update image
docker service update \
--image myapp:v2 \
web
Docker Compose Stack
version: '3.9'
services:
web:
image: myapp:latest
ports:
- "80:8080"
deploy:
replicas: 3
resources:
limits:
cpus: '0.5'
memory: 512M
reservations:
cpus: '0.25'
memory: 256M
restart_policy:
condition: on-failure
delay: 5s
max_attempts: 3
environment:
- DB_HOST=db
db:
image: postgres:15
environment:
POSTGRES_PASSWORD: secure
volumes:
- db_data:/var/lib/postgresql/data
deploy:
replicas: 1
placement:
constraints: [node.role == manager]
volumes:
db_data:
Deploy: docker stack deploy -c docker-compose.yml myapp
Networking
# Create overlay network (cross-node)
docker network create --driver overlay mynet
# Connect service to network
docker service create \
--name web \
--network mynet \
myapp:latest
# Services can communicate by name
# Inside container: curl http://web:8080
Rolling Updates
deploy:
update_config:
parallelism: 1
delay: 10s
failure_action: rollback
rollback_config:
parallelism: 1
delay: 10s
Best Practices
- Pin image versions: Use tags, not latest
- Health checks: Define startup/liveness
- Resource limits: Prevent container sprawl
- Backup: Persist important data
- Monitor: Track service health
Related Concepts
- Kubernetes (more complex)
- Docker Compose (single host)
- Service discovery
- Load balancing
Summary
Docker Swarm simplifies multi-container orchestration. Use services, stacks, and overlay networks for scalable, fault-tolerant deployments.