Difference between Container port and targetport in Kubernetes?
In a nutshell: targetPort
and containerPort
basically refer to the same port (so if both are used they are expected to have the same value) but they are used in two different contexts and have entirely different purposes.
They cannot be used interchangeably as both are part of the specification of two distinct kubernetes resources/objects: Service
and Pod
respectively. While the purpose of containerPort
can be treated as purely informational, targetPort
is required by the Service
which exposes a set of Pods
.
It's important to understand that by declaring containerPort
with the specific value in your Pod
/Deployment
specification you cannot make your Pod
to expose this specific port e.g. if you declare in containerPort
field that your nginx Pod
exposes port 8080
instead of default 80
, you still need to configure your nginx server in your container to listen on this port.
Declaring containerPort
in Pod
specification is optional. Even without it your Service
will know where to direct the request based on the info it has declared in its targetPort
.
It's good to remember that it's not required to declare targetPort
in the Service
definition. If you omit it, it defaults to the value you declared for port
(which is the port of the Service
itself).
ContainerPort in pod spec
List of ports to expose from the container. Exposing a port here gives the system additional information about the network connections a container uses, but is primarily informational. Not specifying a port here DOES NOT prevent that port from being exposed
targetPort in service spec
Number or name of the port to access on the pods targeted by the service. Number must be in the range 1 to 65535. Name must be an IANA_SVC_NAME. If this is a string, it will be looked up as a named port in the target Pod's container ports. If this is not specified, the value of the 'port' field is used (an identity map).
Hence targetPort
in service needs to match the containerPort
in pod spec because that's how service knows which container port is destination to forward the traffic to.
containerPort is the port, which app inside the container can be reached on.
targetPort is the port, which is exposed in the cluster and the service connects the pod to other services or users.