I recently had the use case for needing to forward all traffic on certain ports temporarily to a Docker container. I made a Visual Regression toolkit where I was deploying a stack of applications and during a specific time period I needed to forward all web traffic to one container from another.
At first I approached the problem with a well-known tool dnsmasq and that worked well but was extra bloat and difficult to undo once dns traffic was forwarded. I wanted something simpler.
It turns out this was extremely easy with iptables. To forward all http(80) and https(443) traffic to a single IP you can simply add
--cap-add=NET_ADMIN to your container's run command. E.g.
docker run -it --rm --cap-add=NET_ADMIN ubuntu bash
If you are playing along with docker you will need to install iptables in the docker first.
iptables -t nat -A OUTPUT -p tcp --dport 80 -j DNAT --to-destination <IPADDRHERE>:80 iptables -t nat -A OUTPUT -p tcp --dport 443 -j DNAT --to-destination <IPADDRHERE>:443
-t natAdd the following rule to the NAT table
-A OUTPUTThis rule will be appended to the outbound traffic rule
-p tcpOnly apply this rule to tcp traffic
-j DNATChange destination of packets for locally generated packets
Remove forward rules
If you want a list of the rules you added you can see them with
iptables -L -n -t nat and to remove all rules from the nat table you can simply run
iptables -t nat -F