How to get service's NodePort programmatically in Kubernetes?

8/2/2017

I developed two web apps(we call them A and B) and deployed them to k8s. The web app A refers to the images generated by web app B. In previous environment, B has the fixed IP and port which makes it very easier to reach the images hosted on B.

In the K8S environment, I use the service type - NodePort. In that case, the port is randomly generated upon deployment each time.

The question is whether there is a way to fetch B service's node port programmatically from the A Pod. Or is it possible to fix the node port for one service?

-- ichbinblau
kubernetes

1 Answer

8/2/2017

There are three answers to your question:

The first is that one should not be destroying the Service just because the Pods behind it are redeployed. The Service is designed to be the long-lived contract that abstracts over the placement (or count) of the servicing Pods

The second is that if you do wish to have web-app A use a known-to-you NodePort, you can put a value in the nodePort: field of the ports: mapping inside the Service, and assuming it is not already assigned, kubernetes will defer to your judgement

The third answer is that every Pod that runs within the cluster automatically gains an API token for communication with the kubernetes API (it lives in /run/secrets/kubernetes.io or similar), so you can ask the API from within the Pods to give you the current value of the Service's nodePort

-- mdaniel
Source: StackOverflow