Port vs TargetPort in Kubernetes Service
In Kubernetes, when creating a service, you have to set the “port” and “targetPort” properties.
A “port” refers to the container port exposed by a pod or deployment, while a “targetPort” refers to the port on the host machine that traffic is directed to.
Let’s look at example manifiest file of a service.
1 2 3 4 5 6 7 8 9 10 11 12 |
kind: Service apiVersion: v1 metadata: name: example-service spec: selector: app: example-app ports: - name: http port: 8089 protocol: TCP targetPort: 8080 |
In this example, the service listens on port 8089 and the container listens on port 8080. When you connect to the service on port 8089, the traffic is forwarded to port 8080 inside the container.
The separation of the “Port” and “Target Port” properties allows for the use of different ports for the service and the container. In the above example, the container does not need to have port 8089 exposed, as incoming traffic directed to the service on port 8089 is forwarded to port 8080 on the container.
Also, this allows for the possibility of running multiple services on the same host machine and directing traffic to the appropriate service by specifying the appropriate target port.
Leave a Reply