Skip to content

Instantly share code, notes, and snippets.

@bamthomas
Last active December 22, 2015 14:21
Show Gist options
  • Save bamthomas/87feda7f6534a7f91a06 to your computer and use it in GitHub Desktop.
Save bamthomas/87feda7f6534a7f91a06 to your computer and use it in GitHub Desktop.
update /etc/hosts to link with localhost the docker-compose services
#!/bin/bash
# -*- coding: UTF8 -*-
function rm_hosts {
for container_name in $*
do
host=$(docker inspect --format '{{ index .Config.Labels "com.docker.compose.service" }}' $container_name)
remove_line_infile $host /etc/hosts
done
}
function add_hosts {
for host in $*
do
sudo bash -c "echo $(docker inspect --format '{{ .NetworkSettings.IPAddress }}' $host) $(docker inspect --format '{{ index .Config.Labels "com.docker.compose.service" }}' $host ) >> /etc/hosts"
done
}
function remove_line_infile {
text=$1
filename=$2
exec 3<> $filename
exec 4<> $filename
bytecount=0
while IFS="" read -r line <&3 ; do
if [[ $line == *"$text"* ]]; then
echo "omitting line : $line"
else
echo "$line" >&4
((bytecount += ${#line} + 1))
fi
done
exec 3>&-
exec 4>&-
truncate -s $bytecount $filename
}
if [[ ($1 != "add" && $1 != "rm") || $# < 2 ]]; then
echo "usage : $0 add|rm docker_containers"
echo "example : $0 add cups_1 nginx_1 mongodb_1"
exit 1
fi
action=$1
shift
${action}_hosts "$*"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment