How do I get Pod IP with dns?

11/20/2018

There is Pod with Centos. I want to get Pod IP by DNS. But there was an error.

[root@namenode /]# nslookup namenode.space.default.svc.cluster.local
Server:         10.96.0.10
Address:        10.96.0.10#53
** server can't find namenode.space.default.svc.cluster.local: NXDOMAIN

[root@namenode /]# nslookup namenode
Server:         10.96.0.10
Address:        10.96.0.10#53

Name:   namenode.default.svc.cluster.local
Address: 10.107.117.123

This is my yaml file

apiVersion: v1
kind: Pod
metadata:
 name: test-con
 labels:
  app: test
spec:
 hostname: namenode
 subdomain: space
 containers:
 - name: test-con
   image: 192.168.50.130:5000/test
   command: [ "/usr/sbin/sshd", "-D"]

service.yaml

apiVersion: v1
kind: Service
metadata:
  name: namenode
spec:
  selector:
    name: test
  ports:
   -  name: "ssh"
      port: 22
      targetPort: 22
  type: NodePort

namespace is default. How can i solve this problem?

-- K.k
kubernetes

2 Answers

11/20/2018

First take a look into https://kubernetes.io/docs/concepts/services-networking/dns-pod-service/#pod-s-hostname-and-subdomain-fields.

According to this tutorial you have to change some parts:

  • update spec.selector to app: test in your service.
  • service name has to be equal with the spec.subdomain.
  • service has to be headless (spec.clusterIP set to None)

After everything is ready, try $ namenode.space.default.svc.cluster.local.

-- Shudipta Sharma
Source: StackOverflow

11/20/2018

When you nslookup the normal service name nslookup namenode it returns the clusterIP which is assigned to it. Whenever any request comes to that services, using kube-proxy it automatically discover the pod and send it to that pod. Hence, kube-dns doesn't know th podIP in advance, it just knows clusterIP and rest responsibility is of kube-proxy to find the pod.

To do pod discovery your own way, you need to use the headless service, which returns all the Pod IP attached to that service. However, the use case of headless service is in case of you have statefulset and each replica has its own PV, PVC. To define a headless service you need to provide clusterIP: None in the service definition. Please look at the my answer related to headless service

Kubernetes service architecture

According to your question if you just need Pod IP inside the pod, then you can use the environment variable to do it for you. Add the config block below to your pod definition:

env:
- name: MY_POD_NAME
  valueFrom:
    fieldRef:
      fieldPath: metadata.name
- name: MY_POD_NAMESPACE
  valueFrom:
    fieldRef:
      fieldPath: metadata.namespace
- name: MY_POD_IP
  valueFrom:
    fieldRef:
      fieldPath: status.podIP

Now, echo $MY_POD_IP will provide you pod IP inside container. Hope this helps.

-- Prafull Ladha
Source: StackOverflow