Port forwarding on Ubuntu using iptables

April 13, 2022

Problem

Recently, I was working on setting up port forwarding on Ubuntu in order to bypass the port restriction policy within the firewall.

Solution

To solve this, I learned that I could use iptables to forwarding the IPv4 traffic within my server to eliminate the need of moving the network encryption services to listen to another port.

The whole process now looks like this, assuming the following:

  • Server IP is x.x.x.x
  • Incomming port is 3000
  • Target port is 443
<Incomming Traffic> --> x.x.x.x:3000 --(iptables)--> x.x.x.x:443

Step 1

Enable the IPv4 traffic forwaring option in the kernel config and apply the setting.

echo -e "net.ipv4.ip_forward=1" >> /etc/sysctl.conf
sysctl -p

Step 2

Setting up the iptables.

iptables -t nat -A PREROUTING -p tcp --dport 3000 -j REDIRECT --to-port 443
iptables -t nat -A PREROUTING -p udp --dport 3000 -j REDIRECT --to-port 443

Ending

The port forwarding should works by now until next reboot. To persistent such rule, consider using iptables-save packages.