Kubernetes Service中port与targetPort的区别是什么?
Hey there, let's clear up the difference between port and targetPort using your Service example—it's a common point of confusion, so great question!
port
This is the port that the Service itself exposes to the rest of the Kubernetes cluster. Any other pod, deployment, or internal resource that wants to talk to your my-service will use this port. Think of it as the Service's "public-facing" port within the cluster. In your example, if another pod needs to reach your MyApp, it would connect to my-service:80.
targetPort
This is the port that your backend application pods are actually listening on. The Service acts as a traffic router here: when it gets incoming traffic on its port, it forwards that traffic to the targetPort on the pods matched by the Service's selector (in your case, pods labeled app: MyApp). So in your example, traffic hitting my-service:80 gets sent straight to port 9376 on your MyApp pods.
Quick Traffic Flow Recap
Internal Cluster Pod → my-service:80 (Service port) → MyApp Pod:9376 (targetPort)
One handy bonus: targetPort doesn't have to be a number! If your pod's container defines a named port (like containerPort: 9376 with name: app-port), you can set targetPort: app-port in the Service. This makes your config more flexible if you ever change the actual port number later—no need to update the Service definition.
内容的提问来源于stack exchange,提问作者Mr.DevEng




