How to Add Iptables Firewall Rules

Iptables is the software firewall that is included with most Linux distributions by default. This post guide provides a quick reference to iptables commands that will create firewall rules for everyday scenarios.

Allow Loopback Connections

The loopback interface, also referred to as lo, is what a computer uses to forward network connections to itself. For example, if you run ping localhost or ping, your server will ping itself using the loopback. The loopback interface is also used if you configure your application server to connect to a database server with a “localhost” address. As such, you will want to be sure that your firewall is allowing these connections.

To accept all traffic on your loopback interface, run these commands:

sudo iptables -A INPUT -i lo -j ACCEPT
sudo iptables -A OUTPUT -o lo -j ACCEPT

Allow Established and Related Incoming Connections

As network traffic generally needs to be two-way—incoming and outgoing—to work properly, it is typical to create a firewall rule that allows established and related incoming traffic, so that the server will allow return traffic to outgoing connections initiated by the server itself. This command will allow that:

sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

Allow Established Outgoing Connections

You may want to allow outgoing traffic of all established connections, which are typically the response to legitimate incoming connections. This command will allow that:

sudo iptables -A OUTPUT -m conntrack --ctstate ESTABLISHED -j ACCEPT

Block an IP Address

To block network connections that originate from a specific IP address, for example, run this command:

sudo iptables -A INPUT -s -j DROP

In this example, -s specifies a source IP address of “”. The source IP address can be specified in any firewall rule, including an allow rule.

If you want to reject the connection instead, which will respond to the connection request with a “connection refused” error, replace “DROP” with “REJECT” like this:

sudo iptables -A INPUT -s -j REJECT

Allow Specific Inbound Port

If you want to allow https inbound from anywhere, you can use the follow:

sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT

If you want to allow https inbound only from a specific IP Address (in this case you can use the following:

sudo iptables -A INPUT -p tcp -s --dport 443 -j ACCEPT

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.