title: How can I use the internal ip address of a container as an environment variable in Docker
body: <p>I'm trying to get the IP address of my docker container as an environment variable within the container. Here is what I've tried:</p>
  
  <p>When starting the container</p>
  
  <pre><code>docker run -dPi -e ip=`hostname -i` myDockerImage
  </code></pre>
  
  <p>When the container is already booted up</p>
  
  <pre><code>docker exec -it myDockerImage bash -c "export ip=`hostname -i`"
  </code></pre>
  
  <p>The problem with these two methods is that it uses the ip address of the host running the commands, not the docker container it's being run on.</p>
  
  <p>So then I created a script inside the docker container that looks like this:</p>
  
  <pre><code>#!/bin/bash
  export ip=`hostname -i`
  echo $ip
  </code></pre>
  
  <p>And then run this with</p>
  
  <pre><code>docker exec -it myDockerImage bash -c ". ipVariableScript.sh"
  </code></pre>
  
  <p>When I add my_cmd which in my case is <code>bash</code> to the end of the script, it works in that one session of bash. I can't use it later in the files I need it in. I need to set it as an environment variable, not as a variable for one session.</p>
  
  <p>So I already sourced it with the '.'. But it still won't echo when I'm in the container. If I put an echo <code>$ip</code> in the script, it will give me the correct IP address. But can only be used from within the script it's being set in.</p>