weberjn
Posts: 10
Joined: Sat Jan 13, 2018 9:55 pm
Location: Hohenlohe, Germany
Contact: Website

iptables port forwarding in Raspbian stretch

Sat Jan 13, 2018 10:04 pm

Hi,

I'd like to make Tomcat's port 8080 reachable on port 80.

I tried

Code: Select all

 sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080
but

Code: Select all

weberjn@pi:~ $ curl localhost:80
curl: (7) Failed to connect to localhost port 80: Connection refused
weberjn@pi:~ $ curl pi:80
curl: (7) Failed to connect to pi port 80: Connection refused
This used to work in Jessie.

How can I get iptables get to forward the port?

Thx,
Juergen


https://community.atlassian.com/t5/Conf ... q-p/218498

User avatar
allfox
Posts: 452
Joined: Sat Jun 22, 2013 1:36 pm
Location: Guang Dong, China

Re: iptables port forwarding in Raspbian stretch

Sun Jan 14, 2018 5:09 am

At the first glimpse, I thought this is an easy one. It's not. :)

DuckDuckGo taught me: https://serverfault.com/a/211544

Your command would work for connection coming from outside your Pi. But if you want to develop on the Pi itself, you would also need:
sudo iptables --wait --table nat --append OUTPUT --protocol tcp --dport 80 --jump REDIRECT --to-port 8080

This is because when packets are generated from local, they would travel the iptables differently than those from outside.
They won't pass through the PREROUTING chain: http://www.iptables.info/en/structure-of-iptables.html

weberjn
Posts: 10
Joined: Sat Jan 13, 2018 9:55 pm
Location: Hohenlohe, Germany
Contact: Website

Re: iptables port forwarding in Raspbian stretch

Sun Jan 14, 2018 8:08 pm

Thanks, that did the trick.

Actually, looks like you need both rules for outside access, too.

Greetings,
Jürgen

User avatar
allfox
Posts: 452
Joined: Sat Jun 22, 2013 1:36 pm
Location: Guang Dong, China

Re: iptables port forwarding in Raspbian stretch

Mon Jan 15, 2018 6:09 am

I think you only need PREROUTING for outside access.

The nat table works differently than the default filter table.
It only work on the very first packet of a connection. After that, there is an "NAT engine" would take care of the rest of the packets for the same connection: http://www.iptables.info/en/structure-o ... l#NATTABLE

So you don't need to manually write NAT rule for download and upload.
What we need is a trigger, which would make the "NAT engine" to do its job. The engine knows that a connection would have reply.

We do need rules for both directions in the filter table. They work in a different way.

"sudo iptables -nv --table nat --list" would show the packet counter hitting each rule, so we could see the nat table only work on one packet per connection.

Return to “General discussion”