Securing Linux Firewalls: iptables vs nftables

php2shell patches (CVE-2026-109618 and CVE-2026-109619) for EOL PHP are out now. With sales replies slower than usual due to high demand, the fastest route to patched packages is to buy ELS for Runtimes online (opens in new tab). Read the patch FAQ

Go straight to an AI summary of this blog post instead

  • Summarize this post with Perplexity
  • Summarize this post with Gemini

Key Takeaways

  • nftables is the modern standard for Linux firewalls, superseding iptables on most major distributions.
  • A default deny policy, only opening necessary ports, and persisting rules across reboots are the foundations of a secure Linux firewall setup.
  • Firewall configuration is not a one-time task – regularly reviewing rules, monitoring logs, and keeping software updated is essential.

Misconfigured firewalls are a major cause of data breaches – and if you’re running Linux, getting this right matters. A Linux firewall is your first line of defense against unauthorized access, and the good news is Linux gives you powerful, flexible tools to lock things down fast. In this guide, you’ll learn the most effective Linux firewall options available, how to configure them step by step, and the best practices security teams rely on to keep systems protected.

Understanding Linux Firewalls

linux firewall traffic flow diagram

Linux firewalls regulate network traffic by inspecting packets against predefined security rules. This filtering is enforced at the kernel level via the Netfilter framework. For years, iptables was the industry standard for interacting with Netfilter, but it has largely been superseded by nftables, which offers better performance and a more streamlined syntax.
Today, nftables is the default backend for modern distributions like RHEL 9, Debian 11, and Ubuntu 22.04. However, many administrators prefer high-level frontend tools like UFW (Uncomplicated Firewall) or firewalld to manage these rules without writing complex syntax.

An Overview of iptables & nftables

iptables has been the go-to firewall solution for Linux users for decades. It operates through a series of tables and chains, where packets are evaluated against predefined rules to determine their fate. These rules can be configured to permit, deny, or manipulate traffic based on various criteria, such as source IP, destination port, or protocol type.

linux firewall rule evaluation flow

nftables is its modern successor, offering unified syntax, more efficient rule handling (especially for large rulesets), and a more maintainable design. On many modern distributions, iptables commands are implemented as a compatibility layer that translates to nftables under the hood.

Feature

iptables

nftables

Initial Release

2001

2014

Status

Legacy (still widely supported)

Default in most modern distros

Syntax

Separate commands per protocol (IPv4/IPv6)

Unified syntax for all protocols

Performance

Slower on large rulesets

More efficient rule evaluation

Ease of use

More complex, fragmented syntax

Cleaner, more readable syntax

Learn more about the differences between iptables and nftables.

How to Configure Your Linux Firewall

In this section, we will look at how you can configure a firewall on your Linux system using nftables and iptables.

⚠️ Warning: If you are configuring your firewall over a remote SSH connection, always ensure you have a rule allowing port 22 (SSH) and established connections before you set the default policy to DROP. Failure to do this will result in an immediate lockout.

Configure Your Linux Firewall with nftables

We’ll start with a basic nftables ruleset that allows SSH, HTTP, and HTTPS while blocking all other incoming traffic.

Step 1: Start and Enable nftables

On most modern distributions, nftables is available by default. The service is used to load saved rules at boot.

Enable it with:

sudo systemctl start nftables
sudo systemctl enable nftables

nftables service status systemctl

Step 2: Create a Table

nftables uses tables to organize rules. A table acts as a container for chains and rules.

The following command creates a table named my_firewall.

sudo nft add table inet my_firewall

inet: allows a single ruleset to apply to both IPv4 and IPv6 traffic.

Other address families include ip, ip6, arp, bridge, and netdev.

Step 3: Create a Chain (Safe Default Policy)

A chain is a sequence of rules that are evaluated in order.

We will create the chain named INPUT and start with policy accept to avoid lockout. We’ll switch to drop later.

sudo nft add chain inet my_firewall INPUT { type filter hook input priority 0 \; policy accept \; }

type filter hook input: applies rules to incoming traffic

priority 0: sets standard processing priority

policy accept: temporary safe default

Step 4: Add Essential Safety Rules

A rule defines specific criteria for matching network traffic and specifies an action to take (e.g., accept, reject, drop). Rules are evaluated top to bottom, so order matters – place your most specific rules first and broader rules last.

Let’s add rules required to keep your system accessible:

Allow loopback traffic (required for local processes to communicate):

sudo nft add rule inet my_firewall INPUT iif lo accept

Allow established and related connections (required for return traffic):

sudo nft add rule inet my_firewall INPUT ct state established,related accept

Allow SSH (port 22):

sudo nft add rule inet my_firewall INPUT tcp dport 22 accept

Step 5: Add Additional Rules

Now allow required services.

Allow ICMP (IPv4) and ICMPv6:

sudo nft add rule inet my_firewall INPUT ip protocol icmp accept
sudo nft add rule inet my_firewall INPUT ip6 nexthdr icmpv6 accept

Allow HTTP (port 80) and HTTPS (port 443):

sudo nft add rule inet my_firewall INPUT tcp dport { 80, 443 } accept

Step 6: Apply Secure Default Policy (DROP)

Once all required rules are in place, switch to a secure default policy.

sudo nft add chain inet my_firewall INPUT { policy drop \; }

This ensures all other traffic is blocked. At this point, only explicitly allowed traffic (SSH, HTTP, HTTPS) is permitted.

Step 7: Verify Your Rules

To check the active rules, use this command:

sudo nft list ruleset

Your output should look similar to this:

table inet my_firewall {
    chain INPUT {
        type filter hook input priority filter; policy drop;
        iif "lo" accept
        ct state established,related accept
        tcp dport 22 accept
        ip protocol icmp accept
        ip6 nexthdr ipv6-icmp accept
        tcp dport { 80, 443 } accept
    }
}

Step 8: Save Your Rules

Rules added via the command line are lost on reboot. Save them in a configuration file to persist across restarts:

sudo nft list ruleset | sudo tee /etc/nftables.conf > /dev/null

Reload manually if needed:

sudo nft -f /etc/nftables.conf

Configure Your Linux Firewall with iptables

We’ll set up a basic iptables firewall that allows SSH, HTTP, and HTTPS while blocking all other incoming traffic.

Step 1: Verify iptables is Available

iptables is available by default on most Linux distributions, including older and legacy systems like CentOS 7. If it is not installed, you can install it using the commands below.

On RHEL-based systems:

sudo dnf install iptables   # RHEL 8+/9, Rocky Linux, AlmaLinux
sudo yum install iptables   # CentOS 7

On Debian/Ubuntu-based systems, run:

sudo apt install iptables

Step 2: Checking Existing Rules

Before making changes, check what rules are already in place:

sudo iptables -L -v -n

Step 3: Add Essential Rules

As with nftables, rule order matters – iptables evaluates rules top to bottom.

Before locking down the firewall, you must allow the connections you currently need (like SSH) to avoid being locked out of your system.

Allow loopback traffic:

sudo iptables -A INPUT -i lo -j ACCEPT

Allow established and related connections:

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

Allow ICMP (ping):

sudo iptables -A INPUT -p icmp -j ACCEPT

If IPv6 is enabled on your system:

sudo ip6tables -A INPUT -p ipv6-icmp -j ACCEPT

Allow SSH (port 22):

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

Allow HTTP (port 80) and HTTPS (port 443):

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

Step 4: Set Default Policies

Set the default policy to drop all incoming and forwarded traffic, while allowing outgoing traffic:

sudo iptables -P INPUT DROP
sudo iptables -P FORWARD DROP
sudo iptables -P OUTPUT ACCEPT

Step 5: Verify Your Rules

Check that your rules are active:

sudo iptables -L -v -n

Step 6: Save Your Rules

On Debian/Ubuntu-based systems:

sudo apt install iptables-persistent
sudo netfilter-persistent save

This saves rules to /etc/iptables/rules.v4 (and rules.v6 for IPv6) and reloads them on reboot.

On modern RHEL-based systems (RHEL 8/9, Rocky Linux, AlmaLinux):

On these systems, if you are using firewalld instead of raw iptables:

sudo firewall-cmd --runtime-to-permanent

On RHEL 7 (and optionally RHEL 8/9 when using legacy iptables):

If you are using raw iptables commands instead of a frontend like firewalld, you must install the iptables-services package to make them persistent:

sudo dnf install iptables-services
sudo systemctl enable iptables
sudo service iptables save

This saves rules to /etc/sysconfig/iptables and ensures they reload on reboot.

How to Troubleshoot Firewall Configuration Issues

Firewall configuration issues can disrupt your connections and leave services inaccessible. Before diving into troubleshooting steps, let’s understand the most common issues to know what you’re likely dealing with.

  • Blocked Services: Legitimate services or applications getting blocked unintentionally
  • Rule Conflicts: Overlapping or contradictory rules causing unexpected behavior
  • Open Ports / Exposed Services: Ports or services exposed unintentionally due to misconfiguration
  • Performance Degradation: Excessive or poorly ordered rules slowing down network traffic

Here’s how to troubleshoot them:

1. Check Firewall Status

Use commands like firewall-cmd --state, iptables -L, or ufw status to check the current status of your firewall.

Pro Tip: For a more detailed view of active rules and packet counts, use iptables -L -v -n or nft list ruleset – these show you exactly what’s being matched and how often.

2. Review Active Rules

Carefully examine current rules to ensure they match your intended traffic policies. Misconfigured rules are a common source of problems.

3. Test Network Connectivity

Use tools like ping, traceroute, or netcat to test connectivity to both internal and external resources. This helps pinpoint blocked traffic.

4. Examine Firewall Logs

Check firewall logs for dropped packets or system messages depending on your firewall setup.

sudo journalctl -u firewalld
sudo journalctl -u nftables (only if nftables service logging is enabled on the system)

5. Temporarily Disable the Firewall

Temporarily disable the firewall to confirm if it is the source of the problem.

To temporarily stop the service:

sudo systemctl stop firewalld
sudo systemctl stop nftables
sudo ufw disable

⚠️ Warning: Only do this in a controlled environment or on a non-production system. Re-enable the firewall immediately after testing.

Linux Firewall Configuration: Our 7 Top Tips

Configuring a firewall on Linux can have a bit of a learning curve, but with the right approach, you can simplify the configuration process. Here are seven practical tips that will help you streamline your firewall settings and improve your system security.

Tip 1: Define Your Security Policy Before You Configure

Before touching a single command, know what you’re protecting and from what. Identify which services need to be publicly accessible, which should be restricted to specific IP ranges, and whether unknown traffic should be dropped silently or rejected with a response. A clear security policy turns firewall configuration from guesswork into deliberate, auditable decisions.

Tip 2: Start with a Simple Policy

Begin with a default deny-all policy and explicitly allow only what is necessary. However, before applying this rule, ensure your SSH connection is explicitly allowed to avoid locking yourself out of the system. This safeguards your access before blocking everything else.

default deny vs default allow firewall policy

Tip 3: Only Open Necessary Ports

Every open port counts as a potential entry point for attacks, so be cautious about which ports you leave open. You can restrict access to only the ports required for your applications or services, and close any that are not in use.

To audit what ports are currently exposed on your system, run:

sudo ss -tulnp

Tip 4: Control Outgoing Traffic Too

While much emphasis is placed on blocking incoming traffic, monitoring and controlling outgoing traffic is equally important in some environments. An unrestricted, compromised system inside your network can exfiltrate data or communicate with attacker-controlled servers without any inbound rules stopping it. At minimum, log outgoing traffic from sensitive services to detect unusual behavior early.

Tip 5: Use Zones or Chains for Organization

Organize your firewall rules with zones (firewalld) or chains (iptables, nftables). This lets you apply different rules based on network interfaces or trust levels. Structured rules make configurations easier to manage and reduce the chance of errors.

Tip 6: Regularly Review and Test Rules

Firewall rules should not be “set and forget.” Periodically review them to ensure they meet current requirements. After any change, test thoroughly to confirm your rules function as intended without accidentally blocking legitimate traffic. A good habit is scheduling a quarterly review as part of your broader security maintenance routine.

Tip 7: Keep Your Firewall Software Up to Date

Stay on top of updates for firewall tools you use like nftables, UFW, or firewalld. Updates often include security patches and stability improvements that are essential for maintaining effective firewall protection.

Our Top 5 Recommended Linux Firewall Solutions

There are tons of options out there, from simple tools for beginners to advanced firewall solutions. We have put together a list of the five most relevant Linux firewall tools you will find in 2026, whether you like things straightforward or need robust, feature-rich protection.

1. iptables

iptables has been a workhorse in Linux networking for many years. It gives you fine control over network traffic with its rule-based system, which is why expert users often like it. Though now largely superseded by nftables in modern systems, it is still relevant and widely used, especially on older systems and in compatibility setups.

Key Features:

  • Granular rule chains for precise traffic management.
  • Extensive documentation and community support.
  • Best suited for backward compatibility on older Linux systems.

Availability: Pre-installed on many older Linux distributions.

Example:

Block incoming traffic from a specific IP:

sudo iptables -A INPUT -s 192.168.1.10 -j DROP

2. nftables

nftables is the modern standard in Linux firewall management, replacing iptables with a cleaner syntax, better performance, and unified IPv4/IPv6 support. It is used as the default backend in many modern Linux distributions.

Key Features:

  • Handles IPv4 and IPv6 in a single ruleset
  • Supports hardware acceleration for better performance.
  • Simplified syntax reduces configuration errors.

Availability: Open source; included in standard Linux repositories.

Example:

Block incoming traffic from a specific IP:

sudo nft add rule inet my_firewall INPUT ip saddr 192.168.1.10 drop

3. firewalld

firewalld provides a simpler, user-friendly interface for firewall management. Built on nftables, it uses zones to simplify rule organization. It is the default firewall in RHEL 7 and later, Fedora, and most RHEL ecosystem distributions such as AlmaLinux and CentOS Stream.

Key Features:

  • Zone-based rule management simplifies configuration for different interfaces.
  • Dynamic updates eliminate the need for service restarts.
  • GUI integration (e.g., Cockpit) makes it accessible to beginners.

Availability: Open source; included in standard Linux repositories.

Example:

Allow HTTP traffic permanently:

sudo firewall-cmd --add-service=http --permanent
sudo firewall-cmd --reload

4. UFW (Uncomplicated Firewall)

UFW is all about simplicity. Its command-line syntax makes rule configuration straightforward, and it is the default firewall tool on Ubuntu-based distributions. If you are new to Linux firewalls or managing a personal project, UFW is the easiest starting point.

Key Features:

  • Commands are easy to remember and use, even for beginners
  • Pre-built profiles simplify setup for common services
  • Ideal for small-scale or personal projects

Availability: Open source; included in standard Linux repositories.

Example:

Allow SSH and enable the firewall:

sudo ufw allow ssh
sudo ufw enable
sudo ufw status verbose

5. CSF (ConfigServer Security & Firewall)

CSF provides additional security features beyond basic packet filtering, including intrusion detection and login failure tracking. It is widely used in web hosting environments and integrates with cPanel, making it well-suited for administrators managing shared or dedicated servers.

Key Features:

  • Login failure detection for improved access control
  • Real-time alerts keep administrators informed of threats
  • Stateful packet filtering helps manage connection-based traffic inspection

Availability: Free download from the official ConfigServer website.

Example:

Block and allow specific IP addresses:

sudo csf -d 192.168.1.10   # block an IP
sudo csf -a 192.168.1.20   # allow an IP
sudo csf -r                # reload CSF rules

Additional Best Practices for Effective Linux Firewall Management

Regardless of the Linux firewall solution chosen, these additional practices address broader security considerations that can further strengthen your firewall setup:

  • Application-Level Filtering: Go beyond port and protocol rules by leveraging application-level filtering where supported to enforce security policies based on specific software or services. This provides more granular control, particularly useful when multiple services share the same port.
  • Enable Logging and Monitoring: Enable logging to track network traffic and detect potential security incidents. Regularly monitor firewall logs for anomalies and suspicious activity – catching unusual patterns early is often the difference between a minor incident and a serious breach.
  • Implement Intrusion Detection Systems (IDS): Supplement your firewall with intrusion detection and prevention tools to identify and respond to malicious activity. Tools like Fail2ban or Suricata work alongside your firewall, either automatically updating rules (in the case of Fail2ban) or alerting administrators (in the case of IDS tools like Suricata) in response to detected threats.
  • Network Segmentation: Segmenting networks into distinct zones contains breaches and limits the impact of security incidents. Even if one segment is compromised, segmentation prevents lateral movement across your entire network.
  • Back Up Your Firewall Configuration: Always back up your current ruleset before making significant changes. This ensures you have a working configuration to restore quickly if something goes wrong.
  • Restrict Management Access: Limit who can modify firewall rules by enforcing strict access controls. Use sudo policies or role-based access control to ensure only authorized administrators can make changes to firewall configurations.

Your Linux Firewall is Only as Strong as Its Configuration

A firewall is only effective when it is configured correctly. Choosing the right tool – whether iptables for legacy systems and compatibility use cases, nftables for modern distributions, or UFW and firewalld for simplicity – is just the starting point. The rules you define, the policies you enforce, and the practices you maintain over time are what determine whether your Linux environment is truly protected.

Security is a continuous process, and staying vigilant is key to mitigating risks in the ever-evolving threat landscape. Regularly reviewing your rules, monitoring logs, and keeping your firewall software updated ensure your defenses remain strong as your systems and requirements evolve.

If you want to go further, explore how rebootless patching can help you maintain a secure Linux environment without downtime – keeping your systems protected between maintenance windows without ever taking them offline.

Summary
Linux Firewall: Configuration, Tools, Best Practices & More
Article Name
Linux Firewall: Configuration, Tools, Best Practices & More
Description
Step-by-step guide on how to set up and manage a Linux firewall. Protect your system with best practices and modern tools.
Author
Publisher Name
TuxCare
Publisher Logo

Join 4,500+ Linux & Open Source Professionals!

2x a month. No spam.

Table of Contents
Get the open-source security answers you need

Join 4,500+ Linux & Open Source Professionals!

2x a month. No spam.