<p>I've added a second TCP port to my Kubernetes service, and have noticed that which port kubelet assigns to the <code>{SVCNAME}_SERVICE_PORT</code> <a href="https://kubernetes.io/docs/concepts/services-networking/service/#environment-variables" rel="nofollow noreferrer">environment variable</a> appears to be order dependent.</p>
<p>For example, if I declare my ports like this in my service:</p>
<pre class="lang-yaml prettyprint-override"><code>ports:
- name: example
  port: 9000
  protocol: TCP
- name: http
  port: 8080
  protocol: TCP
</code></pre>
<p>Then <code>FOO_SERVICE_PORT</code> will be assigned the value <code>9000</code>. But if I flip the order ...</p>
<pre class="lang-yaml prettyprint-override"><code>ports:
- name: http
  port: 8080
  protocol: TCP
- name: example
  port: 9000
  protocol: TCP
</code></pre>
<p>... then <code>FOO_SERVICE_PORT</code> is now <code>8080</code>.</p>
<p>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 &quot;http&quot; port (8080) as value it assigns to this variable, regardless of where in the list this particular port is declared?</p>

Roddy of the Frozen Peas
<p>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 <a href="https://github.com/kubernetes/kubernetes/blob/master/pkg/kubelet/envvars/envvars.go#L47" rel="nofollow noreferrer">first port in the backwards compatible environment variable</a>. There is no configuration that changes this behavior.</p>
<p>However, Kubernetes also sets <code>{serviceName}_SERVICE_PORT_{portName}</code> environment variables for named ports, so you can get the port number by port name. For example:</p>
<pre class="lang-java prettyprint-override"><code>FOO_SERVICE_PORT_EXAMPLE=9000
FOO_SERVICE_PORT_HTTP=8080
</code></pre>
