Port Numbers for routing traffic in multicontainer pods

Hi
Consider two containers in a pod listening on different ports.
If pod has multiple ports open, where two different applications are listening inside a POD on two different port numbers - then how does a service know which port to forward the requests to ?

As I know, using targetPort attribute of a service we can assign one port, the what about the other applications traffic. Do we need to create a separate service for that application ?

Please help

You can have multiple services with the same selector if you want.
You can also have multiple ports in a single service. Recall that ports in a service manifest is a list, not a single entry.

apiVersion: v1
kind: Service
metadata:
  name: my-service
spec:
  selector:
     app: frontend
  ports:
  - name: site
     port: 80
     targetPort: 80
     protocol: TCP
  - name: metrics
     port: 9090
     targetPort: 9090
     protocol: TCP
  type: ClusterIP

Then curl http://my-service would go via port 80, and curl http://my-service:9090 would go to the other port.

1 Like

Thanks Alistair.
I have a followup question on Nodeport.

Nodeport also acts a loadbalancer and spans across all the nodes in the cluster. Maps the same Nodeport to target port on all the nodes.

Now to access this service one has to use individual “IPAddress:Port” number of each node - then how loadbalancing is working since we are only invoking the node we want the traffic to be routed to ?

Thanks

It is not really a load balancer. It just exposes the same port on all cluster nodes. If you wanted to load balance across them, then you would need to deploy an external load balancer like HAProxy to connect to all the node ports for a given service which would only make sense if your cluster isn’t running in a cloud where you would use the cloud’s load balancer controller connected to an ingress.