TransWikia.com

iptables port redirect with Docker

Server Fault Asked by Jamescun on February 5, 2021

I have a web service running on port 8080, which is made available on port 80 through iptables like so:

iptables -t nat -A OUTPUT -p tcp -d 127.0.0.0/8 --dport 80 -j REDIRECT --to-port 8080

This works, however attempting to reach 127.0.0.1:80 inside a Docker container fails. I assume this is because lo within the container is a separate device inside a network namespace. Thus I attempted to do the following:

iptables -t nat -A OUTPUT -p tcp -d 172.17.0.0/16 --dport 80 -j REDIRECT --to-port 8080

where 172.17.0.0/26 is the range assigned to the docker0 bridge interface. Connections to 172.17.42.1:80 (the IP assigned to docker0) still fail inside the container.

There are no firewall rules other than the standard set created by Docker.

Why is this forwarding rule still failing?

Versions:

  • Ubuntu 14.04 (3.13.0-36-generic)
  • Docker 1.2.0

2 Answers

In the end, I fixed this by using a slightly different range and inserting a PREROUTING rule before dockers.

iptables -t nat -I PREROUTING 1 -p tcp -d 172.16.0.0/16 --dport 80 -j REDIRECT --to-port 8080

Answered by Jamescun on February 5, 2021

Your first rule redirects anything in the 127.0.0.0/8 network to the local webservice, instead of what you probably intentioned to be things directed at lo.

Assuming you lo interface has IP 127.0.0.1 (which it almost certainly does) try this instead:

iptables -t nat -A OUTPUT -p tcp -d 127.0.0.1 --dport 80 -j REDIRECT --to-port 8080

Answered by GregL on February 5, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP