Home > Software design >  kubernetes LoadBalancer service target port set as random in GCP instead of as configured
kubernetes LoadBalancer service target port set as random in GCP instead of as configured

Time:09-24

This is the simplest config straight from the docs, but when I create the service, kubectl lists the target port as something random. Setting the target port to 1337 in the YAML:

apiVersion: v1
kind: Service
metadata:
  name: sails-svc
spec:
  selector:
    app: sails
  ports:
    - port: 1337
      targetPort: 1337
  type: LoadBalancer

And this is what k8s sets up for services:

kubectl get services
NAME           TYPE           CLUSTER-IP     EXTERNAL-IP     PORT(S)          AGE
kubernetes     ClusterIP      <X.X.X.X>      <none>          443/TCP          23h
sails          LoadBalancer   <X.X.X.X>      <X.X.X.X>       1337:30203/TCP   3m6s
svc-postgres   ClusterIP      <X.X.X.X>      <none>          5432/TCP         3m7s

Why is k8s setting the target port to 30203, when I'm specifying 1337? It does the same thing if I try other port numbers, 80 gets 31887. I've read the docs but disabling those attributes did nothing in GCP. What am I not configuring correctly?

CodePudding user response:

Kubectl get services output includes Port:NodePort:Protocol information.By default and for convenience, the Kubernetes control plane will allocate a port from a range default: 30000-32767(Refer the example in this documentation)

To get the TargetPort information try using

kubectl get service <your service name> --output yaml

This command shows all ports details and stable external IP address under loadBalancer:ingress:

Refer this documentation from more details on creating a service type loadbalancer

CodePudding user response:

Maybe this was tripping me up more that it should have due to some redirects I didn't realize that were happening, but ironing out some things with my internal container and this worked.

Yields:

NAME           TYPE           CLUSTER-IP    EXTERNAL-IP     PORT(S)          AGE
kubernetes     ClusterIP      10.3.240.1    <none>          443/TCP          28h
sails          LoadBalancer   10.3.253.83   <X.X.X.X>       1337:30766/TCP   9m59s
svc-postgres   ClusterIP      10.3.248.7    <none>          5432/TCP         12m

I can curl against the EXTERNAL-IP:1337. The internal target port was what was tripping me up. I thought that meant my pod needed to open up to that port and pod applications were supposed to bind to that port (i.e. 30766), but that's not the case. That port is some internal port mapping to the pod I still don't fully understand yet, but the pod still gets external traffic on port 1337 to the pod's 1337 port. I'd like to understand what's going on there better, as I get more into the k8s Networking section of the docs, or if anyone can enlighten me.

  • Related