Service Ports: port, targetPort and nodePort
Three numbers are involved in getting a request to a container - port, targetPort and containerPort - and only two of them matter. This proves which by setting containerPort to something completely wrong and watching everything keep working, then setting targetPort wrong and watching it all stop.
Services and Networking Guide 33 of 44 Beginner
- Kubernetes1.36.4
- Cluster4 nodes
- Runtimecontainerd 2.2.6
- CNICalico v3.32.1
- TimeAbout 14 min
containerPort is informational. It does not open, publish or reserve anything - the process listens on whatever it listens on. Its only real functions are documentation and giving the port a NAME that targetPort can refer to.
| Server Name | IP Address | OS | Roles | CPU | RAM | HDD |
|---|---|---|---|---|---|---|
| CKA1001 | 192.168.0.175 | Ubuntu 26.04 LTS | Control Plane Node | 2 Core | 4 GB | 50 GB |
| CKA1001-NODE01 | 192.168.0.176 | Ubuntu 26.04 LTS | Worker Node | 2 Core | 4 GB | 50 GB |
| CKA1001-NODE02 | 192.168.0.177 | Ubuntu 26.04 LTS | Worker Node | 2 Core | 4 GB | 50 GB |
| CKA1001-NODE03 | 192.168.0.178 | Ubuntu 26.04 LTS | Worker Node | 2 Core | 4 GB | 50 GB |
This guide includes
Use this when a Service is configured and nothing answers. This matters because three numbers are involved and only two of them do anything - containerPort is informational, so a wrong one changes nothing while a wrong targetPort breaks everything.
- separating
port,targetPortandcontainerPortby what each one actually controls - declaring the wrong containerPort and confirming traffic still flows perfectly
- pointing targetPort at that same wrong number, and watching everything break
- naming the port instead, which is where containerPort finally earns its keep
Before you start
- A cluster and kubectl.
- The session creates namespace
ckad-port, a Deployment whosecontainerPortis deliberately wrong, a Service in front of it, and a second pair using a named port.
-
Three numbers that are not the same thing
-
The wrong containerPort does not matter
-
The wrong targetPort breaks everything
-
Naming the port instead