Skip to content

Instantly share code, notes, and snippets.

@utarn
Created May 24, 2022 02:08
Show Gist options
  • Save utarn/934c2eafab6d026da55db608a9324250 to your computer and use it in GitHub Desktop.
Save utarn/934c2eafab6d026da55db608a9324250 to your computer and use it in GitHub Desktop.
Add docker container IP to hosts file.
#!/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 '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment