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, 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.
Start by ensuring iptables is installed:
sudo apt install iptables
To allow your system to route traffic between network interfaces, IP forwarding must be enabled.
sudo nano /etc/sysctl.conf
net.ipv4.ip_forward=1
sudo sysctl -p
It’s good practice to inspect existing rules before making changes:
sudo iptables -L -n
This helps identify active rules and avoid potential conflicts.
To forward external traffic to an internal IP and port, use the following structure:
sudo iptables -t nat -A PREROUTING -p tcp --dport [external-port] -j DNAT --to-destination [internal-ip]:[internal-port]
Example: To forward external traffic on port 80 to internal IP 192.168.0.121
on port 8080
:
sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to-destination 192.168.0.121:8080
iptables rules are not permanent by default and will reset after a reboot. To preserve them:
sudo apt install iptables-persistent
sudo netfilter-persistent save && sudo netfilter-persistent reload
To confirm your port forwarding rules are in place:
sudo iptables -t nat -L -n -v
Review the output to ensure your PREROUTING rules match the expected IP and port.
From an external system, test access to the forwarded service:
curl [your-public-ip]
If the service responds as expected, your port forwarding setup is complete and functional.