TExcelTAD
Home › Kubernetes › DNS & Service Discovery

DNS & Service Discovery

Every cluster runs a DNS server, usually CoreDNS in kube-system. It watches Services and Pods and answers queries for them. Your code simply connects to http://api or postgres://db:5432, and DNS resolves the name to the right Service IP.

DNS names

Record Name Answer
Service (A/AAAA) <service>.<namespace>.svc.cluster.local The ClusterIP
Headless Service same name One A record per Ready Pod
StatefulSet Pod (via headless Service) <pod>.<service>.<namespace>.svc.cluster.local That Pod's IP
Named port (SRV) _<port-name>._<proto>.<service>.<namespace>.svc.cluster.local Port number + host

cluster.local is the default cluster domain; some clusters configure another one.

Short names and the search path

Each Pod's /etc/resolv.conf is written by the kubelet:

text
search shop.svc.cluster.local svc.cluster.local cluster.local
nameserver 10.96.0.10
options ndots:5

So in namespace shop, the short name api becomes api.shop.svc.cluster.local, and api.payments becomes api.payments.svc.cluster.local. The ndots:5 option says: if a name has fewer than 5 dots, try the search domains first, then the name as typed. A model of the resolver:

python · try it yourself
records = {
    "api.shop.svc.cluster.local.": "10.96.12.4",
    "api.payments.svc.cluster.local.": "10.96.77.30",
    "db.shop.svc.cluster.local.": "10.96.12.9",
    "example.com.": "93.184.215.14",
}
search = ["shop.svc.cluster.local", "svc.cluster.local", "cluster.local"]
NDOTS = 5

def resolve(name):
    tried = []
    if name.endswith("."):
        candidates = [name]
    else:
        expanded = [f"{name}.{domain}." for domain in search]
        candidates = expanded + [name + "."] if name.count(".") < NDOTS else [name + "."] + expanded
    for fqdn in candidates:
        tried.append(fqdn)
        if fqdn in records:
            return records[fqdn], len(tried), fqdn
    return "NXDOMAIN", len(tried), None

for name in ["api", "api.payments", "db.shop.svc.cluster.local", "example.com", "example.com.", "nope"]:
    ip, lookups, fqdn = resolve(name)
    print(f"{name:27} -> {ip:14} after {lookups} lookup(s) {fqdn or ''}")
api                         -> 10.96.12.4     after 1 lookup(s) api.shop.svc.cluster.local.
api.payments                -> 10.96.77.30    after 2 lookup(s) api.payments.svc.cluster.local.
db.shop.svc.cluster.local   -> 10.96.12.9     after 4 lookup(s) db.shop.svc.cluster.local.
example.com                 -> 93.184.215.14  after 4 lookup(s) example.com.
example.com.                -> 93.184.215.14  after 1 lookup(s) example.com.
nope                        -> NXDOMAIN       after 4 lookup(s)

Notice example.com took 4 lookups: three failing search-domain queries before the real one. Even the full name db.shop.svc.cluster.local has only 4 dots, so it was also tried with all three search domains before the name as typed. Busy apps calling external APIs can generate a lot of wasted DNS traffic this way. Fixes: use a trailing dot (example.com.) or lower ndots in the Pod's dnsConfig:

yaml
spec:
  dnsConfig:
    options:
      - name: ndots
        value: "2"

Testing DNS from inside the cluster

bash
kubectl run dnsutils --rm -it --image=registry.k8s.io/e2e-test-images/agnhost:2.39 -- sh
nslookup api
nslookup api.payments.svc.cluster.local
nslookup db-headless        # headless: one address per Pod

Sample output:

text
Server:    10.96.0.10
Address:   10.96.0.10#53

Name:   api.shop.svc.cluster.local
Address: 10.96.12.4

Headless Services and per-Pod names

For a headless Service, DNS returns all Ready Pod IPs, and each StatefulSet Pod gets its own stable name. That is how database replicas find each other:

python · try it yourself
pods = [
    {"name": "pg-0", "ip": "10.244.1.20", "ready": True},
    {"name": "pg-1", "ip": "10.244.2.31", "ready": True},
    {"name": "pg-2", "ip": "10.244.3.12", "ready": False},
]
service, ns, domain = "pg", "data", "cluster.local"

def headless_records():
    zone = {}
    svc_name = f"{service}.{ns}.svc.{domain}"
    zone[svc_name] = [p["ip"] for p in pods if p["ready"]]
    for p in pods:
        if p["ready"]:
            zone[f"{p['name']}.{svc_name}"] = [p["ip"]]
    return zone

for name, ips in headless_records().items():
    print(f"{name:32} A {', '.join(ips)}")
pg.data.svc.cluster.local        A 10.244.1.20, 10.244.2.31
pg-0.pg.data.svc.cluster.local   A 10.244.1.20
pg-1.pg.data.svc.cluster.local   A 10.244.2.31

(A StatefulSet's publishNotReadyAddresses: true on the Service can include not-ready Pods too, which some clustered databases need during bootstrap.)

Environment variables (the old way)

The kubelet also injects variables like API_SERVICE_HOST and API_SERVICE_PORT for every Service that existed when the Pod started. Services created later are invisible this way, which is why DNS is the recommended discovery mechanism.

python · try it yourself
def service_env(services):
    env = {}
    for svc in services:
        prefix = svc["name"].upper().replace("-", "_")
        env[f"{prefix}_SERVICE_HOST"] = svc["ip"]
        env[f"{prefix}_SERVICE_PORT"] = str(svc["port"])
    return env

for k, v in service_env([{"name": "api", "ip": "10.96.12.4", "port": 80},
                         {"name": "redis-cache", "ip": "10.96.12.7", "port": 6379}]).items():
    print(f"{k}={v}")
API_SERVICE_HOST=10.96.12.4
API_SERVICE_PORT=80
REDIS_CACHE_SERVICE_HOST=10.96.12.7
REDIS_CACHE_SERVICE_PORT=6379

Test yourself

From a Pod in namespace shop, which name reaches Service api in namespace payments?

  1. api
  2. api.payments
  3. payments.api
  4. api.shop

What does a DNS query for a headless Service return?

  1. The ClusterIP
  2. The IPs of the Ready Pods
  3. NXDOMAIN
  4. The node IPs

Why does example.com cause extra DNS queries inside a Pod?

  1. CoreDNS is slow
  2. With ndots:5, search domains are tried first because the name has fewer than 5 dots
  3. External names are blocked
  4. DNS caches are disabled