Logging & Monitoring
A swarm hides where things run, which is great until something goes wrong and you need to know which task on which node printed that error, or why a service is short of replicas. This lesson covers the three sources of truth: logs (what the containers say), metrics (numbers over time: CPU, memory, request rates, replica counts) and events (what the swarm did: task started, node down, update paused).
Service logs
docker service logs collects the output of all tasks of a service from whatever nodes they run on, and prefixes every line with the task and node:
$ docker service logs --tail 3 --timestamps shop_api
shop_api.1.k3l9…@worker-1 | 2026-10-18T09:14:02.118Z GET /orders 200 12ms
shop_api.2.x8v2…@worker-2 | 2026-10-18T09:14:02.120Z GET /orders 200 9ms
shop_api.2.x8v2…@worker-2 | 2026-10-18T09:14:02.574Z POST /checkout 500 connection refused (db:5432)(sample output.) Useful flags: --follow, --since 10m, --tail N, --raw (no prefixes), --no-task-ids, --no-trunc. You can also pass a task ID instead of a service name to see one task's logs, including tasks that have already failed, which is often where the interesting error is.
Two things to know: the lines from different nodes are merged as they arrive, so they're not strictly ordered across nodes; and docker service logs only works with logging drivers that keep logs locally (json-file, local, journald). Here's a model of merging per-task logs by timestamp, which is what a central log system does properly:
import heapq
task_logs = {
"api.1@worker-1": [("09:14:02.118", "GET /orders 200"), ("09:14:03.020", "GET /orders 200")],
"api.2@worker-2": [("09:14:02.120", "GET /orders 200"), ("09:14:02.574", "POST /checkout 500 db refused")],
"db.1@worker-3": [("09:14:02.570", "LOG: checkpoint starting"), ("09:14:02.571", "FATAL: too many connections")],
}
streams = [[(ts, task, msg) for ts, msg in lines] for task, lines in task_logs.items()]
for ts, task, msg in heapq.merge(*streams):
print(f"{ts} {task:<15} {msg}")09:14:02.118 api.1@worker-1 GET /orders 200
09:14:02.120 api.2@worker-2 GET /orders 200
09:14:02.570 db.1@worker-3 LOG: checkpoint starting
09:14:02.571 db.1@worker-3 FATAL: too many connections
09:14:02.574 api.2@worker-2 POST /checkout 500 db refused
09:14:03.020 api.1@worker-1 GET /orders 200
Sorted by time, the story is obvious: the database hit its connection limit just before the checkout failed. That's why production swarms ship logs to a central store (Loki, Elasticsearch/OpenSearch, a cloud log service) where you can search across services and time.
Logging drivers per service
The logging: key works in stack files and is applied to every task. Two common setups: keep json-file with rotation (so disks don't fill up) and run a log shipper as a global service that tails the files; or send logs straight to a remote driver (fluentd, gelf, syslog, awslogs). Remote drivers make docker service logs stop working for that service.
# $ docker stack config -c stack.yaml
# --- stack.yaml
x-logging: &default-logging
driver: json-file
options:
max-size: 10m
max-file: "5"
tag: "{{.Name}}"
services:
api:
image: ghcr.io/acme/shop-api:2.4.1
logging: *default-logging
web:
image: ghcr.io/acme/shop-web:3.2.0
logging: *default-logging
audit:
image: ghcr.io/acme/audit:1.1
logging:
driver: gelf
options:
gelf-address: udp://logs.internal:12201version: "3.13"
services:
api:
image: ghcr.io/acme/shop-api:2.4.1
logging:
driver: json-file
options:
max-file: "5"
max-size: 10m
tag: '{{.Name}}'
audit:
image: ghcr.io/acme/audit:1.1
logging:
driver: gelf
options:
gelf-address: udp://logs.internal:12201
web:
image: ghcr.io/acme/shop-web:3.2.0
logging:
driver: json-file
options:
max-file: "5"
max-size: 10m
tag: '{{.Name}}'
x-logging:
driver: json-file
options:
max-file: "5"
max-size: 10m
tag: '{{.Name}}'
The x-logging fragment is copied into each service by the YAML anchor, and the top-level x- key itself is kept in the output (Swarm ignores it). Compose fragments explains anchors in detail.
Metrics: the standard monitoring stack
A widely used open-source setup runs entirely inside the swarm:
| Service | Mode | Job |
|---|---|---|
| node-exporter | global | host metrics (CPU, memory, disk, network) per node |
| cAdvisor | global | per-container CPU, memory, I/O |
| Prometheus | 1 replica, on a manager | scrapes the above, plus the engines' own metrics, and evaluates alert rules |
| Grafana | 1 replica | dashboards |
| Alertmanager | 1 replica | routes alerts to chat/e-mail/pager |
Prometheus has built-in Swarm service discovery (dockerswarm_sd_configs): it asks the Docker API for nodes, services or tasks and scrapes them without a static target list. That's why it runs on a manager with the Docker socket mounted. The Docker engine itself can expose Prometheus metrics too ("metrics-addr": "0.0.0.0:9323" in daemon.json), including swarm-level ones like the number of tasks per state on managers.
# $ docker stack config -c stack.yaml
# --- stack.yaml
services:
node-exporter:
image: prom/node-exporter:v1.9.1
command: ["--path.rootfs=/host"]
volumes:
- /:/host:ro,rslave
deploy:
mode: global
resources:
limits: {memory: 64M}
cadvisor:
image: gcr.io/cadvisor/cadvisor:v0.52.1
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
- /sys:/sys:ro
- /var/lib/docker:/var/lib/docker:ro
deploy:
mode: global
prometheus:
image: prom/prometheus:v3.5.0
user: root
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
- prometheus-data:/prometheus
configs:
- source: prom_conf
target: /etc/prometheus/prometheus.yml
deploy:
placement:
constraints: [node.role == manager]
configs:
prom_conf:
name: prom_conf_${PROM_CONF_REV:-1}
file: ./prometheus.yml
volumes:
prometheus-data:
# --- prometheus.yml
scrape_configs:
- job_name: tasks
dockerswarm_sd_configs:
- host: unix:///var/run/docker.sock
role: tasks
relabel_configs:
- source_labels: [__meta_dockerswarm_task_desired_state]
regex: running
action: keepversion: "3.13"
services:
cadvisor:
deploy:
mode: global
image: gcr.io/cadvisor/cadvisor:v0.52.1
volumes:
- type: bind
source: /var/run/docker.sock
target: /var/run/docker.sock
read_only: true
- type: bind
source: /sys
target: /sys
read_only: true
- type: bind
source: /var/lib/docker
target: /var/lib/docker
read_only: true
node-exporter:
command:
- --path.rootfs=/host
deploy:
mode: global
resources:
limits:
memory: "67108864"
image: prom/node-exporter:v1.9.1
volumes:
- type: bind
source: /
target: /host
read_only: true
bind:
propagation: rslave
prometheus:
configs:
- source: prom_conf
target: /etc/prometheus/prometheus.yml
deploy:
placement:
constraints:
- node.role == manager
image: prom/prometheus:v3.5.0
user: root
volumes:
- type: bind
source: /var/run/docker.sock
target: /var/run/docker.sock
read_only: true
- type: volume
source: prometheus-data
target: /prometheus
volumes:
prometheus-data: {}
configs:
prom_conf:
name: prom_conf_1
file: /home/ada/demo/prometheus.yml
The rslave propagation option on the root-filesystem mount was turned into a bind.propagation field: the long syntax shows what the short one meant.
Alerts that matter for a swarm
The most important swarm-specific alert compares desired and running replicas. A service that is short of tasks for more than a few minutes means the scheduler can't place tasks (resources, constraints, image pulls) or tasks keep crashing:
samples = { # service -> (desired, running) at each 1-minute scrape
"shop_api": [(4, 4), (4, 3), (4, 3), (4, 4), (4, 4), (4, 4)],
"shop_web": [(3, 3), (3, 3), (3, 3), (3, 3), (3, 3), (3, 3)],
"shop_worker":[(2, 2), (2, 1), (2, 1), (2, 1), (2, 1), (2, 1)],
}
FOR_MINUTES = 3 # like "for: 3m" in a Prometheus alert rule
for service, series in samples.items():
short_for, fired = 0, None
for minute, (desired, running) in enumerate(series):
short_for = short_for + 1 if running < desired else 0
if short_for >= FOR_MINUTES and fired is None:
fired = minute
status = f"ALERT at minute {fired}: {series[-1][1]}/{series[-1][0]} running" if fired is not None else "ok"
print(f"{service:<12} {status}")shop_api ok
shop_web ok
shop_worker ALERT at minute 3: 1/2 running
shop_api lost a task for two minutes during a node failure and healed itself: no page at 3 a.m. shop_worker stayed short, which needs a human. The for: duration is how you tell these apart. Other alerts worth having: managers not Reachable, nodes Down, disk space on /var/lib/docker, and certificate expiry for anything you terminate TLS with.
Events
docker events streams what the cluster does. On a manager, swarm-scoped events show service, node, secret and config changes cluster-wide:
$ docker events --filter scope=swarm --filter type=service --since 15m
2026-10-18T09:12:44.100Z service update u2v7x9k1m4pq (name=shop_api, updatestate.new=updating)
2026-10-18T09:13:31.552Z service update u2v7x9k1m4pq (name=shop_api, updatestate.old=updating, updatestate.new=completed)(sample output.) Feed them into your log system for an audit trail of who changed what, and when.
Learn more: Troubleshooting · Healthchecks & Self-Healing · Kubernetes observability · Compose logs & debugging
Test yourself
What does docker service logs shop_api show?
- Only the logs of the task on the current node
- The merged logs of all tasks of the service, from all nodes, prefixed with task and node
- The manager's own logs
- Only error lines
Why do node-exporter and cAdvisor run as global services?
- Global services are cheaper
- They must run exactly once on every node to collect that node's metrics
- Replicated services can't mount volumes
- Prometheus only scrapes global services
Why does an alert on 'running replicas < desired' usually have a for: duration of a few minutes?
- Prometheus requires it
- Short dips during updates or rescheduling heal by themselves; only lasting gaps need a human
- Replica counts are only updated hourly
- To save disk space