Sample Header Ad - 728x90

Using iptables to redirect all docker outbound traffic back into container

1 vote
2 answers
2643 views
I've been stuck on this problem all day and am keeping my fingers crossed some iptables expert reads this and can help me please. I would like to force all my docker containers's outbound traffic to go through a socks5 proxy. This is the closest I've come:
iptables -t nat -N REDSOCKS
iptables -t nat -A REDSOCKS -s 172.20.0.0/16 -d 0.0.0.0/8 -j RETURN
iptables -t nat -A REDSOCKS -s 172.20.0.0/16 -d 10.0.0.0/8 -j RETURN
iptables -t nat -A REDSOCKS -s 172.20.0.0/16 -d 127.0.0.0/8 -j RETURN
iptables -t nat -A REDSOCKS -s 172.20.0.0/16 -d 169.254.0.0/16 -j RETURN
iptables -t nat -A REDSOCKS -s 172.20.0.0/16 -d 172.16.0.0/12 -j RETURN
iptables -t nat -A REDSOCKS -s 172.20.0.0/16 -d 192.168.0.0/16 -j RETURN
iptables -t nat -A REDSOCKS -s 172.20.0.0/16 -d 224.0.0.0/4 -j RETURN
iptables -t nat -A REDSOCKS -s 172.20.0.0/16 -d 240.0.0.0/4 -j RETURN

iptables -t nat -A REDSOCKS -s 172.20.0.0/16 -p tcp -j DNAT --to-destination 172.17.0.1:12345
iptables -t nat -A OUTPUT -s 172.20.0.0/16 -j REDSOCKS
iptables -t nat -A PREROUTING -s 172.20.0.0/16 -j REDSOCKS
It works almost perfectly, but the socks5 proxy is unable to tell the originating IP address. The remote address is always '127.0.0.1' Is there any way I can keep the originating IP address? # Example Scenario 1) I have applied the iptables rules above to my docker host 2) I have a docker container with the address 172.20.0.2 2) Inside that container, I do a curl to example.com 3) The traffic is forwarded to 172.17.0.1:12345 (the docker host machine) 4) The server running on 12345 shows the remote IP address as being '127.0.0.1' 5) I would like the remote IP address to show as 172.20.0.2 Thank to anyway who can try and help me with this.
Asked by Mark (231 rep)
Oct 5, 2020, 10:16 AM
Last activity: Jul 26, 2025, 08:08 PM