Ubuntu 18.04: Communication to server on localhost stops working after setting a port forwarding rule

muliku asked:

I have a Ubuntu 18.04 device with two network interfaces, ethernet and USB LTE modem. There is IP camera connected directly to the ethernet port and it has address I use the LTE interface for everything else – internet, ssh, etc. – it has static IP address (our company has its own APN).

My device has a Python app running that communicates with local Node.JS server on http://localhost/abc that communicates to my server via the LTE interface to https://myserver.com/app

The IP camera has its own web server for configuration purposes. In order to get to the camera’s config page I set a port forward rule so I can access the IP camera on

sudo sysctl net.ipv4.ip_forward=1
sudo iptables -t nat -A PREROUTING -p tcp --dport 8888 -j DNAT --to-destination
sudo iptables -t nat -A POSTROUTING -j MASQUERADE

It works fine and I can access the camera and shell all good. But the Python app stops communicating with the local Node.JS server with this error:

502 Server Error: Bad Gateway for url: http://localhost/abc My guess is that my port forward rule broke some ports that those two local apps were communicating trough. Any idea on how to fix that?

My answer:

Your MASQUERADE rule is wrong. It needs to specify the outbound interface, otherwise it will try to NAT all traffic. Since you have two interfaces to the Internet, it is OK to specify it twice. Each will apply only to traffic exiting that interface. For example:

iptables -t nat -A POSTROUTING -o enp4s0 -j MASQUERADE
iptables -t nat -A POSTROUTING -o wwp0s20f0u3 -j MASQUERADE

If you still get 502 errors after fixing this, check that your web application is actually running and listening on the port you expect. The usual cause of this error is the app is not running or listening on a different port.

P.S. If you are not working for La Jolla Baking Company in Plano, Texas, USA, you should use a different IP address block. They own the global address you used in your question. Using other people’s global IP addresses can also cause problems.

View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.