Last active
October 29, 2015 15:10
-
-
Save byrnedo/6614eed43cb82d3ce0b1 to your computer and use it in GitHub Desktop.
Maps a dynamically allocated docker port to a chosen static port. Watches for updates.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func staticDockerPortMapper(){ | |
[[ $# -lt 3 ]] && >&2 echo "usage: $0 <container-name/id> <exposed-container-port>/<tcp|udp> <static-port>" && return | |
local container=$1 | |
local internalPort=$2 | |
local staticPort=$3 | |
local currentPid=$(lsof -ti :$staticPort 2>/dev/null) | |
if [[ -n $currentPid ]] | |
then | |
command=$(ps -h --format %c $currentPid) | |
read -k 1 -r "?Kill process $currentPid/$command already on your static port $staticPort? [y/n]" | |
echo | |
if [[ $REPLY =~ ^[Yy]$ ]] | |
then | |
kill $currentPid >/dev/null 2>&1 | |
else | |
echo "Well not killing it is probably not going to work but ok..." | |
fi | |
fi | |
local pid= | |
local port= | |
while true | |
do | |
local currentPort=$(docker inspect $container|jq ".[0].NetworkSettings.Ports.\"$internalPort\"| .[0].HostPort|tonumber") | |
if [[ ! $? ]] | |
then | |
>&2 echo Port Not Found | |
elif [[ "$currentPort" -ne "$port" ]] | |
then | |
echo "Mapping $currentPort to $staticPort" | |
port="$currentPort" | |
[[ -n $pid ]] && echo "Killing old socat command at $pid" && kill "$pid" | |
socat tcp-listen:$staticPort,reuseaddr,fork tcp:localhost:$port & | |
fi | |
sleep 5 | |
done | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment