Use Case: Updating Host File with IP Addresses of Host-Running Containers

adminUncategorized

 

Introduction
We are using BIRT extensively for reporting from our Atlassian JIRA.  The BIRT viewer is a tomcat application that 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.  It’s a bit like DNS works – isn’t it?

 

Extracting the docker IP addresses and adding to the /etc/hosts file
Thanks to bash, we have a very easy approach to extracting 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

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

If you want more info or need help, please get in touch!