How to resolve pod hostnames from other pods? How to resolve pod hostnames from other pods? kubernetes kubernetes

How to resolve pod hostnames from other pods?


Normally, only Services get DNS names, not Pods. So, by default, you can't refer to another Pod directly by a domain name, only by its IP address.

Pods get DNS names only under certain condidtions that include a headless Service, as explained in the documentation. In particular, the conditions are:

  • The Pods have a hostname field
  • The Pods have a subdomain field
  • There is a headless Service (in the same namespace) that selects the Pods
  • The name of the headless Service equals the subdomain field of the Pods

In this case, each Pod gets a fully-qualified domain name of the following form:

my-hostname.my-subdomain.default.svc.cluster.local

Where my-hostname is the hostname field of the Pod and my-subdomain is the subdomain field of the Pod.

Note: the DNS name is created for the "hostname" of the Pod and not the "name" of the Pod.

You can test this with the following setup:

apiVersion: v1kind: Servicemetadata:  name: my-subdomainspec:  selector:    name: my-test  clusterIP: None---apiVersion: v1kind: Podmetadata:  name: my-pod-1  labels:    name: my-testspec:  hostname: my-hostname-1  subdomain: my-subdomain  containers:  - image: weibeld/ubuntu-networking    command: [sleep, "3600"]    name: ubuntu-networking---apiVersion: v1kind: Podmetadata:  name: my-pod-2  labels:    name: my-testspec:  hostname: my-hostname-2  subdomain: my-subdomain  containers:  - image: weibeld/ubuntu-networking    command: [sleep, "3600"]    name: ubuntu-networking

After applying this, you can exec into one of the Pods:

kubectl exec -ti my-pod-1 bash

And you should be able to resolve the fully-qualifed domain names of the two Pods:

host my-hostname-1.my-subdomain.default.svc.cluster.localhost my-hostname-2.my-subdomain.default.svc.cluster.local

Since you're making the requests from the same namespace as the target Pods, you can abbreviate the domain name to:

host my-hostname-1.my-subdomainhost my-hostname-2.my-subdomain