#!/bin/bash -e # Usage: ./docker-local-hosts.sh containername mylocalname # Get IP of container and strip newlines. INSPECT=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $1) IP=${INSPECT//[$'\t\r\n']} if test -z "$IP"; then echo "Container IP for $1 not found." exit fi # Get hostname or use container name as default. HOSTNAME="${2:-$1}" # Remove line with previous container. sudo sed -i "/\s#$1/d" /etc/hosts # Add new hosts line. echo "$IP $HOSTNAME #$1" | sudo tee -a /etc/hosts