TExcelTAD
Home › Docker Swarm › Service Discovery & Load Balancing

Service Discovery & Load Balancing

Tasks come and go: they crash and are replaced, they move when a node is drained, and every replacement gets a new IP address. Applications must never hard-code those addresses. Instead, a container simply connects to a service name like db or api, and Swarm's built-in DNS and load balancer turn the name into a working connection. This lesson looks at exactly what that name resolves to.

The embedded DNS server

Every container attached to a user-defined network uses the Docker engine's embedded DNS server at 127.0.0.11. It answers questions about services and tasks on the networks that container shares with them, and forwards everything else (like github.com) to the node's normal resolvers.

bash
$ docker exec -it $(docker ps -q -f name=shop_api | head -1) cat /etc/resolv.conf
nameserver 127.0.0.11
options ndots:0

(sample output.) Two important rules:

  • A name resolves only if the asking container and the target service share a network. proxy on front cannot resolve db on back, which is a feature: it's the network isolation from the overlay networks lesson.
  • In a stack, a service is really called <stack>_<service> (shop_db), and the stack also registers the short name (db) as an alias on the stack's networks. Inside the stack, use the short name.

VIP mode: one stable address

By default (endpoint_mode: vip) every service gets a virtual IP on each network it joins. The DNS name returns that single VIP, which never changes while the service exists. Connections to the VIP are spread over the healthy tasks by IPVS in the kernel, just like the routing mesh but on the internal network.

text
api task ── "db?" ──► 127.0.0.11 ──► 10.0.2.2 (VIP)
api task ── TCP to 10.0.2.2:5432 ──► IPVS ──► db.1 10.0.2.7  or  db.2 10.0.2.8

There is also a special name, tasks.<service>, that returns the individual task IPs. Clients that do their own balancing or need to reach every replica (a gossip-based cache cluster, a Prometheus scraper) use it.

DNSRR mode: no VIP

With endpoint_mode: dnsrr the service gets no VIP. The service name itself returns the list of task IPs (DNS round robin), rotated between queries. You'd pick it when:

  • a client library wants to see all members (some databases and message brokers);
  • you run your own load balancer (HAProxy, Envoy) that resolves the name and health-checks each backend;
  • you want to avoid IPVS for very long-lived connections.

The price: clients and resolvers cache DNS answers, so a client may keep using a dead task's IP until its cache expires, and dnsrr services can't publish ports through the ingress mesh (use mode: host ports instead).

Let's model both modes:

python · try it yourself
services = {
    "db":    {"mode": "vip",   "vip": "10.0.2.2", "tasks": ["10.0.2.7", "10.0.2.8"]},
    "cache": {"mode": "dnsrr", "vip": None,       "tasks": ["10.0.2.11", "10.0.2.12", "10.0.2.13"]},
}
rotation = {}

def resolve(name):
    if name.startswith("tasks."):
        return sorted(services[name[6:]]["tasks"])
    svc = services.get(name)
    if svc is None:
        return "NXDOMAIN (forwarded to the node's resolver)"
    if svc["mode"] == "vip":
        return [svc["vip"]]
    # dnsrr: every answer lists all tasks, starting one further each time
    k = rotation.get(name, 0)
    rotation[name] = k + 1
    t = svc["tasks"]
    return t[k % len(t):] + t[:k % len(t)]

for q in ["db", "db", "tasks.db", "cache", "cache", "cache", "tasks.cache", "github.com"]:
    print(f"{q:<12} -> {resolve(q)}")
db           -> ['10.0.2.2']
db           -> ['10.0.2.2']
tasks.db     -> ['10.0.2.7', '10.0.2.8']
cache        -> ['10.0.2.11', '10.0.2.12', '10.0.2.13']
cache        -> ['10.0.2.12', '10.0.2.13', '10.0.2.11']
cache        -> ['10.0.2.13', '10.0.2.11', '10.0.2.12']
tasks.cache  -> ['10.0.2.11', '10.0.2.12', '10.0.2.13']
github.com   -> NXDOMAIN (forwarded to the node's resolver)

db always returns the same VIP; the balancing happens later, at connection time. cache returns all tasks with a different one first each time, so naive clients that take the first address spread themselves out.

What the stack file says

compose · try it yourself
# $ docker stack config -c stack.yaml
# --- stack.yaml
services:
  api:
    image: ghcr.io/acme/shop-api:2.4.1
    environment:
      DB_HOST: db
      CACHE_PEERS: tasks.cache
    deploy:
      replicas: 3
  db:
    image: postgres:17
    deploy:
      endpoint_mode: vip
  cache:
    image: ghcr.io/acme/peer-cache:1.0
    ports:
      - "7000:7000"        # ingress mode: will be refused at deploy time
    deploy:
      replicas: 3
      endpoint_mode: dnsrr
version: "3.13"
services:
  api:
    deploy:
      replicas: 3
    environment:
      CACHE_PEERS: tasks.cache
      DB_HOST: db
    image: ghcr.io/acme/shop-api:2.4.1
  cache:
    deploy:
      replicas: 3
      endpoint_mode: dnsrr
    image: ghcr.io/acme/peer-cache:1.0
    ports:
      - mode: ingress
        target: 7000
        published: 7000
        protocol: tcp
  db:
    deploy:
      endpoint_mode: vip
    image: postgres:17

docker stack config happily accepts cache, a dnsrr service with an ingress-mode port, but docker stack deploy would fail when it creates that service: the combination is only rejected by the engine. stack config checks the file's shape, not every rule of the cluster, so try changes on a test swarm first. The fix here is mode: host on the port, or no published port at all.

Connection-level balancing and its surprises

VIP balancing works on TCP connections. HTTP/1.1 keep-alive, HTTP/2 and gRPC open one connection and send many requests over it, so a single busy client can pin all of its traffic on one task while the others idle. This model sends 12 requests from 3 clients, each reusing one connection:

python · try it yourself
from collections import Counter

backends = ["api.1", "api.2", "api.3", "api.4"]
next_backend = 0
conn_of = {}
load = Counter()

def request(client):
    global next_backend
    if client not in conn_of:                      # new TCP connection -> IPVS picks a backend
        conn_of[client] = backends[next_backend % len(backends)]
        next_backend += 1
    load[conn_of[client]] += 1                     # later requests reuse the connection

for client, n in [("checkout", 8), ("search", 3), ("admin", 1)]:
    for _ in range(n):
        request(client)

for b in backends:
    print(f"{b}: {load[b]:>2} requests " + "#" * load[b])
api.1:  8 requests ########
api.2:  3 requests ###
api.3:  1 requests #
api.4:  0 requests

api.4 got nothing and api.1 got two thirds of the work. Fixes: let clients recycle connections periodically, use tasks.<service> with a client-side balancer, or put a layer-7 proxy (Envoy, Traefik, nginx) in between that balances individual requests.

Debugging names

bash
$ docker run --rm --network shop_back nicolaka/netshoot sh -c 'dig +short db; dig +short tasks.db'
10.0.2.2
10.0.2.7
10.0.2.8

(sample output; this needs back to be an attachable network.) If a name doesn't resolve, check that both sides share a network and that the service has running tasks: a service with zero healthy tasks still has a VIP, but tasks.<name> returns nothing.

Note: Kubernetes has the same two flavours: a normal Service has a ClusterIP (like a VIP), and a headless Service (clusterIP: None) returns Pod IPs (like dnsrr). See Kubernetes DNS. Compose on one host uses the same embedded DNS: Compose service discovery.

Learn more: The Routing Mesh · External Load Balancers

Test yourself

With the default endpoint mode, what does a DNS lookup of a service name return?

  1. The IP of every task
  2. One virtual IP (VIP) that is load-balanced across the tasks
  3. The IP of the manager
  4. The IP of the node running the first task

Which name returns the IP addresses of all individual tasks of service cache?

  1. cache.all
  2. tasks.cache
  3. _cache._tcp
  4. cache-0

Why can a few gRPC clients overload one replica even though the service uses a VIP?

  1. gRPC bypasses DNS
  2. VIP balancing is per TCP connection, and gRPC sends many requests over one long-lived connection
  3. VIPs only work with UDP
  4. IPVS always picks the first task