Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtain Pod DNS Name Programmatically

I have a statefulset with 3 members. They are accessible from inside the cluster with something like:

podname-{0..n}.service.default.svc.cluster.local

I'm using the Kubernetes API from a Controller. I just created the Statefulset with:

import (
    "k8s.io/client-go/kubernetes"
    appsv1 "k8s.io/api/apps/v1"
)
...

s := appsv1.StatefulSet{ /* some data */ }
kubernetes.AppsV1().StatefulSets(nameSpace).Create(s)

Let's assume everything worked correctly, and after a few minutes I have 3 running Pods. How can I get the Pod DNS entries for the newly created Pods?

I know I can build the DNS with:

fmt.Sprintf("%s-%d.%s.%s.svc.cluster.local", s.Name, idx, service, S.Namespace)

But I'm finding some issues:

  1. I will have to calculate the index depending on the amount of replicas
  2. I need to know about the service name used for this StatefulSet
  3. I'm assuming the cluster domain is cluster.local which is not necessarily true

What I think it should exists (but I'm not sure if it really exists), is an API, that given a StatefulSet will allow me to know the DNS names of the Replicas that were created. Does an API like this exists?

like image 382
licorna Avatar asked Oct 16 '22 20:10

licorna


1 Answers

When you create the headless Service with the StatefulSet, it should create DNS SRV entries. You can query that to get a list of all host names of the pods corresponding to the headless Service without knowing the number. For example, if using Python you can do:

>>> import dns
>>> for item in dns.resolver.query('your-app-name-headless', 'SRV'): item
...
<DNS IN SRV rdata: 10 25 0 2555bb89.your-app-name-headless.your-project.svc.cluster.local.>
<DNS IN SRV rdata: 10 25 0 830bdb18.your-app-name-headless.your-project.svc.cluster.local.>
<DNS IN SRV rdata: 10 25 0 aeb532de.your-app-name-headless.your-project.svc.cluster.local.>
<DNS IN SRV rdata: 10 25 0 a432c21f.your-app-name-headless.your-project.svc.cluster.local.>

See:

  • https://kubernetes.io/docs/concepts/services-networking/dns-pod-service/#srv-records
  • https://kubernetes.io/docs/concepts/services-networking/service/#headless-services
like image 121
Graham Dumpleton Avatar answered Oct 19 '22 22:10

Graham Dumpleton