Iptables configuration examples

As Linux systems become popular, it may be used as gateway in small networks.
This is the case when iptables – standard Linux firewall will come in handy.

You can easily set up simple NAT-ed network with few simple command lines.

Basic syntax: iptables -t *table* *command*

-L – list rules
-F – flush all rules
-A – add rule
ex: iptables -t *table* -A *chain* *rule*
-D – delete rule

For example: iptables -t *table* -D *chain* *rule number*

To make current ruleset persistent, run:

 /etc/init.d/iptables save

So let’s imagine we have a simple netork (at home), with a Linux host, Internet gateway (cable modem or similar) and a PC host (running Windows for example).

Before setting up iptables, we need to allow Linux kernel to forward packets (Turned Off by default):

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

For setting this automatically each boot, we need to uncomment 1 line in /etc/sysctl.conf :

  • 1. Internet Access
  • Assuming eth0 is connected to the ISP with IP-address With default gateway (ISP modem or similar).
    eth1 is connected to PC workstation, which needs to access Internet via Linux host.
    eth1 has IP-address
    PC workstation has one interface, with IP –

    Setting up Internet access from

    iptables -t nat -A POSTROUTING -s -o eth1 -j MASQUERADE

    Or, if you have multiple PC-s, use a subnet mask and allow access for the whole network:

    iptables -t nat -A POSTROUTING -s -o eth1 -j MASQUERADE

  • 2. Port forwarding
  • Imagine Workstation PC has ftp server running on, port 21, and we need to allow it to be accessible from the Internet.
    External address is –, ftp server IP –, TCP port – 21.

    iptables -t nat -A PREROUTING --dst -p tcp --dport 21 -j DNAT --to-destination
    iptables -I FORWARD -i eth0 -o eth1 -d -p tcp -m tcp --dport 21 -j ACCEPT

    First rule adds a network translation entry to NAT table(-t nat), it diverts packets, sent to port 21, from IP to
    Second rule is a firewall access rule, that allows packets to pass.

    To forward multiple ports at once, use colon – :

    iptables -t nat -A PREROUTING --dst -p tcp --dport 1024:65535 -j DNAT --to-destination
    iptables -I FORWARD -i eth0 -o eth1 -d -p tcp -m tcp --dport 1024:65535 -j ACCEPT

    This will forward all high ports from to

    Sometimes you don’t want to expose port 21 to outer network, you can change the external port to any other port, for example – 4321, so accessing will be translated to
    To achieve this enter following commands:

    iptables -t nat -A PREROUTING --dst -p tcp -m tcp --dport 4321 -j DNAT --to-destination
    iptables -I FORWARD -i eth0 -o eth1 -d -p tcp -m tcp --dport 21 -j ACCEPT


    Leave a Reply

    Your email address will not be published. Required fields are marked *