How to update your host file with the ip addresses of the containers running on the host

rootUncategorizedLeave a Comment

startup-photos-567-min

 

Introduction
We are using BIRT extensively for reporting from our Atlassian JIRA.    The BIRT viewer is a tomcat application which will use a design file to turn raw data into documents or pdf files.
But now we got this idea to migrate our Atlassian stack to docker and the migration of BIRT into the container was a challenge on its own.

 

The fact is that BIRT needs access to the JIRA database to run the reports, and furthermore, we need to have access to the database to develop the reporting files.
It all boiled down to the fact that we need a way to convert the docker container name into an IP address.  A bit like DNS works – isn’t it.

 

Extracting the docker ip addresses and add to the /etc/hosts file
Thanks to bash we have a very easy approach to extract the ip addresses

The idea is that we add the ip addresses of the different docker services to the host file such that we can address the service with the ‘domain name’

The following script ‘addDockerIPaddressesTo.sh’ will do the grunt work

#!/bin/sh
 
#
# Retrieve the argument and create a name for a tmp file
#
processfile=$1
tmpfile=${1}.tmp
  
#
# for all running docker containers
#
for service in `docker ps -q`; do
   #
   # Extract the servicename and ipaddress
   #
   servicename=`docker inspect --format '{{ .Name }}' $service `
   ipaddress=`docker inspect --format '{{ .NetworkSettings.IPAddress }}' $service`
  
   #
   # if there is a service name and ipaddress
   #
   if [ ! -z $ipaddress ] &&  [ ! -z $servicename ] ;
   then
        # get rid of the first character - this is '/'
  
        servicename=${servicename:1}
  
        # remove the service name from the process file, and add it again
        grep -v $servicename $processfile > $tmpfile
        echo -e $ipaddress '\t' $servicename  >> $tmpfile
        mv $tmpfile $processfile
   fi
done

 

Integrate onto your environment

Whenever you restart your environment and/or add a new container, just run

addDockerIPaddressesTo /etc/hosts

 

(off course as root), or add it to your crontab