---
title: "Docker Swarm"
description: "Comprehensive Docker Swarm reference guide covering swarm initialization, node management, services, stacks, overlay networking, secrets, configs, rolling updates, and cluster monitoring."
author: "Mohammad Abu Mattar"
canonical: https://mkabumattar.com/cheatsheets/docker-swarm
---

# Docker Swarm

This cheatsheet provides a comprehensive reference for managing Docker Swarm clusters, services, and stacks. It covers essential commands and best practices for scaling, updating, and monitoring your swarm applications.

## Getting Started

Core concepts and prerequisites for Docker Swarm cluster orchestration.

### What is Docker Swarm

Overview of Docker Swarm architecture manager nodes, worker nodes, services, and tasks.

**Keywords:** swarm, orchestration, manager node, worker node, services, tasks, cluster

#### Docker Swarm overview

```bash
# Docker Swarm is Docker's native container orchestration tool.
# Key concepts:
# - Swarm:   A cluster of Docker engines (nodes) managed as one.
# - Node:    A Docker engine participating in the swarm.
#            Manager nodes coordinate scheduling and cluster state.
#            Worker nodes execute tasks dispatched by managers.
# - Service: Defines a desired state (image, replicas, ports).
# - Task:    A running container that is a slot in a service.
# - Stack:   A group of inter-related services sharing networks/volumes.
```

_exec_
```bash
docker info --format '{{.Swarm.LocalNodeState}}'
```

_output_
```text
inactive
```

Docker Swarm turns a group of Docker hosts into a fault-tolerant, self-healing cluster. Manager nodes use the Raft consensus algorithm to maintain cluster state.

- A swarm can have multiple manager nodes for high availability; odd numbers (3, 5, 7) are recommended.
- Worker nodes never take part in Raft consensus.
- Requires Docker Engine 1.12+ (swarm mode is built in).

#### Verify Docker Engine version

```bash
docker version
```

_output_
```text
Client: Docker Engine - Community
 Version: 26.0.0
Server: Docker Engine - Community
 Engine:
  Version: 26.0.0
```

Docker Swarm mode is bundled with Docker Engine no separate installation is needed.

- Swarm mode requires Docker Engine 1.12 or later.
- All nodes in a swarm should run the same or compatible Docker versions.

### Required Ports & Firewall Rules

Network ports that must be open between swarm nodes.

**Keywords:** ports, firewall, networking, 2377, 7946, 4789

#### Open required swarm ports (Linux / UFW)

```bash
# TCP 2377 cluster management communications (manager nodes only)
sudo ufw allow 2377/tcp

# TCP/UDP 7946 node-to-node communication (overlay network control)
sudo ufw allow 7946/tcp
sudo ufw allow 7946/udp

# UDP 4789 overlay network data path (VXLAN)
sudo ufw allow 4789/udp
```

These three ports must be reachable between all swarm nodes for the cluster to function correctly.

- Port 2377 only needs to be open on manager nodes, but opening it on all nodes is common practice.
- 4789 uses UDP: ensure your cloud provider/router allows VXLAN traffic.

## Swarm Initialization

Commands for creating, joining, leaving, and securing a Docker Swarm cluster.

### Initialize a Swarm

Bootstrap the first manager node to create a new swarm.

**Keywords:** swarm init, advertise-addr, manager, bootstrap

#### Initialize swarm on current host

```bash
docker swarm init
```

_output_
```text
Swarm initialized: current node (abc123def456) is now a manager.

To add a worker to this swarm, run the following command:

    docker swarm join --token SWMTKN-1-xxxx... 192.168.1.10:2377

To add a manager to this swarm, run 'docker swarm join-token manager' and follow the instructions.
```

Docker automatically selects the advertise address. Use when the host has a single network interface.

- The join token displayed is the worker token; use `docker swarm join-token manager` for the manager token.

#### Initialize swarm with explicit advertise address

```bash
docker swarm init --advertise-addr 192.168.1.10
```

Specify the IP address that other nodes use to connect to this manager. Required when multiple network interfaces are present.

- `--advertise-addr` can be an IP address or a network interface name (e.g., `eth0`).
- The port defaults to 2377; override with `--advertise-addr 192.168.1.10:2377`.

#### Initialize swarm with autolock enabled

```bash
docker swarm init --autolock
```

_output_
```text
Swarm initialized: current node (xyz789) is now a manager.

To unlock a swarm manager after it restarts, run the `docker swarm unlock`
command and provide the following key:

    SWMKEY-1-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Please remember to store this key in a password manager, since without it
you will not be able to restart the manager.
```

Autolock encrypts the Raft logs and requires a key to unlock managers after they restart, protecting swarm secrets at rest.

- Store the unlock key securely losing it means you cannot restart the manager.
- Enable autolock on an existing swarm with `docker swarm update --autolock=true`.

### Manage Join Tokens

View, rotate, and use join tokens for adding nodes to the swarm.

**Keywords:** join-token, worker token, manager token, rotate

#### Display worker join token

```bash
docker swarm join-token worker
```

_output_
```text
To add a worker to this swarm, run the following command:

    docker swarm join --token SWMTKN-1-xxxx 192.168.1.10:2377
```

Displays the complete `docker swarm join` command needed to add a new worker node.

#### Display manager join token

```bash
docker swarm join-token manager
```

Displays the complete command to add a new manager node.

#### Rotate join token (invalidate existing)

```bash
# Rotate worker token
docker swarm join-token --rotate worker

# Rotate manager token
docker swarm join-token --rotate manager
```

Invalidates the existing token and generates a new one. Use when a token has been exposed or compromised.

- Previously issued tokens become invalid immediately after rotation.
- Running containers and joined nodes are not affected by rotation.

### Join & Leave Swarm

Add nodes to or remove them from a swarm cluster.

**Keywords:** swarm join, swarm leave, worker, manager

#### Join a swarm as a worker node

```bash
docker swarm join \
  --token SWMTKN-1-xxxx \
  192.168.1.10:2377
```

Run on the node you want to add as a worker. Obtain the token from `docker swarm join-token worker` on a manager.

#### Join a swarm as a manager node

```bash
docker swarm join \
  --token SWMTKN-1-yyyy \
  192.168.1.10:2377
```

Run on the node you want to promote to manager. Use the manager token from `docker swarm join-token manager`.

- For fault tolerance use 3, 5, or 7 managers (odd number to keep Raft quorum).

#### Leave the swarm (worker node)

```bash
docker swarm leave
```

Gracefully removes the current node from the swarm.

#### Force-leave the swarm (manager node)

```bash
docker swarm leave --force
```

Forces a manager node to leave, even if it would break quorum. Use with caution in production.

- --force is required on manager nodes; ensure remaining managers still have quorum.

### Unlock & Update Swarm

Unlock an autolocked manager and update swarm-wide settings.

**Keywords:** unlock, autolock, swarm update

#### Unlock a restarted manager node

```bash
docker swarm unlock
```

Prompts for the unlock key to decrypt the Raft store after a manager node restart when autolock is enabled.

#### Enable autolock on an existing swarm

```bash
docker swarm update --autolock=true
```

#### Update certificate rotation interval

```bash
docker swarm update --cert-expiry 720h
```

Sets node certificate expiry to 30 days. Docker auto-renews certificates before they expire.

- Default certificate expiry is 90 days.

## Node Management

Inspect, configure, promote, drain, and remove nodes in the swarm cluster.

### List & Inspect Nodes

View and query node details within the swarm.

**Keywords:** node ls, node inspect, node ps, status

#### List all nodes in the swarm

```bash
docker node ls
```

_output_
```text
ID                            HOSTNAME   STATUS    AVAILABILITY   MANAGER STATUS   ENGINE VERSION
abc123def456 *                node1      Ready     Active         Leader           26.0.0
xyz789ghi012                  node2      Ready     Active                          26.0.0
jkl345mno678                  node3      Ready     Active         Reachable        26.0.0
```

The asterisk (*) marks the current node. MANAGER STATUS shows Leader, Reachable, or blank (worker).

#### Inspect a specific node

```bash
# Inspect by node ID or hostname
docker node inspect node2

# Pretty-formatted output
docker node inspect --pretty node2
```

Shows full node details including IP address, resources, labels, and status.

#### List tasks running on a node

```bash
docker node ps node2
```

_output_
```text
ID             NAME            IMAGE          NODE    DESIRED STATE   CURRENT STATE
abcd1234       web.1           nginx:alpine   node2   Running         Running 2 hours ago
efgh5678       api.3           node:18        node2   Running         Running 1 hour ago
```

Shows all tasks (containers) currently scheduled on the specified node.

#### List tasks on the current node

```bash
docker node ps self
```

Use the alias `self` to refer to the node where the command is run.

### Update Node Settings

Change node availability, labels, and roles.

**Keywords:** node update, availability, drain, active, pause, label-add, label-rm

#### Drain a node (for maintenance)

```bash
docker node update --availability drain node2
```

Tasks are rescheduled on other nodes immediately. The node will no longer receive new tasks.

- Drain before performing maintenance (OS updates, Docker upgrades) to avoid downtime.

#### Pause a node (stop new task scheduling)

```bash
docker node update --availability pause node2
```

Stops new tasks from being scheduled on the node but keeps existing tasks running.

#### Reactivate a node

```bash
docker node update --availability active node2
```

Returns the node to active status so it can receive new tasks.

#### Add a label to a node

```bash
docker node update --label-add region=us-east node2
docker node update --label-add region=us-east --label-add env=prod node2
```

Labels are used by placement constraints in service definitions to control where services are scheduled.

#### Remove a label from a node

```bash
docker node update --label-rm region node2
```

### Promote, Demote & Remove Nodes

Change node roles and remove nodes from the swarm.

**Keywords:** node promote, node demote, node rm, manager, worker

#### Promote a worker to manager

```bash
docker node promote node2
```

Adds manager responsibilities to a worker node. Use to increase fault tolerance.

#### Demote a manager to worker

```bash
docker node demote node3
```

Removes manager responsibilities while keeping the node in the swarm as a worker.

- Ensure enough managers remain for quorum before demoting.

#### Remove a node from the swarm

```bash
# Node must have left the swarm first (status = Down)
docker node rm node2

# Force-remove a node that is still reachable
docker node rm --force node2
```

Permanently removes the node entry from the swarm's node list.

- The node should run `docker swarm leave` before being removed.
- --force removes the node without waiting for it to acknowledge.

## Service Management

Create, inspect, scale, update, rollback, and remove swarm services.

### Create a Service

Define and deploy a new replicated or global service.

**Keywords:** service create, replicas, global, publish, mount, env, constraint

#### Create a basic replicated service

```bash
docker service create \
  --name web \
  --replicas 3 \
  --publish published=80,target=80 \
  nginx:alpine
```

Deploys 3 replicas of `nginx:alpine` and publishes port 80 on every swarm node via the routing mesh.

- The routing mesh routes traffic to any published port on any node to a running replica.

#### Create a global service (one replica per node)

```bash
docker service create \
  --name log-collector \
  --mode global \
  fluent/fluentd:v1.16
```

A global service runs exactly one replica on every active node ideal for monitoring agents and log collectors.

#### Create service with resource limits

```bash
docker service create \
  --name api \
  --replicas 4 \
  --limit-cpu 0.5 \
  --limit-memory 256M \
  --reserve-cpu 0.25 \
  --reserve-memory 128M \
  node:18-alpine
```

Sets both hard resource limits and soft reservations. Swarm uses reservations for scheduling decisions.

#### Create service with placement constraint

```bash
docker service create \
  --name db \
  --replicas 2 \
  --constraint 'node.labels.region==us-east' \
  --constraint 'node.role==worker' \
  postgres:16-alpine
```

Constrains service placement to nodes matching all specified conditions.

- Use `node.labels.<key>==<value>`, `node.role==manager|worker`, `node.hostname==<name>`.

#### Create service with environment variables and volume mount

```bash
docker service create \
  --name app \
  --replicas 2 \
  --env NODE_ENV=production \
  --env PORT=3000 \
  --mount type=volume,source=app-data,target=/data \
  --publish published=3000,target=3000 \
  myapp:latest
```

Passes environment variables and attaches a named volume to every task replica.

#### Create service with rolling update policy

```bash
docker service create \
  --name web \
  --replicas 6 \
  --update-parallelism 2 \
  --update-delay 15s \
  --update-failure-action rollback \
  --update-max-failure-ratio 0.1 \
  nginx:alpine
```

Updates 2 replicas at a time with a 15-second delay between batches. Automatically rolls back if more than 10% of updates fail.

### List & Inspect Services

View running services and their detailed configuration.

**Keywords:** service ls, service inspect, service ps

#### List all services

```bash
docker service ls
```

_output_
```text
ID             NAME      MODE         REPLICAS   IMAGE          PORTS
abc123def456   web       replicated   3/3        nginx:alpine   *:80->80/tcp
xyz789ghi012   api       replicated   4/4        node:18        *:3000->3000/tcp
```

REPLICAS shows `running/desired`. A mismatch indicates scheduling or health issues.

#### Inspect a service (full JSON)

```bash
docker service inspect web
```

#### Inspect a service (human-readable)

```bash
docker service inspect --pretty web
```

_output_
```text
ID:             abc123
Name:           web
Service Mode:   Replicated
 Replicas:      3
UpdateStatus:
 State:         completed
Placement:
UpdateConfig:
 Parallelism:   2
 Delay:         15s
 On failure:    rollback
ContainerSpec:
 Image:         nginx:alpine
Resources:
Endpoint Mode:  vip
Ports:
 PublishedPort = 80
```

Shows service configuration in a readable format without raw JSON.

#### List tasks (containers) for a service

```bash
docker service ps web
```

_output_
```text
ID             NAME    IMAGE        NODE    DESIRED STATE   CURRENT STATE         ERROR
aaa111         web.1   nginx:alpine node1   Running         Running 3 hours ago
bbb222         web.2   nginx:alpine node2   Running         Running 3 hours ago
ccc333         web.3   nginx:alpine node3   Running         Running 3 hours ago
```

Shows each task, which node it runs on, its current state, and any recent errors.

#### List tasks including failed/completed history

```bash
docker service ps --no-trunc web
```

Shows the full task ID and complete error messages without truncation, useful for debugging failed deployments.

### Scale Services

Adjust the number of replicas for one or more services.

**Keywords:** service scale, replicas

#### Scale a single service

```bash
docker service scale web=5
```

Adjusts the desired replica count. Swarm immediately schedules or removes tasks to match.

#### Scale multiple services at once

```bash
docker service scale web=5 api=8 worker=3
```

Scales all listed services in parallel with a single command.

- Scaling down removes replicas; Swarm picks which tasks to stop.
- Cannot scale a global-mode service (it always runs one per active node).

### Update a Service

Change service configuration, image, replicas, or update policy.

**Keywords:** service update, image, rollback, env-add, env-rm, publish-add, publish-rm, constraint-add

#### Update service image (rolling update)

```bash
docker service update --image nginx:1.25-alpine web
```

Performs a rolling update, replacing old replicas with the new image according to the service's update policy.

#### Update replicas count

```bash
docker service update --replicas 6 web
```

#### Add an environment variable

```bash
docker service update --env-add DEBUG=true web
```

#### Remove an environment variable

```bash
docker service update --env-rm DEBUG web
```

#### Add a published port

```bash
docker service update --publish-add published=443,target=443 web
```

#### Remove a published port

```bash
docker service update --publish-rm 80 web
```

#### Update resource limits

```bash
docker service update \
  --limit-cpu 1.0 \
  --limit-memory 512M \
  api
```

#### Modify the update policy

```bash
docker service update \
  --update-parallelism 3 \
  --update-delay 30s \
  --update-failure-action rollback \
  web
```

#### Force re-deploy all tasks (same image)

```bash
docker service update --force web
```

Re-creates all tasks even when no configuration change is detected. Useful to pick up rebuilt images using the same tag.

- --force replaces tasks one at a time, respecting the update policy.

### Rollback a Service

Revert a service to its previous configuration after a failed update.

**Keywords:** service rollback, rollback, revert

#### Rollback a service to previous version

```bash
docker service rollback web
```

Reverts the service to the configuration it had before the most recent `docker service update`.

- Only one level of rollback is stored you cannot roll back further than the previous state.
- Configure automatic rollback with `--update-failure-action rollback` during service creation/update.

### Remove Services

Delete one or more services from the swarm.

**Keywords:** service rm, service remove

#### Remove a single service

```bash
docker service rm web
```

Immediately stops all tasks and removes the service definition.

- This is irreversible. All running containers for the service are stopped.

#### Remove multiple services

```bash
docker service rm web api worker
```

## Stack Management

Deploy and manage multi-service applications defined in Compose files.

### Compose File for Swarm

Docker Compose v3 file structure with Swarm-specific deploy keys.

**Keywords:** compose, deploy, replicas, update_config, restart_policy, placement, resources

#### Minimal Compose v3 stack definition

```yaml
services:
  web:
    image: nginx:alpine
    ports:
      - "80:80"
    deploy:
      replicas: 3
      update_config:
        parallelism: 1
        delay: 10s
        failure_action: rollback
      restart_policy:
        condition: on-failure
        delay: 5s
        max_attempts: 3
    networks:
      - frontend

  api:
    image: node:18-alpine
    environment:
      NODE_ENV: production
    deploy:
      replicas: 2
      resources:
        limits:
          cpus: '0.5'
          memory: 256M
        reservations:
          cpus: '0.25'
          memory: 128M
      placement:
        constraints:
          - node.role == worker
    networks:
      - frontend
      - backend

networks:
  frontend:
    driver: overlay
  backend:
    driver: overlay
    attachable: true
```

Shows the key `deploy` block available only in Swarm mode. The `build` key is ignored in Swarm images must be pre-built.

- `docker-compose up` ignores the `deploy` block; it is only used by `docker stack deploy`.
- Secrets and configs are referenced under `secrets:` / `configs:` at the top-level and service level.

### Deploy a Stack

Deploy or update a multi-service application to the swarm.

**Keywords:** stack deploy, compose, with-registry-auth

#### Deploy a stack from a Compose file

```bash
docker stack deploy -c compose.yml myapp
```

_output_
```text
Creating network myapp_frontend
Creating network myapp_backend
Creating service myapp_web
Creating service myapp_api
```

Creates services, volumes, and networks defined in the Compose file. Re-running the command updates an existing stack.

#### Deploy using a private registry

```bash
docker login registry.example.com
docker stack deploy -c compose.yml --with-registry-auth myapp
```

Passes the local Docker registry credentials to the swarm so worker nodes can pull images from private registries.

- Without `--with-registry-auth`, worker nodes may fail to pull private images.

#### Deploy from multiple Compose files (merge)

```bash
docker stack deploy \
  -c compose.yml \
  -c docker-compose.prod.yml \
  myapp
```

Merges multiple Compose files, with later files overriding earlier ones.

### Manage Stacks

List, inspect, and remove stacks and their resources.

**Keywords:** stack ls, stack ps, stack services, stack rm

#### List all stacks

```bash
docker stack ls
```

_output_
```text
NAME      SERVICES   ORCHESTRATOR
myapp     2          Swarm
monitoring 3         Swarm
```

#### List services in a stack

```bash
docker stack services myapp
```

_output_
```text
ID             NAME        MODE         REPLICAS   IMAGE
abc123         myapp_web   replicated   3/3        nginx:alpine
def456         myapp_api   replicated   2/2        node:18-alpine
```

#### List all tasks in a stack

```bash
docker stack ps myapp
```

_output_
```text
ID             NAME          IMAGE         NODE    DESIRED STATE   CURRENT STATE
aaa111         myapp_web.1   nginx:alpine  node1   Running         Running 1 hour ago
bbb222         myapp_web.2   nginx:alpine  node2   Running         Running 1 hour ago
ccc333         myapp_web.3   nginx:alpine  node3   Running         Running 1 hour ago
ddd444         myapp_api.1   node:18       node2   Running         Running 1 hour ago
eee555         myapp_api.2   node:18       node3   Running         Running 1 hour ago
```

Shows every container for the stack, across all nodes, with its current state.

#### Remove a stack (all services, networks)

```bash
docker stack rm myapp
```

Stops and removes all services and networks created by the stack. Named volumes are not removed.

- Named volumes must be removed manually with `docker volume rm`.

## Networking

Create and manage overlay networks for service-to-service communication.

### Overlay Networks

Multi-host container networks that span the entire swarm cluster.

**Keywords:** overlay, network create, attachable, encrypted, ingress

#### Create an overlay network

```bash
docker network create \
  --driver overlay \
  --attachable \
  my-overlay
```

Creates an overlay network spanning all swarm nodes. The `--attachable` flag allows standalone containers (not just services) to connect.

- Overlay networks are available cluster-wide but only created on nodes running a connected service.

#### Create an encrypted overlay network

```bash
docker network create \
  --driver overlay \
  --opt encrypted \
  my-secure-overlay
```

Encrypts data-plane traffic between nodes using AES-GCM in GCM mode. Adds slight overhead but improves security.

- Control-plane traffic is always encrypted; this flag encrypts data-plane traffic too.

#### List all networks

```bash
docker network ls
```

_output_
```text
NETWORK ID     NAME              DRIVER    SCOPE
abc123         bridge            bridge    local
def456         docker_gwbridge   bridge    local
ghi789         host              host      local
jkl012         ingress           overlay   swarm
mno345         my-overlay        overlay   swarm
```

#### Inspect a network

```bash
docker network inspect my-overlay
```

Shows connected services, IP addresses, and network configuration.

#### Connect a service to an additional network

```bash
docker service update --network-add my-overlay api
```

#### Disconnect a service from a network

```bash
docker service update --network-rm my-overlay api
```

#### Remove a network

```bash
docker network rm my-overlay
```

- A network cannot be removed while services or containers are still connected to it.

**Best practices:**

- Use separate overlay networks per application tier (frontend/backend) to limit exposure.
- Enable encryption on networks carrying sensitive data.

## Secrets & Configs

Securely manage sensitive data and configuration files distributed to services.

### Secrets Management

Store and distribute sensitive data (passwords, API keys, certificates) to swarm services.

**Keywords:** secret create, secret ls, secret inspect, secret rm, secret file

#### Create a secret from stdin

```bash
printf 'mysecretpassword' | docker secret create db_password -
```

Reads the secret value from stdin (the trailing `-`). Avoids storing secrets in shell history.

- Never use `echo` (adds a newline); use `printf` or read from a file.

#### Create a secret from a file

```bash
docker secret create tls_cert ./certs/server.crt
docker secret create tls_key ./certs/server.key
```

Reads the secret value from the specified file. Useful for certificates, keys, and other binary data.

#### List all secrets

```bash
docker secret ls
```

_output_
```text
ID                          NAME          DRIVER    CREATED         UPDATED
aaaaabbbbcccc               db_password             2 hours ago     2 hours ago
dddddeeeeffff               tls_cert                1 hour ago      1 hour ago
```

- Secret values are never retrievable after creation only their metadata is shown.

#### Inspect a secret

```bash
docker secret inspect db_password
```

Shows secret metadata (ID, name, labels, timestamps) but never the secret value.

#### Grant a service access to a secret

```bash
docker service create \
  --name db \
  --secret db_password \
  --env POSTGRES_PASSWORD_FILE=/run/secrets/db_password \
  postgres:16-alpine
```

The secret is mounted read-only at `/run/secrets/<secret-name>` inside each task container. The app reads the file instead of an env var.

- Mounting as a file is more secure than injecting into an environment variable.

#### Add a secret to an existing service

```bash
docker service update --secret-add db_password api
```

#### Remove a secret from a service

```bash
docker service update --secret-rm db_password api
```

#### Delete a secret

```bash
docker secret rm db_password
```

- A secret can only be removed if no running services are using it.

**Best practices:**

- Always read secrets from `/run/secrets/<name>` (file) rather than environment variables.
- Rotate secrets by creating a new secret and updating the service to use the new name.

**Common errors:**

- **secret 'db_password' could not be found**: Create the secret first with `docker secret create`, then attach it to the service.

### Configs Management

Distribute non-sensitive configuration files to swarm services.

**Keywords:** config create, config ls, config inspect, config rm

#### Create a config from a file

```bash
docker config create nginx_conf ./nginx/nginx.conf
```

Stores the config file content in the swarm's Raft store and distributes it to services.

#### List all configs

```bash
docker config ls
```

#### Inspect a config (view content)

```bash
docker config inspect nginx_conf
# Decode the base64-encoded Data field:
docker config inspect --format '{{printf "%s" .Spec.Data}}' nginx_conf
```

The `Data` field in the inspect output is base64-encoded. Use the format flag to decode it.

#### Use a config in a service

```bash
docker service create \
  --name proxy \
  --config source=nginx_conf,target=/etc/nginx/nginx.conf,mode=0440 \
  --publish published=80,target=80 \
  nginx:alpine
```

Mounts the config as a read-only file at the specified path inside the container.

#### Delete a config

```bash
docker config rm nginx_conf
```

## Monitoring & Logging

Observe service health, view logs, and track cluster events.

### Service Logs

Stream and filter logs from services and individual tasks.

**Keywords:** service logs, follow, tail, timestamps, details

#### View logs for a service

```bash
docker service logs web
```

#### Follow (stream) logs in real time

```bash
docker service logs -f web
```

#### Show last N lines with timestamps

```bash
docker service logs --tail 100 -t web
```

#### View logs from a specific task (replica)

```bash
docker service logs web.1
```

Append the replica number to the service name to scope logs to a single task.

#### Follow logs with full details

```bash
docker service logs -f -t --tail 50 --details web
```

`--details` includes extra attributes set on the log message (e.g., service name, task ID).

### Cluster Events

Monitor real-time events from the swarm cluster.

**Keywords:** system events, filter, service events, node events

#### Watch all Docker events

```bash
docker system events
```

#### Filter events by service type

```bash
docker system events --filter type=service
```

#### Filter events by node type

```bash
docker system events --filter type=node
```

#### Watch events since a timestamp

```bash
docker system events --since "2026-03-07T00:00:00"
```

### Cluster Health & Info

Check overall swarm health and resource usage.

**Keywords:** docker info, system df, system prune

#### Show swarm status and cluster info

```bash
docker info
```

_output_
```text
...
Swarm: active
 NodeID: abc123def456
 Is Manager: true
 ClusterID: xyz789
 Managers: 3
 Nodes: 5
...
```

#### Show disk usage

```bash
docker system df
```

_output_
```text
TYPE            TOTAL     ACTIVE    SIZE      RECLAIMABLE
Images          12        8         2.1GB     450MB (21%)
Containers      25        20        180MB     12MB (6%)
Local Volumes   8         6         3.2GB     850MB (26%)
Build Cache     0         0         0B        0B
```

#### Remove unused resources

```bash
# Remove stopped containers, unused images, volumes, networks
docker system prune -f

# Also remove unused volumes
docker system prune --volumes -f
```

- Run on each node individually `docker system prune` is not a cluster-wide command.

## Rolling Updates & Rollbacks

Perform zero-downtime deployments and recover from failed updates.

### Update Strategy Configuration

Set up update parallelism, delay, failure action, and monitoring window.

**Keywords:** update-parallelism, update-delay, update-failure-action, update-monitor, update-max-failure-ratio, update-order

#### Full update policy example

```bash
docker service update \
  --update-parallelism 2 \
  --update-delay 20s \
  --update-monitor 30s \
  --update-failure-action rollback \
  --update-max-failure-ratio 0.2 \
  --update-order start-first \
  web
```

- parallelism 2: update 2 replicas at a time
- delay 20s: wait 20 seconds between each batch
- monitor 30s: wait 30 seconds after each task update before marking it a success
- failure-action rollback: automatically revert on failure
- max-failure-ratio 0.2: allow up to 20% of tasks to fail before triggering rollback
- order start-first: start the new task before stopping the old one (requires spare capacity)

- `start-first` provides zero-downtime during updates but temporarily increases resource usage.
- `stop-first` (default) stops the old task before starting the new one.

#### Rollback policy configuration

```bash
docker service update \
  --rollback-parallelism 2 \
  --rollback-delay 10s \
  --rollback-failure-action pause \
  --rollback-monitor 20s \
  --rollback-max-failure-ratio 0.1 \
  --rollback-order start-first \
  web
```

Defines how a rollback itself is performed similar parameters to the update config.

### Perform & Monitor Updates

Execute a rolling update and roll back if needed.

**Keywords:** service update, service rollback, service ps, update state

#### Update image with controlled rollout

```bash
docker service update \
  --image nginx:1.25-alpine \
  --update-parallelism 1 \
  --update-delay 15s \
  web
```

#### Monitor update progress

```bash
# Watch tasks being replaced
watch docker service ps web

# Check the update state
docker service inspect --pretty web | grep -A5 UpdateStatus
```

_output_
```text
UpdateStatus:
 State:         updating
 Started:       3 seconds ago
 Message:       update in progress
```

#### Pause an in-progress update

```bash
docker service update --update-pause web
```

Halts the rolling update at the current batch. Useful when you observe issues mid-rollout.

#### Resume a paused update

```bash
docker service update --update-resume web
```

#### Manual rollback

```bash
docker service rollback web
```

Reverts to the previous service spec. Can be issued even if the update has completed.

- Swarm stores only one previous state (PreviousSpec). You cannot chain multiple rollbacks.

**Best practices:**

- Always test updates in staging with the same update policy before applying to production.
- Use `--update-failure-action rollback` to automate recovery from bad deployments.
- Monitor `docker service ps` during updates to catch task failures early.

**Common errors:**

- **Update rolls back automatically and state shows "rollback completed"**: Check `docker service ps --no-trunc <service>` for task error messages, then review image health checks or resource limits.
