How can I use the internal IP address of the container as an environment variable in Docker

I am trying to get the IP address of my dock container as an environment variable inside the container. Here is what I tried:

When starting container

docker run -dPi -e ip='hostname -i' myDockerImage 

When the container is already loaded

 docker exec -it myDockerImage bash -c "export ip='hostname -i'" 

The problem with these two methods is that it uses the IP address of the host on which the commands are executed, and not the docker container on which it runs.

So, I created a script inside the Docker container that looks like this:

 #!/bin/bash export ip='hostname -i' echo $ip 

And then run this with

 docker exec -it myDockerImage bash -c ". ipVariableScript.sh" 

When I add my_cmd, which in my case is bash to the end of the script, it works in a single bash session. I can not use it later in the files in which I need it. I need to set it as an environment variable, not as a variable for a single session.

So I already put it with ".". But it still won’t echo when I'm in the container. If I $ip into the echo $ip script, it will give me the correct IP address. But it can only be used from the script in which it is installed.

+5
source share
1 answer

Docker service names are more reliable and easier to use. However here

How to assign Docker guest IP to var guest guest

 $ docker run -it ubuntu bash -c 'IP=$(hostname -i); echo ip=$IP' ip=172.17.0.76 
0
source

All Articles