Search code examples
kuberneteskubernetes-dns

kubernetes dns list all ips for service


I have a list of pods like so:

❯ kubectl get pods -l app=test-pod                                                                                                                              (base)
NAME                               READY   STATUS    RESTARTS   AGE
test-deployment-674667c867-jhvg4   1/1     Running   0          14m
test-deployment-674667c867-ssx6h   1/1     Running   0          14m
test-deployment-674667c867-t4crn   1/1     Running   0          14m

I have a service

kubectl get services                                                                                                                          (base)
NAMESPACE     NAME                                TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)                        AGE
default       test-service                        ClusterIP   10.100.4.138     <none>        4000/TCP                       15m

I perform a dns query:

❯ kubectl exec -ti test-deployment-674667c867-jhvg4  -- /bin/bash                                                                                               (base)
root@test-deployment-674667c867-jhvg4:/# busybox nslookup test-service
Server:     10.100.0.10
Address:    10.100.0.10:53

Name:   test-service.default.svc.cluster.local
Address: 10.100.4.138

My config:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: test-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: test-pod
  template:
    metadata:
      labels:
        app: test-pod
    spec:
      containers:
      - name: python-http-server
        image: python:2.7
        command: ["/bin/bash"]
        args: ["-c", "echo \" Hello from $(hostname)\" > index.html; python -m SimpleHTTPServer 80"]
        ports:
        - name: http
          containerPort: 80
kind: Service
apiVersion: v1
metadata:
  name: test-service
spec:
  selector:
    app: test-pod
  ports:
  - protocol: TCP
    port: 4000
    targetPort: http

How can I instead get a list of all the pods's ip addresses via a dns query?

Ideally I would like to perform an nslookup of a name and get a list of all the pod's ips in a list.


Solution

  • You have to use a headless service with selectors. It returns the ip addresses of the pods.

    See here: https://kubernetes.io/docs/concepts/services-networking/service/#headless-services

    .spec.clusterIP must be "None"