How to Forward Ports With Iptables On A Linux Server

How to Set Up NAT and Forward Ports on Linux Servers Port forwarding is an essential tool for network admins, enabling internet traffic redirection from one IP address and port to another. Itโ€™s widely used to access services behind firewalls or NAT, such as hosting web servers or connecting to priva

Last updated 30 Nov 2026Also in: Dedicated Servers

How to Set Up NAT and Forward Ports on Linux Servers

Port forwarding is an essential tool for network admins, enabling internet traffic redirection from one IP address and port to another. Itโ€™s widely used to access services behind firewalls or NAT, such as hosting web servers or connecting to private network resources. Hereโ€™s a concise guide on using iptables to set up NAT and port forwarding in Linux.

Understanding iptables and Port Forwarding

iptables is a command-line utility for managing traffic rules in Linux. It operates on chains and tables to allow or block network packets.

Port forwarding is a NAT technique that redirects traffic from one IP:Port combination to another, making private services accessible externally.

Step-by-Step Guide to Set Up Port Forwarding

Step 1: Install iptables

First, ensure iptables is installed. On most systems, itโ€™s pre-installed. If not, use:

sudo apt install iptables

Step 2: Enable IP Forwarding

Enable packet forwarding by editing the sysctl.conf file:

sudo nano /etc/sysctl.conf

Add the following line:

net.ipv4.ip_forward=1

Apply the changes:

sudo sysctl -p

Step 3: Set Up Port Forwarding Rules

Use the PREROUTING chain in the nat table to redirect traffic. For example, to forward traffic from external 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

Step 4: Make Rules Persistent

By default, iptables rules are lost after a reboot. Save them using netfilter-persistent:

sudo apt install iptables-persistent

sudo netfilter-persistent save && sudo netfilter-persistent reload

Step 5: Verify Rules

Check the active iptables rules with:

sudo iptables -t nat -L -n -v

Step 6: Test Port Forwarding

Test the forwarding by accessing the service externally:

curl http://<external-io>:80

Conclusion

Port forwarding with iptables provides a robust way to manage traffic in Linux. By following these steps, you can efficiently configure NAT and forward ports to make internal services accessible while maintaining security.

cloud servers in kenyaservers