What is the need of target port for pods running in Kubernetes cluster

10/24/2018

When a container runs on a machine, one has to specify the port on which it should run, so other services in the machine can access to this container via port. But in kubernetes, each pod has their own IP address and user can mention incoming port, so other pods can communicate via IP:Port address.

So what is the need for having target port. I feel one can set any port for "target port" field and the other pods will be seamlessly able to communicate with it.

-- Vineet Mimrot
kubernetes

1 Answer

10/24/2018
---
apiVersion: v1
kind: Service
metadata:
  name: my-service
spec:
  ports:
  - port: 8080
    targetPort: 8070
    nodePort: 31222
    protocol: TCP 
  selector:
    component: my-service-app

port: is the port used by the k8s service

target port: is the port on which the pod is serving the app

nodePort: is the port on which the service is exposed outside the cluster

-- Ijaz Ahmad Khan
Source: StackOverflow