Created
April 9, 2020 16:50
-
-
Save briceburg/2796f4729bf88a368263e2ee1ca1ac90 to your computer and use it in GitHub Desktop.
forward local ports in a docker container to the docker host (host.docker.internal)
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
#!/usr/bin/env bash | |
main(){ | |
set -eo pipefail | |
# sysctl is a readonly filesystem in containers, so this must be set at run; | |
# [[ "$OSTYPE" =~ darwin|macos* ]] || docker_flags+=("--add-host host.docker.internal:host-gateway") | |
# docker run -it "${docker_flags[@]}" --cap-add=NET_ADMIN --sysctl net.ipv4.conf.all.route_localnet=1 ... | |
sysctl -w net.ipv4.conf.all.route_localnet=1 | |
docker_host_ip=$(getent ahostsv4 host.docker.internal | head -n1 | awk '{print $1}') | |
port_forward_start=8000 | |
port_forward_end=8999 | |
iptables -t nat -A OUTPUT -p tcp -m tcp -j DNAT \ | |
--dport $port_forward_start:$port_forward_end \ | |
--to-destination "$docker_host_ip:$port_forward_start-$port_forward_end" | |
iptables -t nat -A POSTROUTING -j MASQUERADE | |
"$@" | |
} | |
main "$@" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment