iptables setup notes

Published: Wednesday, 24 June 2020
linux iptables

iptables can be used to manage firewalls in Linux.

Chain management

A chain contains a list of rules.

Creating a new chain

# iptables --new USER-FOO

The -N switch can be used instead of --new

Listing rules in a chain

# iptables --list USER-FOO

The -L switch can be used instead of --list

It will return 1 if the chain does not exist.

iptables: No chain/target/match by that name.
# echo $?

If it is empty it will be successful.

Chain USER-FOO (0 references)
target     prot opt source               destination
# echo $?

To display more details, add --numeric or -n for numeric IPs, add --verbose or -v to show packet and byte counts.

# iptables --list USER-FOO --numeric --verbose

Deleting a chain

# iptables --delete-chain USER-FOO

The -X switch can be used instead of --delete-chain


A chain consists of an ordered list of rules. Each rule can be referred by its ordinal or rulenum within a chain. Rules are numbered starting from 1.

Each rule has a specification.

For a packet to match a rule and perform an action, the packet is matched against the rule-specification.

Rule-specification can include tests such as

Rule-specifications can include an action such as

conntrack: connection tracking module

The conntrack module is useful for packets that have already been NATed, such as those seen in DOCKER-USER after docker is installed.

To enable this module on a rule, -m conntrack must be added to the rule specification.

Rule-specification now has additional options available when using this module.

To exit the chain when a packet matches 333.333.333.333:25

iptables -A DOCKER-USER -j RETURN -p tcp -m conntrack --ctstate NEW,RELATED,ESTABLISHED --ctorigdst 333.333.333.333 --dport 25

See the man page iptables-extensions for more details.


Packets flow in the original or reply direction. Rules usually block packets in the original direction only.

To append a rule allowing reply packets in the DOCKER-USER chain, run:

iptables -A DOCKER-USER -j RETURN -p tcp -m conntrack --ctdir REPLY

Chain and Rule Ordering - Whitelist

To configure a chain to behave like a whitelist

  1. Add rules that jump to RETURN if the packet matches. The previous chain should be configured to ACCEPT the packets.
  2. Add a final rule in the chain that DROPs the packet