I have been starting to use Docker to implement a number of applications (Jira, Confluence, Jenkins, GitLab etc), but one issue I have encountered is, that unless you create specific networks for each container, on starting the container, it is given a random IP address (typically the next available one in the subnet).

Since I use reverse proxies to navigate to the containers, I need to be able to redirect from the external URL to the internal IP address of each container, but there is no simple way of identifying those IP addresses.

Enter a quick piece of code that can be used to retrieve the IP addresses for each container: dockerip.sh.

  1. Log into your Linux server that is running Docker as a user that can execute Docker commands.
  2. At the shell prompt, type ‘vi dockerip.sh’.
  3. In vi, press I and paste in the code on the dockerip.sh tab.
  4. In vi, press [ESC] and then type ‘wq dockerip.sh’ and press [ENTER].
  5. At the shell prompt, type ‘chmod 744 dockerip.sh’ to make the script executable.
  6. You can now run the script specifying each container you want the IP address for as follows:
    ./dockerip.sh [containername1 | containername2 | containernameN]
  7. If you want to display IP addresses for all Containers, simply type:
    ./dockerip.sh
  8. If you want to make life even more simple, you can create an alias for the script.
  9. At the shell prompt, type ‘vi ~/.bashrc’ and press [ENTER].
  10. In vi, type ‘dockerip=’~/dockerip.sh’.
  11. In vi, press [ESC] and then type ‘wq’ and press [ENTER].
  12. At the shell prompt, type ‘. ~/.bashrc’ to reload the file.

To run the script you can now use: dockerip in place of ./dockerip.sh.

bash$: dockerip Jira Confluence
Jira: 172.18.0.2
Confluence: 172.18.0.3

bash$: dockerip
Jira: 172.18.0.2
Confluence: 172.18.0.3
Jenkins: 172.17.0.2
GitLab: 172.17.0.3

#Displays the IP addresses for each Docker Container specified:
# ./dockerip.sh [containername1 | containername2 | containernameN]
# or all Docker Containers if no parameters are passed:
# ./dockerip.sh


if [ ! "$@" ]
then
  #You can use either of these commands: they will both give the same output.
  #containers="$(docker ps | cut -c175- | sed "1 d")"
   containers="$(docker ps | awk 'NR>1 {print substr($0,175)}')"
else
   containers="$@"
fi
for container in $containers
 do
    echo -n "$container: "; docker inspect -f 
        '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $container
 done

Share This

Share this post with your friends!