Skip to content

Instantly share code, notes, and snippets.

@briceburg
Created April 9, 2020 16:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save briceburg/2796f4729bf88a368263e2ee1ca1ac90 to your computer and use it in GitHub Desktop.
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)
#!/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