iptables Not Forwarding Port as Expected

Issue

I’m trying to get a basic Express application running on an AWS EC2 Ubuntu Linux instance.

On such systems, the server has to be run as a super user to listen to port 80. But that would be a bad practice, so instead you’re supposed to listen to a different port (eg. 3000) and redirect traffic from port 80 to 3000.

To forward the port I tried using this command from another Stack Overflow answer, Node.js + Express: app won't start listening on port 80):

sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 3000

I’ve run that command (and re-run it to be sure), but even so it doesn’t seem to be forwarding 3000 to 80, because I can only access my server on port 3000:

curl localhost:3000
*html*

curl localhost
curl: (7) Failed to connect to localhost port 80 after 0 ms: Connection refused

I have no idea what I did wrong, but I know nothing about iptables, so any help would be appreciated.

P.S. I’ve tried checking the iptables records with the command sudo iptables -L -n -v, but the results don’t say anything about ports (and again, I don’t know iptables), so I’m not sure if it’s saying my command worked or not:

Chain INPUT (policy ACCEPT 0 packets, 0 bytes) pkts bytes target
prot opt in out source destination

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes) pkts bytes target
prot opt in out source destination

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes) pkts bytes target
prot opt in out source destination

Solution

The reason your test doesn’t work is because trying to access the service from localhost bypasses the NAT table. You need to test from a different host. It should then work presuming the rule is loaded correctly and there is no firewall or other rules interfering.

Note, there are multiple other, probably better ways, to get get a non-privileged process bound to a privileged port. There is a big discussion in Is there a way for non-root processes to bind to "privileged" ports on Linux? which includes the solution your using among others.

Answered By – spinkus

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published