targetPort vs containerPort

Can someone please explain the diff b/w targetPort and containerPort. When to use which port?
Can I use containerPort(instead of targetPort) while creating a service of type = NodePort

A containerPort is the port that each container inside a pod listens to for traffic.

The targetPort is the port that a Service uses to reroute traffic. So, for example, a Service can listen for incoming traffic on its own port #ABC, and reroute that traffic to the targetPort #XYZ. This targetPort #XYZ should match the containerPort for the container that the service wants to send the traffic to (i.e. this would be port #XYZ on the containter).

NodePort exposes a port that the service listens on for incoming external traffic and that traffic flows into the exposed service.

At least, I believe that is it. I am still learning myself :slight_smile:

2 Likes
  • nodePort : The port on the node where external traffic will come in on
  • port : The port of this service
  • targetPort The target port on the pod(s) to forward traffic to

Traffic comes in on nodePort , forwards to port on the service which then routes to targetPort on the pod(s).

It’s worth emphasizing more that nodePort is for external traffic. Other pods in the cluster that may need to access the service will just use port , not nodePort as it’s internal only access to the service.

Please also mention the purpose of “containerPort”

1 Like

The containPort is the port that a container within a pod listens on for traffic. It is set within the pod definition in a Pod yaml, or as part of the container spec within a Pod template (i.e. as part of a replication set or deployment).

The containerPort of a container within a pod must match the targetPort set within any service that points to that pod. In other words, traffic routed by a service to a relevant pod is sent to the targetPort, and that pod then knows to route that traffic to the matching containerPort on whatever container is using that port.

Sorry, that explanation was probably a bit convoluted, so I hope it makes sense.

Summary: a service’s targetPort = the containerPort on the final container destination for the traffic (i.e. the target container within a pod).

2 Likes