How to forward a port with iptables
Forward incoming traffic from one port to another host or port using iptables DNAT and PREROUTING rules.
How to forward a port with iptables
Forward incoming traffic from one port to another host or port using iptables DNAT and PREROUTING rules.
Prerequisites
- Root access on a Linux system with iptables.
- IP forwarding enabled (
net.ipv4.ip_forward = 1).
Step-by-Step: Forward a Port with iptables
Enable IP forwarding:
sudo sysctl -w net.ipv4.ip_forward=1Add a DNAT rule to the PREROUTING chain. iptables redirects incoming TCP traffic on port 8080 to an internal host on port 80:
sudo iptables -t nat -A PREROUTING -p tcp --dport 8080 -j DNAT --to-destination 192.168.1.100:80Add a FORWARD rule to allow the forwarded traffic:
sudo iptables -A FORWARD -p tcp -d 192.168.1.100 --dport 80 -j ACCEPTAdd a MASQUERADE rule so return traffic routes correctly:
sudo iptables -t nat -A POSTROUTING -j MASQUERADE
How to Verify Port Forwarding with iptables
List the NAT rules to confirm the DNAT entry:
sudo iptables -t nat -L -n -vTest from an external client:
curl http://{SERVER_PUBLIC_IP}:8080