TExcelTAD
Home › Docker Swarm › External Load Balancers

External Load Balancers

The routing mesh makes every node answer on a published port, but clients still need one address to type into the browser. If your DNS name points at a single node and that node dies, the whole site is down even though the swarm healed itself. The standard answer is an external load balancer (LB): a cloud load balancer, a pair of HAProxy/nginx boxes with a floating IP, or a hardware appliance, that sits in front of the swarm and spreads traffic over several nodes.

Two common layouts

Layout A: LB → all nodes → routing mesh. The LB forwards to the published port on every node (or every worker). The mesh then forwards each connection to a task. Simple and robust: tasks can move freely and the LB config never changes.

text
                 ┌──────────────┐
  clients ──────►│ external LB  │  health check: GET /healthz on :8080 of each node
                 └──┬────┬────┬─┘
                    ▼    ▼    ▼
               node-1 node-2 node-3   (each :8080 → ingress mesh → any web task)

Layout B: LB → edge nodes → proxy in host mode. A reverse proxy (Traefik, Caddy, HAProxy, nginx) runs as a global service on a few nodes labelled edge, publishing 80/443 with mode: host. The LB targets only those nodes. The proxy terminates TLS, sees real client IPs and routes by hostname or path to services over an overlay network.

Layout A Layout B
Hops LB → node → (overlay) → task LB → edge proxy → (overlay) → task
Client IP in the app lost (unless the LB adds X-Forwarded-For or PROXY protocol and the app trusts it) preserved at the proxy
TLS termination at the LB at the LB or the proxy
Routing by host/path at the LB, or in the app in the proxy
Config changes when tasks move none none

Health checks decide everything

An LB is only as good as its health checks. It periodically probes each backend and stops sending traffic to backends that fail several checks in a row, then brings them back after several successes. Two settings matter: the fall count (failures before removal) and the rise count (successes before re-adding). Too eager and one slow response flaps a node in and out; too lazy and users hit a dead node for a long time.

This model runs an LB with interval 5 s, fall 3, rise 2 against three nodes while node-2 crashes and comes back:

python · try it yourself
FALL, RISE, INTERVAL = 3, 2, 5

# probe results per node over time (True = /healthz answered 200)
timeline = {
    "node-1": [True] * 12,
    "node-2": [True, True, False, False, False, False, False, True, True, True, True, True],
    "node-3": [True] * 12,
}
state = {n: {"up": True, "fails": 0, "oks": 0} for n in timeline}

for tick in range(12):
    events = []
    for node, results in timeline.items():
        s, ok = state[node], results[tick]
        if ok:
            s["oks"], s["fails"] = s["oks"] + 1, 0
            if not s["up"] and s["oks"] >= RISE:
                s["up"] = True
                events.append(f"{node} UP")
        else:
            s["fails"], s["oks"] = s["fails"] + 1, 0
            if s["up"] and s["fails"] >= FALL:
                s["up"] = False
                events.append(f"{node} DOWN")
    pool = [n for n in timeline if state[n]["up"]]
    print(f"t={tick * INTERVAL:>3}s pool={pool} {' '.join(events)}")
t=  0s pool=['node-1', 'node-2', 'node-3']
t=  5s pool=['node-1', 'node-2', 'node-3']
t= 10s pool=['node-1', 'node-2', 'node-3']
t= 15s pool=['node-1', 'node-2', 'node-3']
t= 20s pool=['node-1', 'node-3'] node-2 DOWN
t= 25s pool=['node-1', 'node-3']
t= 30s pool=['node-1', 'node-3']
t= 35s pool=['node-1', 'node-3']
t= 40s pool=['node-1', 'node-2', 'node-3'] node-2 UP
t= 45s pool=['node-1', 'node-2', 'node-3']
t= 50s pool=['node-1', 'node-2', 'node-3']
t= 55s pool=['node-1', 'node-2', 'node-3']

node-2 stopped answering at t=10 s but was only removed at t=20 s: between those moments roughly a third of new connections failed. Shorter intervals or a lower fall count shrink that window at the cost of more probe traffic and more flapping.

What should the health check probe?

With layout A, a probe to node-2:8080/healthz goes through the mesh and may be answered by a task on node-1. So the check tells you "the mesh on node-2 works and some task is healthy", not "node-2 has a healthy task". That is exactly what you want for layout A: a node is a good entry point if its mesh can reach the service.

Don't point the LB at a manager-only port or at the Docker API, and don't use a plain TCP check when an HTTP check is possible: a port can accept connections while the app behind it returns 500s.

Draining a node for maintenance

Before you reboot a node, take it out of the LB pool and out of scheduling:

bash
$ docker node update --availability drain node-2      # tasks move to other nodes
$ # remove node-2 from the LB pool, or let its health check fail
$ sudo reboot
$ docker node update --availability active node-2

With layout A, a drained node still runs the routing mesh, so it keeps serving LB traffic until it actually shuts down. Many teams also expose a node-level /healthz (for example a tiny global service in host mode) that they flip to failing a few seconds before maintenance, so the LB stops sending traffic first.

Edge proxy as a stack

Here is layout B as a stack fragment: a global proxy on edge nodes, an app reachable only over the public overlay, and labels that a Swarm-aware proxy such as Traefik reads from the service to build its routes.

compose · try it yourself
# $ docker stack config -c stack.yaml
# --- stack.yaml
services:
  proxy:
    image: traefik:v3.5
    command:
      - --providers.swarm.endpoint=unix:///var/run/docker.sock
      - --providers.swarm.exposedByDefault=false
      - --entrypoints.web.address=:80
      - --ping=true
    ports:
      - target: 80
        published: 80
        mode: host
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro
    networks: [public]
    deploy:
      mode: global
      placement:
        constraints:
          - node.labels.edge == true
          - node.role == manager
  shop:
    image: ghcr.io/acme/shop-web:3.2.0
    networks: [public]
    deploy:
      replicas: 4
      labels:
        traefik.enable: "true"
        traefik.http.routers.shop.rule: Host(`shop.example.com`)
        traefik.http.services.shop.loadbalancer.server.port: "8000"
networks:
  public:
    driver: overlay
version: "3.13"
services:
  proxy:
    command:
      - --providers.swarm.endpoint=unix:///var/run/docker.sock
      - --providers.swarm.exposedByDefault=false
      - --entrypoints.web.address=:80
      - --ping=true
    deploy:
      mode: global
      placement:
        constraints:
          - node.labels.edge == true
          - node.role == manager
    image: traefik:v3.5
    networks:
      public: null
    ports:
      - mode: host
        target: 80
        published: 80
    volumes:
      - type: bind
        source: /var/run/docker.sock
        target: /var/run/docker.sock
        read_only: true
  shop:
    deploy:
      replicas: 4
      labels:
        traefik.enable: "true"
        traefik.http.routers.shop.rule: Host(`shop.example.com`)
        traefik.http.services.shop.loadbalancer.server.port: "8000"
    image: ghcr.io/acme/shop-web:3.2.0
    networks:
      public: null
networks:
  public:
    driver: overlay

Two details: the labels sit under deploy.labels (service labels, which the proxy reads from the Swarm API), not under the service's top-level labels (container labels); and the proxy runs on managers because it reads the Swarm API through the Docker socket, which only managers serve. Giving a container the Docker socket gives it full control of the node and the swarm, so in hardened setups a read-only socket proxy sits in between (see Swarm Security).

Counting capacity

A load balancer also needs enough healthy backends to carry the traffic. A quick capacity check, with every node able to serve 400 requests/s at most:

python · try it yourself
NODE_CAPACITY = 400
peak = 1000

for nodes_up in (4, 3, 2):
    capacity = nodes_up * NODE_CAPACITY
    util = peak / capacity
    verdict = "ok" if util <= 0.7 else "tight" if util <= 1 else "OVERLOADED"
    print(f"{nodes_up} nodes: capacity {capacity:>4} req/s, utilisation {util:5.0%}  {verdict}")
4 nodes: capacity 1600 req/s, utilisation   62%  ok
3 nodes: capacity 1200 req/s, utilisation   83%  tight
2 nodes: capacity  800 req/s, utilisation  125%  OVERLOADED

Plan so that losing one node (or one availability zone) still leaves headroom; the High Availability lesson turns this into a rule.

Note: In Kubernetes the same role is played by a Service of type LoadBalancer or an Ingress / Gateway controller (Ingress, Gateway API).

Learn more: The Routing Mesh · Managing Nodes · High Availability

Test yourself

Why put an external load balancer in front of a swarm when the routing mesh already balances traffic?

  1. The mesh only works on managers
  2. Clients need one address that keeps working when a single node fails
  3. The mesh cannot balance HTTP
  4. Swarm requires it to publish ports

An LB checks every 5 s and removes a backend after 3 consecutive failures. Roughly how long after a node dies does it stop receiving traffic?

  1. Immediately
  2. About 10–15 seconds
  3. About 5 minutes
  4. Never, until an admin removes it

Where do routing labels for a Swarm-aware proxy like Traefik belong in a stack file?

  1. Top-level labels: of the service
  2. deploy.labels
  3. networks.<name>.labels
  4. In the image's Dockerfile only