What is the advantage of allowing port and targetPort to be different in Kubernetes services?

5/7/2020

Today I have started to learn about Kubernetes because I have to use it in a project. When I came to the Service object, I started to learn what is the difference between all the different types of ports that can be specified. I think now I undertand it.

Specifically, the port (spec.ports.port) is the port from which the service can be reached inside the cluster, and targetPort (spec.ports.targetPort) is the port that an application in a container is listening to.

So, if the service will always redirect the traffic to the targetPort, why is it allowed to specify them separately? In which situations would it be necessary?

-- Abraham Simpson
kubernetes

1 Answer

5/7/2020

The biggest use is with LoadBalancer services where you want to expose something on (usually) 80 or 443, but don't want the process to run as root so it's listening on 8080 or something internally. This lets you map things smoothly.

-- coderanger
Source: StackOverflow