Home > Net >  Kubernetes SERVICE_PORT environment variable appears order dependent
Kubernetes SERVICE_PORT environment variable appears order dependent

Time:04-09

I've added a second TCP port to my Kubernetes service, and have noticed that which port kubelet assigns to the {SVCNAME}_SERVICE_PORT environment variable appears to be order dependent.

For example, if I declare my ports like this in my service:

ports:
- name: example
  port: 9000
  protocol: TCP
- name: http
  port: 8080
  protocol: TCP

Then FOO_SERVICE_PORT will be assigned the value 9000. But if I flip the order ...

ports:
- name: http
  port: 8080
  protocol: TCP
- name: example
  port: 9000
  protocol: TCP

... then FOO_SERVICE_PORT is now 8080.

Is there a way to force kubelet to pick a specific port to set into this variable so that it's not dependent on the order I've defined my ports in? That is, is there a configuration I can set so it always uses the "http" port (8080) as value it assigns to this variable, regardless of where in the list this particular port is declared?

CodePudding user response:

In older Kubernetes versions, a Service can define only a single port. When they added support for multiple ports, they chose by design to put the first port in the backwards compatible environment variable. There is no configuration that changes this behavior.

However, Kubernetes also sets {serviceName}_SERVICE_PORT_{portName} environment variables for named ports, so you can get the port number by port name. For example:

FOO_SERVICE_PORT_EXAMPLE=9000
FOO_SERVICE_PORT_HTTP=8080
  • Related