Kubernetes: Port vs. TargetPort in Service

Kubernetes: Port vs. Target Port

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 an example manifest file of a service.

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.

1,508 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *