Full lesson
Explore the full explanation, examples, and visuals at your own pace.
API logs after moving to namespace api
postgres worked yesterday. Today the same name says not found. Look at the API's logs: it's still connecting to host postgres on port 5432, but the lookup fails with "Name or service not known." The only thing we changed was the namespace the API runs in.
$ kubectl logs deploy/api -n api
connecting to host=postgres port=5432
error: could not translate host name "postgres"
to address: Name or service not knownSame name, different namespace
A short Service name like postgres resolves only inside the caller's own namespace. A namespace is a named folder of cluster resources, and a Service is a stable name for a set of pods. From the api namespace, postgres fails, but postgres.data reaches the Service in data.
Inside the API pod: /etc/resolv.conf
Every pod gets a small file that tells it how to look up names. The search line lists suffixes that DNS, the cluster's name lookup, appends to a short name, in order. The first suffix is the pod's own namespace, api. That's what matters here.
nameserver 10.96.0.10
search api.svc.cluster.local svc.cluster.local cluster.local
options ndots:5How the lookup plays out
Follow the API pod. It asks cluster DNS for postgres, and DNS tries postgres.api first. No Service owns that name, so you get not found. Now the pod asks for postgres.data. The svc.cluster.local suffix completes it, DNS returns the Service IP, and the pod connects on port 5432.
Fix: deployment env in namespace api
The fix is one line in the API's deployment. In the env block, DATABASE_HOST used to be postgres, and now it's postgres.data. Redeploy, and the same API reaches the same database across namespaces. The Service in data doesn't change at all.
env:
- name: DATABASE_HOST
# was: postgres
value: postgres.dataWhich name to use
Inside the same namespace, plain postgres works. Crossing namespaces, use postgres.data, the shortest name that includes the namespace. The fully qualified form, ending in svc.cluster.local, works too, assuming default cluster DNS settings.
- postgres: same namespace only
- postgres.data: from any namespace
- postgres.data.svc.cluster.local: fully qualified
Short names only work at home.
A bare Service name resolves in the caller's own namespace. When you cross namespaces, add the namespace, like postgres.data. Short names only work at home.
