From docker run to Swarm Services
On a single Docker host, you might launch a web server like this:
- You must configure external load balancing.
- Health monitoring and restarts are manual.
- Deployment becomes error-prone as the cluster grows.
- Unified load balancing across nodes
- Built-in health monitoring and self-healing
- Declarative desired state and scaling
Creating a Docker Service
A Swarm service represents one or more replicas of the same container. On a manager node, run:| Flag | Description | Example |
|---|---|---|
--name | Assigns a name to the service | web |
--replicas | Number of container replicas to run | 3 |
--publish | Maps a host port to container port | 80:80 |
| Image | Container image (with optional tag) | httpd:alpine |
If you omit
--replicas, Docker defaults to a single replica (1).How Swarm Orchestration Works
When you issuedocker service create, the Swarm manager components collaborate:
- API Server
Accepts the CLI/API request. - Orchestrator
Calculates desired tasks (one per replica). - Allocator
Assigns virtual IPs and ports to each task. - Dispatcher
Sends tasks to available worker nodes. - Worker Node
Launches containers and reports status back to the manager. - Rescheduler
Detects failures and automatically replaces failed tasks.
A task is the Swarm abstraction for running a container and maintaining its desired state.
Managing Services
Use the following commands to inspect and troubleshoot services:| Command | Description |
|---|---|
docker service ls | List all services in the Swarm cluster |
docker service ps <service> | View tasks (containers) for a specific service |
docker service inspect <service> --pretty | Show detailed service configuration in human-readable form |
docker service logs <service> | Retrieve aggregated logs from all service replicas |
docker service scale <service>=<replicas> | Adjust the number of replicas on the fly |
Removing a Service
To tear down a service and its tasks:Links and References
Happy containerizing! See you in the next guide.