Debian Tutorials

Debian Tutorials

Step by step tutorials showing you how to install and configure various applications and services on Debian based Linux distros.

June 2024


Port forwarding with iptables

Ástþór IPÁstþór IP

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}

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

Comments 4
  • Riaan
    Posted on

    Riaan Riaan


    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.

  • dan
    Posted on

    dan dan


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

  • stonehedge_11
    Posted on

    stonehedge_11 stonehedge_11


    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 ?

  • nrhm
    Posted on

    nrhm nrhm


    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.