DEV Community

Cover image for Finding DNS hostname for Kubernetes Service
Victor Osório
Victor Osório

Posted on

Finding DNS hostname for Kubernetes Service

Kubernetes is very difficult! If someone says it is easy, do not believe! But we can learn! 😎

There there is a little trick to find the internal DNS for a service.

I have created a service for a Cassandra Database using the following YAML:

apiVersion: v1 kind: Pod metadata: name: my-service labels: app: my-service spec: containers: - name: my-service image: my-service --- apiVersion: v1 kind: Service metadata: name: my-service spec: type: NodePort ports: - port: 8080 targetPort: 8080 nodePort: 30080 protocol: TCP selector: app: my-service --- apiVersion: v1 kind: Pod metadata: name: cassandra-db labels: app: cassandra-db spec: containers: - name: cassandra-db image: cassandra:3 --- apiVersion: v1 kind: Service metadata: name: cassandra-db spec: selector: app: cassandra-db type: ClusterIP ports: - port: TCP port: 7000 
Enter fullscreen mode Exit fullscreen mode

So I have a question? How can I know where I can find my database? I'm using a ClusterIP, so if I redeploy my database, it can change.

So the first approach is to not directly use my database hostname/port on code. I should retrieve it thought Environment Variables.

The I have to find the cassandra-db service hostname.

Finding the hostname

I have to create a pod in the environment, to access the environment topology:

apiVersion: v1 kind: Pod metadata: name: dnsutils namespace: default spec: containers: - name: dnsutils image: gcr.io/kubernetes-e2e-test-images/dnsutils:1.3 command: - sleep - "3600" imagePullPolicy: IfNotPresent restartPolicy: Always 
Enter fullscreen mode Exit fullscreen mode

Apply the created yaml file:

$ kubectl apply -f dnsutils.yaml pod/dnsutils created 
Enter fullscreen mode Exit fullscreen mode

Then I can easily search for the DNS with nslookup on dnsutils:

$ kubectl exec -ti dnsutils -- nslookup cassandra-db Server: 10.96.0.10 Address: 10.96.0.10#53 Name: cassandra-db.default.svc.cluster.local Address: 10.98.98.138 
Enter fullscreen mode Exit fullscreen mode

Easy?

Now that I do not need dnsutils pod anymore, I can delete it:

$ kubectl delete pod dnsutils pod "dnsutils" deleted 
Enter fullscreen mode Exit fullscreen mode

Using the found value as Environment Variable

Now we can use found value as environment variable:

apiVersion: v1 kind: Pod metadata: name: my-service labels: app: my-service spec: containers: - name: my-service image: my-service env: - name: DATABASE_HOST value: "cassandra-db.default.svc.cluster.local" - name: DATABASE_PORT value: "7000" 
Enter fullscreen mode Exit fullscreen mode

Conclusion

Using Kubernetes is not easy, but we can learn. Here we can find an easy way to find how can we access services internal Kubernetes DNS.

Top comments (0)