Monday, 27 November 2017

Setting up port forwarding on Ubuntu 16.04

Here we demonstrate how to set up port forwarding on a VPS with Ubuntu 16.04, so that we can use this VPS as an Internet traffic forwarding service. This setup is useful when the route between the source and the destination IPs is bad, but the intermediate VPS has good connections to both the source and the destination.

First, set the net.ipv4.ip_forward=1 flag in the /etc/sysctl.conf file with vi, and use the following command to make it effective immediately:
sysctl -p
Next, say we want to use port 50000 to forward both TCP and UDP traffic to We use the following iptables commands:
iptables -t nat -A PREROUTING -p tcp -m tcp --dport 50000 -j DNAT --to-destination
iptables -t nat -A PREROUTING -p udp -m udp --dport 50000 -j DNAT --to-destination
iptables -t nat -A POSTROUTING -d -p tcp -m tcp --dport 40000 -j SNAT --to-source
iptables -t nat -A POSTROUTING -d -p udp -m udp --dport 40000 -j SNAT --to-source
In the command above, is the private IP of the intermediate VPS. We can use the following command to check if we set up the NAT table correctly:
iptables -L -n -t nat
Finally, to make the iptables settings persistent, install:
apt-get install iptables-persistent
To save any additional changes to the NAT table, run:
netfilter-persistent save

No comments:

Post a Comment