Flash Sale:75% Off Hosting + Free DomainEnds in13h47m14sView Plans
Hostvento logoHostvento

Forward Ports with iptables on Linux

Send traffic that arrives on one port to another port or another machine.

Firewall2 min read8 screenshots

What port forwarding is

Port forwarding sends traffic that arrives at one address and port to a different address and port. You can use it to reach a service on a private machine, or to move traffic from port 80 to a port such as 8080.

iptables does this with NAT rules (Network Address Translation).

Step 1: Install iptables

sudo apt install iptables
Installing iptables

Step 2: Turn on IP forwarding

Open the file:

sudo nano /etc/sysctl.conf

Add or uncomment this line:

net.ipv4.ip_forward=1
Enabling IP forwarding

Load the setting:

sudo sysctl -p
Applying the setting

List the current rules:

sudo iptables -L -n
The current iptables rules

Step 3: Add the forwarding rule

The general form:

sudo iptables -t nat -A PREROUTING -p tcp --dport <original-port> -j DNAT --to-destination <destination-ip>:<new-port>

Example: send port 80 to port 8080 on the machine 192.168.0.121:

sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to-destination 192.168.0.121:8080
The forwarding rule

If you forward to another machine, add a masquerade rule too, so that the replies come back through this server:

sudo iptables -t nat -A POSTROUTING -j MASQUERADE

Also allow the forwarded traffic if your FORWARD chain drops by default:

sudo iptables -A FORWARD -p tcp -d 192.168.0.121 --dport 8080 -j ACCEPT

Step 4: Save the rules

Rules are lost at a reboot unless you save them. Install the saving tool first with sudo apt install iptables-persistent. Then:

sudo netfilter-persistent save && sudo netfilter-persistent reload
Saving the rules

Step 5: Check the rules

sudo iptables -t nat -L -n -v
The NAT table

Step 6: Test

From another machine, request the address:

curl 192.168.0.121
Testing the forwarded port

Quick recap

  • Turn on net.ipv4.ip_forward.
  • Add a DNAT rule in the nat table.
  • Save the rules so they survive a reboot.