<p>Say if I have a <code>rabbitmq</code> service as follows:</p>

<pre><code>apiVersion: v1
kind: Service
metadata:
  name: my-rabbitmq
spec:
  ports:
  - port: 6379
  selector:
    app: my-rabbitmq
</code></pre>

<p>And I have another deployment:</p>

<pre><code>apiVersion: apps/v1beta1
kind: Deployment
metadata:
  name: A-worker
spec:
  replicas: 1
  containers:
  - name: a-worker
    image: worker-image
    ports:
    - containerPort: 80
    env:
    - name: rabbitmq_url
      value: XXXXXXXXXXXXX
</code></pre>

<p>Is there any way to set the service ip as environment variable in my second deployment by some kind of selector? In other words what should go to the <code>value: XXXXXXXXXX</code> in the second deployment yaml. (Note I know I can get the service ip by <code>kubectl get services</code>, but I'd like to know how to set this by the service name or label). Any advice is welcome!</p>

<p>kubernetes injects environment variables for a service's host, port, protocol among others into pod containers (see <a href="https://kubernetes.io/docs/concepts/containers/container-environment-variables/" rel="nofollow noreferrer">this doc</a>).  </p>

<p><code>kubectl exec &lt;pod&gt; printenv</code> is one way to check which env variables are set.  </p>

<p>If the service is created after the pod the env var may not be present so killing (restarting) the pod is one way to make sure the new environment variables are populated.</p>

<p>The convention is typically uppercase <code>&lt;SERVICE_NAME&gt;_SERVICE_HOST</code>.
You can set it explicitly in a pod spec using the following syntax.  </p>

<blockquote>
<pre><code>    - name: rabbitmq_url
      value: $(MY-RABBITMQ_SERVICE_HOST)
</code></pre>
</blockquote>

<p>Bear in mind the variable is already injected by k8s and this is just aliasing it. You may want to update your reference in the application layer /script to use the k8s injected environment variable for the service.</p>
