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

Forwarding Traffic

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 nat Add the following rule to the NAT table
  • -A OUTPUT This rule will be appended to the outbound traffic rule
  • -p tcp Only apply this rule to tcp traffic
  • --dport Destination port
  • -j DNAT Change destination of packets for locally generated packets

Great iptables introduction

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