The Routing Mesh
When you publish a port on a swarm service (-p 8080:80), something surprising happens: every node in the swarm starts listening on port 8080, including nodes that run no replica of the service at all. A request that arrives at any node is forwarded to a healthy task somewhere in the cluster. This is the routing mesh, and it is what lets you point a load balancer or a DNS name at "the cluster" without tracking where tasks currently live.
How a request travels
client
│ http://node-2:8080
▼
┌────────── node-2 (no web task) ─────────┐
│ :8080 ─► ingress-sbox (IPVS) │
└───────────────┬─────────────────────────┘
│ ingress overlay (VXLAN)
┌────────┴─────────┐
▼ ▼
node-1: web.1 node-3: web.2 ◄─ next request goes to the other one- The node's firewall rules (iptables / nftables) catch traffic on the published port and send it into a hidden network namespace called
ingress-sbox, which is attached to the specialingressoverlay network. - Inside it, IPVS (the Linux kernel's layer-4 load balancer) picks one of the service's tasks, round-robin by default.
- The packet travels over the
ingressoverlay to the chosen task, possibly on another node, and the reply comes back the same way.
The balancing is per connection, not per HTTP request: a browser that keeps one keep-alive connection open talks to the same task for its whole lifetime.
Here is a model: three nodes, a service with two replicas, and requests arriving at different nodes.
from itertools import cycle
tasks = {"web.1": "node-1", "web.2": "node-3"} # where the replicas run
nodes = ["node-1", "node-2", "node-3"]
# Every node has its own IPVS table for the service, and every table lists ALL tasks.
ipvs = {n: cycle(sorted(tasks)) for n in nodes}
def connect(entry_node, conn_id):
task = next(ipvs[entry_node])
hop = "local" if tasks[task] == entry_node else f"via overlay to {tasks[task]}"
print(f"conn {conn_id}: client -> {entry_node}:8080 -> {task} ({hop})")
connect("node-2", 1) # node-2 runs no replica, it still answers
connect("node-2", 2)
connect("node-1", 3)
connect("node-1", 4)
connect("node-3", 5)conn 1: client -> node-2:8080 -> web.1 (via overlay to node-1)
conn 2: client -> node-2:8080 -> web.2 (via overlay to node-3)
conn 3: client -> node-1:8080 -> web.1 (local)
conn 4: client -> node-1:8080 -> web.2 (via overlay to node-3)
conn 5: client -> node-3:8080 -> web.1 (via overlay to node-1)
Every connection succeeded, even those that hit node-2. Notice also that node-1 sent its second connection to node-3 although it runs a replica itself: the mesh does not prefer local tasks, so with ingress publishing some traffic always makes an extra hop.
When a task disappears
The managers keep each node's IPVS table in sync with the service's running tasks. When a task fails its healthcheck or its node goes down, it is removed from the tables and new connections go to the survivors; meanwhile the scheduler starts a replacement. Requests that were in flight on the dead task fail, which is why clients (or your external load balancer) should retry idempotent requests.
tasks = {"web.1": "node-1", "web.2": "node-3", "web.3": "node-2"}
healthy = set(tasks)
counters = {}
def pick(entry):
backends = sorted(healthy)
if not backends:
return "connection refused (no healthy task)"
i = counters.get(entry, 0)
counters[entry] = i + 1
return backends[i % len(backends)]
print("all healthy :", [pick("node-1") for _ in range(4)])
healthy.discard("web.2") # node-3 went down
print("web.2 gone :", [pick("node-1") for _ in range(4)])
healthy.add("web.4") # replacement scheduled on node-1
print("web.4 added :", [pick("node-1") for _ in range(3)])
healthy.clear()
print("nothing left:", pick("node-1"))all healthy : ['web.1', 'web.2', 'web.3', 'web.1']
web.2 gone : ['web.1', 'web.3', 'web.1', 'web.3']
web.4 added : ['web.4', 'web.1', 'web.3']
nothing left: connection refused (no healthy task)
Ingress mode vs host mode
A published port has a mode:
mode: ingress (default) |
mode: host |
|
|---|---|---|
| Which nodes listen | every node in the swarm | only nodes running a task of the service |
| Load balancing | IPVS across all tasks | none: the port goes straight to the local task |
| Client source IP seen by the app | the address of the ingress endpoint (the original IP is lost) |
the real client IP |
| Two tasks on one node | fine | port conflict: the second task can't start on that node |
| Typical use | most web services | edge proxies that need client IPs; mode: global services; very high throughput |
Host mode is usually combined with a global service (one task per node, so no port conflicts) or with placement constraints that pick the edge nodes. Let's see how the long port syntax looks after docker stack config normalises it:
# $ docker stack config -c stack.yaml
# --- stack.yaml
services:
web:
image: nginx:1.27-alpine
ports:
- "8080:80"
deploy:
replicas: 3
edge:
image: traefik:v3.5
ports:
- target: 80
published: 80
mode: host
- target: 443
published: 443
protocol: tcp
mode: host
deploy:
mode: global
placement:
constraints: [node.labels.edge == true]
dns:
image: coredns/coredns:1.12.2
ports:
- "53:53/udp"version: "3.13"
services:
dns:
image: coredns/coredns:1.12.2
ports:
- mode: ingress
target: 53
published: 53
protocol: udp
edge:
deploy:
mode: global
placement:
constraints:
- node.labels.edge == true
image: traefik:v3.5
ports:
- mode: host
target: 80
published: 80
- mode: host
target: 443
published: 443
protocol: tcp
web:
deploy:
replicas: 3
image: nginx:1.27-alpine
ports:
- mode: ingress
target: 80
published: 8080
protocol: tcp
The short form "8080:80" became a long-form entry with mode: ingress and protocol: tcp. The routing mesh handles UDP too, as the dns service shows.
Turning the mesh off
You can skip the mesh entirely in two ways:
- Publish with
mode: hostas above. - Publish nothing and let a proxy that lives inside the swarm (Traefik, Caddy, HAProxy, nginx) reach the services over an overlay network by name. Only the proxy publishes ports. This is the most common production layout: one entry point, TLS terminated in one place, path- or host-based routing.
To check what a service publishes:
$ docker service inspect shop_web --format '{{json .Endpoint.Ports}}'
[{"Protocol":"tcp","TargetPort":80,"PublishedPort":8080,"PublishMode":"ingress"}]
$ curl -s -o /dev/null -w '%{http_code}\n' http://node-2:8080/
200(sample output.) If curl to a node hangs while the service is healthy, check that 4789/udp and 7946 are open between the nodes: the mesh needs the ingress overlay to work.
Note: The routing mesh is Swarm's equivalent of a Kubernetes
NodePortService, where every node opens the same port (see Kubernetes Services). In Compose on a single host,ports:simply maps a host port to one container (Compose ports).
Learn more: Service Discovery & Load Balancing · External Load Balancers · Overlay Networks
Test yourself
A service with 2 replicas publishes port 8080 in ingress mode on a 5-node swarm. Which nodes accept connections on 8080?
- Only the 2 nodes running a replica
- Only manager nodes
- All 5 nodes
- Only the leader
Your app logs show the same internal IP for every client. What change lets the app see real client IPs?
- Use
endpoint_mode: dnsrr - Publish the port with
mode: host(or put a proxy in front that sets X-Forwarded-For) - Add more replicas
- Make the network attachable
Why can't two tasks of the same service run on one node when the port is published with mode: host?
- Host mode only supports UDP
- Both tasks would need the same port on the same host
- Host mode requires a global service by law
- The ingress network refuses them