VPS Hosting

VPS Hosting

Buy Now

How to forward ports with iptables

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.

Install iptables

Start by ensuring iptables is installed:

sudo apt install iptables

Enable IP Forwarding

To allow your system to route traffic between network interfaces, IP forwarding must be enabled.

  • Open the configuration file:
sudo nano /etc/sysctl.conf
  • Add or update the following line:
net.ipv4.ip_forward=1
  • Save the file, then apply the changes:
sudo sysctl -p

View Current iptables Rules

It’s good practice to inspect existing rules before making changes:

sudo iptables -L -n

This helps identify active rules and avoid potential conflicts.

Add a Port Forwarding Rule

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

Make iptables Rules Persistent

iptables rules are not permanent by default and will reset after a reboot. To preserve them:

  • Install persistence package (if not installed):
sudo apt install iptables-persistent
  • Save and reload the current rules:
sudo netfilter-persistent save && sudo netfilter-persistent reload

Verify NAT Table Rules

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.

Test the Configuration

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.