Port forwarding is essential when you need to expose internal network services like web servers or SSH from behind a NAT or firewall to the public internet. Using iptables, a built-in Linux firewall tool, you can securely route incoming traffic to specific internal IPs and ports.
This guide walks you through setting up port forwarding with iptables on Ubuntu or Debian based systems, ensuring your services remain accessible and protected. By the end, you’ll have a persistent, working configuration that safely forwards traffic to the right internal resource.
If you have a fresh VPS you’ll want to start by ensuring iptables is installed and that your system is current. Use the alias we set up in our .bashrc file guide to update your system or run the command below to update, upgrade and install iptables and iptables persistent on your VPS.
sudo apt update && sudo apt upgrade && apt install iptables iptables-persistent
To enable you system to route traffic between different network interfaces you’ll need to enable IP forwarding in the configuration file, follow on from below.
1. Start off by opening the configuration file in nano text editor using the below command.
nano /etc/sysctl.conf
2. Now from within the config file search for the line below and update it as shown.
net.ipv4.ip_forward=1
3. From nano save the file with CTRL+X
and then Y
4. Finally, apply the change to the config file with the command below.
sudo sysctl -p
Before making any changes to iptables, inspect any existing rules to ensure that they’re all compatible, avoiding any unwanted conflicts. You can do this with the command below:
sudo iptables -L -n
So far in this guide you’ve configured iptables and checked for any rule conflicts, now its time to set up port forwarding rules that will forward external traffic to an internal IP and port.
The examples below shows how you can route external traffic from port 80 to 192.168.1.1 on port 9086. You can change this as you need to.
sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to-destination 192.168.1.1:9086
To verify that you’ve made those changes correctly and those port forwarding rules are in place, you can use the command below to check that PREROUTING values match your specified IP and port.
sudo iptables -t nat -L -n -v
As a final step you’ll want to verify that those forwarding rules work externally, we can test access to the forwarded service with cURL and if the service responds correctly then port forwarding is working as intended.