kubernetesportkind

How the K8s service port mapping works?


I have successully configured an external load balancer service with Kind (Kubernetes in Docker) using kind-cloud-provider. I can access the service using http://localhost:63238

Here is my yaml file (pods + service) :

kind: Pod
apiVersion: v1
metadata:
  name: foo-app
  labels:
    app: http-echo
spec:
  containers:
    - command:
        - /agnhost
        - serve-hostname
        - --http=true
        - --port=8080
      image: registry.k8s.io/e2e-test-images/agnhost:2.39
      name: foo-app
---
kind: Pod
apiVersion: v1
metadata:
  name: bar-app
  labels:
    app: http-echo
spec:
  containers:
    - command:
        - /agnhost
        - serve-hostname
        - --http=true
        - --port=8080
      image: registry.k8s.io/e2e-test-images/agnhost:2.39
      name: bar-app
---
kind: Service
apiVersion: v1
metadata:
  name: foo-service
spec:
  type: LoadBalancer
  selector:
    app: http-echo
  ports:
    - port: 5678
      targetPort: 8080

As described above, the port of the service is 5678 and is mapped with the port of the pods 8080. But when I get the service info using kubectl it shows that port 5678 is mapped with 30755. I have no clue what this port is refering to.

kubectl get service

Endpoints are using 8080 :

kubectl get endpoint

I have explored my cluster using kubectl and Lens. I can see that the port 30755 also shows up in the kind-cloud-provider config :

kind-cloud-provider conf screenshot

the only way to actually know which port to use is to scroll the kind-cloud-provider, looking for this line matching my service port (5678).

kind-cloud-provider conf screenshot

Can anyone enlighten me on this mysterious whole port mapping thing ? Especially on the 30755 showing up in my service ? thanks :)


Solution

  • When using a LoadBalancer as a Service type in kubernetes, it starts off by creating a NodePort service in the background to facilitate communication, the control plane will allocate the port from a default range port: 30000-32767. Then, configures the external load balancer to forward traffic to the assigned service port by cloud-controller-manager.

    If you want to toggle this type of allocation you may set the field as:

    spec: 
      allocateLoadBalancerNodePorts: #true or false