Difference between port and targetPort in Kubernetes
In the previous post, we deployed a simple microservice to Kubernetes. In this post, we would take a look at the various port mappings available for an application in Kubernetes and the differences between them.
Let us take a look at the service yaml file created in previous post.
You must be wondering that there are so many port mappings available in the yaml file, and what each of those means.
There are two port mappings available, port and targetPort. There is also a third option., when we use Service type as nodePort, we can also provide a specific nodePort which could be used.
Explanation of Ports:
When we use nodePort Service type, Kubernetes assigns a static port through which external clients can access the service. In our example, it is 31869.
Port (8086), is the port through which other services in the same node or other nodes within the cluster can access the service.
TargetPort (8085), is the port through which the actual Pod is accessible.
Explanation of Traffic Flow:
The diagram above shows the traffic flow when a request is made by an external client. When the external client makes a call using Node Port (31869), the kube proxy will handle this request and will forward the request to the port exposed by the service which is 8086 in our case. Finally, this request gets forwarded to the POD which is exposed on port 8085.
We can observe that, Service 2 can access Service 1 directly using the Port 8086.
I hope we have learnt about the various port mappings used and next time, we deploy an application to Kubernetes, we know the meaning of each port mapping.