Skip to content

Instantly share code, notes, and snippets.

@jharlap
Last active February 11, 2016 14:03
Show Gist options
  • Save jharlap/9997e603ee8688eee035 to your computer and use it in GitHub Desktop.
Save jharlap/9997e603ee8688eee035 to your computer and use it in GitHub Desktop.
Docker port redirector container

Docker Port Forwarder

This is useful if a container exposes a service on a port and you need to be able to hit it at a different port, for example if one container stubs out two collaborator services on ports 1234 and 2345 but your program expects to hit the collaborators both on port 80 (and for some reason it's not trivial to change that).

The example docker-compose.yml assumes that you have the stubber (in this case, fake_sns) which listens on port 443 on the docker network, and that you have my_consumer which will hit http://sns.us-east-1.amazonaws.com:80 and you want it to use fake_sns instead.

Note that the portforwarder uses inotify to watch /etc/hosts which docker will update automatically whenever a linked container IP changes.

my_consumer:
build: my_consumer
links:
- redirector:sns.us-east-1.amazonaws.com
sns:
image: lattwood/fake_sns
command: fake_sns -p 443
redirector:
build: portforwarder
links:
- sns
environment:
- FROM_PORT=80
- TO_PORT=443
- TO_HOST=sns
cap_add:
- NET_ADMIN
FROM alpine:3.3
RUN apk update && apk upgrade && apk add bash iptables inotify-tools
ADD /start.sh /
CMD ["/start.sh"]
#!/bin/bash
if [[ -z $TO_PORT || -z $TO_HOST || -z $FROM_PORT ]]; then
echo "Usage: TO_PORT=1234 TO_HOST=other_host FROM_PORT=80 start.sh"
exit 1
fi
echo "I am "`whoami`
function update_port_forwarding {
FROM_IP=$(/sbin/ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}')
TO_IP=$(getent hosts $TO_HOST | awk '{print $1}')
echo "Fowarding port from local $FROM_PORT to $TO_IP:$TO_PORT"
iptables -F
iptables -t nat -F
iptables -X
iptables -t nat -A PREROUTING -p tcp --dport $FROM_PORT -j DNAT --to-destination $TO_IP:$TO_PORT
iptables -t nat -A POSTROUTING -p tcp -d $TO_IP --dport $TO_PORT -j SNAT --to-source $FROM_IP
}
update_port_forwarding
while inotifywait -e close_write /etc/hosts
do
update_port_forwarding
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment