<p>Inside a service yaml file, you can use jsonpath to select a named nodeport value like so:</p>

<pre><code>    - name: MY_NODE_PORT
      valueFrom:
        fieldRef:
          fieldPath: spec.ports[?(@.name=="http")].nodePort
</code></pre>

<p>However, in my deployment yaml file, I would like to have an environment variable like <code>MY_NODE_PORT</code> above that is exposed to the container to the pod. I happen to have combined my service and deployment into a single file for me to <code>kubectl create -f</code>. Is it possible to select the named service nodeport in the deployment section, rather than in the service section?</p>

<p>My purpose is to register a Kubernetes service and deployment to a legacy service discovery mechanism, in this case Netflix OSS Eureka.</p>

<p>As in <a href="https://stackoverflow.com/users/371954/janos-lenart">Janos Lenart</a>'s answer and <a href="https://stackoverflow.com/users/4763788/marc-sluiter">Marc Sluiter</a> commented, a service and a deployment are different resources and might as easily be specified in separate files. They have no direct knowledge of one another, and, even if you name the service NodePort port, unless you explicitly specify the service NodePort port value (e.g. something from 30000 to 32767) you won't be able to specify what the pod environment variable should be to match it. While you can hard code the NodePort port value like that, as <a href="https://stackoverflow.com/users/371954/janos-lenart">Janos Lenart</a> suggested, but it's brittle and not recommended.</p>

<p>While Kubernetes provides a number of handy environment variables to pods, it is not possible for a pod environment variable to reference a service nodeport port value that was dynamically assigned by kubernetes.</p>

<p>However, the Pod <strong>does</strong> have access to talk to the Kubernetes API server, and the API server will be able to reply back with information about the service, such as the nodeport. So a Pod can ask the API server for a service's NodePort port value. I created a <a href="https://github.com/StevenACoffman/kubernetes-eureka-sidecar" rel="nofollow noreferrer">kubernetes service and deployment with simple sidecar pod</a> as a proof of concept.</p>

<p><a href="https://github.com/StevenACoffman/kubernetes-eureka-sidecar" rel="nofollow noreferrer">My example here</a> handles registering a Kubernetes NodePort service with an (external or internal) Netflix OSS Eureka service registry. This might be useful to others for bridging Kubernetes to other legacy service discovery mechanisms. </p>
