What is the difference between port, targetPort and nodePort in a Service?
port is where the Service listens inside the cluster, targetPort is the container port traffic is forwarded to, and nodePort is the port opened on each node for NodePort or LoadBalancer Services.
Explain it simply
Think of a company's helpline. Customers dial the published number (port). The call is forwarded to the desk extension inside (targetPort). For visitors at the building, there is also a specific gate number on the street (nodePort).
Suppose the app listens on 8080 inside the container. The Service says port: 80, targetPort: 8080. Other Pods call http://web:80; the Service forwards to a Pod on 8080. If you omit targetPort, it defaults to the same value as port. With type: NodePort, Kubernetes also opens nodePort, for example 30080, on every node, so NODE_IP:30080 reaches the Service. If you do not set it, Kubernetes picks one from the 30000-32767 range.
targetPort can also be the name of a port defined on the container, which lets you change numbers without editing the Service.
Example
spec:
type: NodePort
selector:
app: web
ports:
- port: 80 # cluster-internal Service port
targetPort: 8080 # container port
nodePort: 30080 # node portWhat to say in the interview
"port is the Service's own port, targetPort is the container port it forwards to, and nodePort is the port opened on every node for NodePort and LoadBalancer types, defaulting to the 30000-32767 range."
Common mistakes
- Setting targetPort to the Service port when the container listens elsewhere, causing connection refused.