Kubernetes supports 2 primary modes of finding a Service - environment variables and DNS. The former works out of the box while the latter requires the CoreDNS cluster addon.
When a Pod runs on a Node, the kubelet adds a set of environment variables for each active Service. This introduces an ordering problem. To see why, inspect the environment of your running nginx Pods (your Pod name will be different): Let’s view the pods again:
kubectl get pods -l run=my-nginx -o wide
Output:
Now let’s inspect the environment of your running nginx Pods (your Pod name will be different):kubectl exec my-nginx-3800858182-jr4a2 -- printenv | grep SERVICE
Note there’s no mention of your Service. This is because you created the replicas before the Service. Another disadvantage of doing this is that the scheduler might put both Pods on the same machine, which will take your entire Service down if it dies. We can do this the right way by killing the 2 Pods and waiting for the Deployment to recreate them. This time around the Service exists before the replicas. This will give you scheduler-level Service spreading of your Pods (provided all your nodes have equal capacity), as well as the right environment variables:
kubectl scale deployment my-nginx --replicas=0
kubectl scale deployment my-nginx --replicas=2
kubectl get pods -l run=my-nginx -o wide
Output just in the moment of change:
You may notice that the pods have different names, since they are killed and recreated.kubectl exec my-nginx-3800858182-e9ihh -- printenv | grep SERVICE
Kubernetes offers a DNS cluster addon Service that automatically assigns dns names to other Services. You can check if it’s running on your cluster:
kubectl get services kube-dns --namespace=kube-system
If it isn’t running, you can enable it. The rest of this section will assume you have a Service with a long lived IP (my-nginx), and a DNS server that has assigned a name to that IP (the CoreDNS cluster addon), so you can talk to the Service from any pod in your cluster using standard methods (e.g. gethostbyname). Let’s run another curl application to test this:
kubectl run curl --image=radial/busyboxplus:curl -i --tty
Output:
Then, hit enter and runnslookup my-nginx
Output:
exit