in Security

Port forwarding with iptables

In this tutorial we’ll set up a simple port forwarding (NAT) using iptables.

1. Enable ip forward

echo "1" > /proc/sys/net/ipv4/ip_forward

2. Append routing rules to the nat table

iptables -t nat -A PREROUTING -p tcp -s 0/0 -d {local_ip} --dport {local_port} -j DNAT --to {destination_ip}:{destination_port}
iptables -t nat -A POSTROUTING -o eth0 -d {destination_ip} -j SNAT --to-source {local_ip}

  • {local_ip}: A ip address mapped on the local system
  • {local_port}: The port you would like to listen on
  • {destination_ip}: Destination ip address
  • {destination_port}: Destination port

3. Now you can access http://{local_ip}:{local_port} and would actually be getting response from http://{destination_ip}:{destination_port}

A working example

If the ip address of your system is and you import the following rules, you would be able to connect to and actually see the Google search engine because is one of Google’s web servers.

iptables -t nat -A PREROUTING -p tcp -s 0/0 -d --dport 8080 -j DNAT --to
iptables -t nat -A POSTROUTING -o eth0 -d -j SNAT --to-source

Write a Comment


  1. I have been working with iptables for a while. Forgot the SNAT and had major issues getting port fwd to a Xen machine up and running. Kicked myself when I read your post.

    You saved me another few hours of not thinking. Thanks from Cape Town South Africa.

  2. Thank you very much!
    That work very well! You helped a lot 🙂

  3. I read your article thought might ask you, i am have dom0 on with one eth0 on public ip, the xen vm is on private ip nat, all works okay.
    but when i try to to put prerouting rule for port 3389 to forward to vm from external it doesnt work.
    firewall on windows vm is off. I can ping windows vm from dom0 and also telnet to 3389.
    any idea ?

  4. I’ve successfully setup port forwarding using example provided.
    didn’t know that destionation and source for pre and post route differs in that way. Thanks guys.