How to Install and Use nftables in Linux

Updated on 10 April, 2025
How to Install and Use nftables in Linux header image

nftables is a modern packet filtering framework for Linux that replaces iptables. It offers a unified and efficient way to manage firewall rules across multiple protocols like IPv4, IPv6, and ARP. To get started with it, you need to install and configure nftables in Linux, which provides better performance and a simpler configuration through a single interface instead of multiple tables like iptables.

This article explains how to install and configure nftables on Linux. You will set up basic firewall rules, manage network traffic, and implement common security policies.

Prerequisites

Before you begin, you need to:

nftables versus iptables

iptables works as the standard firewall management tool on Linux. However, Its limitations included a complex rule structure, performance inefficiencies, and the need for multiple tools to handle different protocols (IPv4, IPv6, ARP, and so on). To address these issues, nftables was introduced as a replacement, offering significant improvements in functionality, performance, and usability.

This section compares nftables and iptables, highlighting key differences in functionality, performance, and usability to explain why nftables is the preferred choice.

Feature iptables nftables
Packet Filtering Requires multiple tools to manage different protocols (iptables, ip6tables, arptables) Uses a unified approach with named tables and chains
Rule Syntax Forces users to write complex chain-based rules with multiple entries Offers a modern, table-based syntax that simplifies rule writing
Performance Processes rules sequentially, which can slow down large rule sets Uses optimized rule evaluation, reducing overhead
Atomic Rule Changes Requires flushing and reloading entire rule sets for modifications Supports atomic rule updates, preventing disruption
Logging Uses legacy logging targets (LOG and ULOG frameworks) Provides built-in logging with advanced tracing options (meta nftrace, log)
Connection Tracking Requires external conntrack modules Integrates connection tracking directly into the system
Multi-protocol Support Requires different commands for each protocol Manages all protocols with a single command set
Resource Usage Consumes more memory by duplicating rules Manages memory efficiently with a unified ruleset
Scripting & Automation Relies on shell scripting and manual rule management Supports JSON-based rule definition and direct scripting integration
Compatibility Runs on all distributions but follows a legacy architecture Works natively on modern systems while supporting iptables conversion

Install nftables on Linux

Follow the steps below to install nftables depending on your Linux distribution.

Install nftables on Ubuntu and Debian

Follow the steps below to install nftables package on Ubuntu and Debian.

  1. Update the server's package index.

    console
    $ sudo apt update
    
  2. Install nftables using the APT package manager.

    console
    $ sudo apt install nftables -y
    

nft Command Syntax

nft [ -nNscaeSupyjtT ] [ -I directory ] [ -f filename | -i | cmd ... ]
  • -n: Show rule numbers in output.
  • -N: Print more detailed output for rules.
  • -s: Show statistics for rules.
  • -c: Show chain name for each rule.
  • -a: Print the rule with its address family and protocol.
  • -e: Expand rule details.
  • -S: Print the ruleset (configuration).
  • -u: Enable update mode for dynamic changes.
  • -p: Print the current ruleset in a parsable format.
  • -y: Show detailed object types.
  • -j: Output in JSON format.
  • -t: Show output in table format.
  • -T: Show tokenized output.
  • -I directory: Use the specified directory for configuration files.
  • -f filename: Load rules from a file.
  • -i: Interactive mode to modify rules directly.
  • cmd ...: Command arguments to manipulate the nftables rules.

Manage the nftables System Service

The nftables service manages your firewall rules and ensures persistence across system reboots. Follow these steps to enable and start the nftables service on your system.

  1. Enable the nftables service to start at boot.

    console
    $ sudo systemctl enable nftables
    
  2. Start the nftables service.

    console
    $ sudo systemctl start nftables
    
  3. Verify the service status.

    console
    $ sudo systemctl status nftables
    

    Your output should be similar to the one below:

    ● nftables.service - Netfilter Tables
         Loaded: loaded (/usr/lib/systemd/system/nftables.service; enabled; preset: disabled)
         Active: active (exited) since Mon 2025-03-31 17:52:35 UTC; 5s ago
           Docs: man:nft(8)
        Process: 1838 ExecStart=/sbin/nft -f /etc/sysconfig/nftables.conf (code=exited, status=0/SUCCESS)
       Main PID: 1838 (code=exited, status=0/SUCCESS)
            CPU: 11ms
    
    Mar 31 17:52:35 nftables-03 systemd[1]: Starting Netfilter Tables...
    Mar 31 17:52:35 nftables-03 systemd[1]: Finished Netfilter Tables.

Tables, Chains, and Policies in nftables

In nftables, rules are organized into tables, which contain chains that define how traffic is processed. Each chain is associated with a hook (INPUT, OUTPUT, FORWARD) that determines when it is evaluated. Chains also have policies that define the default action when no explicit rule matches a packet.

nftables supports multiple address families for handling different network protocols:

  • inet: Unified handling for both IPv4 and IPv6.
  • ip: IPv4-only filtering.
  • ip6: IPv6-only filtering.
  • arp: ARP packet filtering.
  • bridge: Ethernet bridge packet filtering.
  • netdev: Packet filtering at the network device level.

Chain Hooks

Each chain in nftables is linked to a specific traffic type:

  • input: Controls packets destined for the local machine.
  • output: Manages packets leaving the machine.
  • forward: Handles packets routed through the machine.

Policy

Policy refers to the default action taken by a chain when no explicit rule matches a packet. The default policy for a chain determines whether traffic is accepted, dropped, or rejected when it doesn't match any specific rule.

  • policy accept - Allows all traffic by default (useful for testing or initial configurations).
  • policy drop - It discards unmatched packets (most secure, commonly used in production environments).
  • policy reject - Sends a rejection notice to the source (informative but reveals the presence of the server, which might not be ideal for security).
Warning
Using accept as the default policy is not recommended for production environments as it allows all traffic unless explicitly blocked.

Manage the Default nftables Configuration

Follow the steps below to explore the default configurations on your server.

  1. View the list of existing nftables rules.

    console
    $ sudo nft list tables
    

    Your output should be similar to the one below:

    table ip filter
    table ip6 filter
  2. View the default nftables configuration file.

    console
    $ cat /etc/nftables.conf
    

    Your output should be similar to the one below:

    ini
    #!/usr/sbin/nft -f
    
    flush ruleset
    
    table inet filter {
        chain input {
            type filter hook input priority 0; policy accept;
        }
        chain forward {
            type filter hook forward priority 0; policy accept;
        }
        chain output {
            type filter hook output priority 0; policy accept;
        }
    }
    

Configure Basic nftables Firewall Rules

Follow the steps below to configure and manage nftables rules to control network traffic on your Linux machine.

Create Initial Table and Chains

  1. Create a new firewall table for IPv4 and IPv6 traffic.

    console
    $ sudo nft add table inet my_table
    

    The above command creates a new table named my_table, that can process both IPv4 and IPv6 packets. Please replace my_table with your preferred table name. The inet family allows you to manage both protocols with a single set of rules.

    Note
    In this article my_table table name is used. Please replace my_table with your preferred table name.
  2. Add an input chain with a default accept policy.

    console
    $ sudo nft add chain inet my_table input { type filter hook input priority 0 \; }
    

    The above command creates a filtering chain that applies to incoming traffic. The type filter option designates it as a filtering chain, while hook input ensures it processes incoming packets. The priority 0 setting determines the execution order, with lower values running first.

  3. Create forward chain with default accept policy.

    console
    $ sudo nft add chain inet my_table forward { type filter hook forward priority 0\; }
    

    The above command creates a filtering chain that applies to forwarded traffic. The type filter option designates it as a filtering chain, while hook forward ensures it processes forwarded packets. The priority 0 setting determines the execution order, with lower values running first.

  4. Allow established connections to keep existing communications.

    console
    $ sudo nft add rule inet my_table input ct state established,related accept
    

    This rule uses connection tracking to manage traffic. The ct state option enables connection tracking, while established allows packets from existing connections.

Add, List, and Delete Rules

Follow the steps below to add, list, and delete nftables rules to control network access.

  1. Add a rule to block incoming traffic from a specific IP address:

    console
    $ sudo nft add rule inet my_table input ip saddr 192.0.2.10 drop
    

    The above command adds a rule to the my_table table, blocking incoming traffic from the IP address 192.0.2.10. The rule is applied to the input chain in the inet family.

  2. View all active nftables rules to verify configurations.

    console
    $ sudo nft list ruleset
    

    The above command lists all active nftables rules to verify your configurations.

  3. List the rules with handle numbers.

    console
    $ sudo nft list chain inet my_table input
    

    The above command lists the rules in the input chain of the my_table table, so you can reference a specific rule for removal.

    Your output should be similar to the one below:

    ini
    table inet my_table {
            chain input {
                    type filter hook input priority filter; policy accept;
                    ct state established,related accept
                    ip saddr 192.0.2.10 drop
            }
    }
    
  4. Identify the handle number from the output and delete the corresponding rule.

    console
    $ sudo nft delete rule inet my_table input handle 0
    

    The above command deletes the rule with the handle number 0 from the input chain of the my_table table.

Implement Essential Security Rules

  1. Allow SSH access to your server.

    console
    $ sudo nft add rule inet my_table input tcp dport 22 accept
    

    The above command adds a rule that matches the TCP protocol packets and targets to the destination port 22 (the default SSH port). It accepts matching packets, allowing SSH connections.

  2. Block a specific IP address that shows suspicious activity.

    console
    $ sudo nft add rule inet my_table input ip saddr 192.0.2.10 drop
    

    The above command adds a rule that matches the packets from the specified source IP address, drops them without notifying the sender, and prevents any access from that IP address.

  3. Allow HTTP traffic on port 80.

    console
    $ sudo nft add rule inet my_table input tcp dport 80 accept
    

    The above command adds a rule that matches TCP protocol packets targeting port 80 (the default HTTP port). It accepts matching packets, allowing web traffic to reach the server.

  4. Allow HTTPS traffic on port 443.

    console
    $ sudo nft add rule inet my_table input tcp dport 443 accept
    

    The above command adds a rule allows TCP traffic on port 443 (default for HTTPS). It ensures encrypted web traffic is allowed while blocking other types of traffic on this port.

  5. Drop all incoming other traffic.

    console
    $ sudo nft add rule inet my_table input ip daddr 0.0.0.0/0 counter drop
    

    The above command adds a rule that drops all incoming traffic by default while allowing only the preconfigured rules (SSH, HTTP, HTTPS). It effectively blocks unwanted access.

Enable NAT and Port Forwarding

  1. Enable NAT functionality in the Linux kernel by editing the /etc/sysctl.conf file using any text editor such as vim.

    console
    $ sudo vim /etc/sysctl.conf
    
  2. Uncomment the following line.

    ini
    ...
    # Uncomment the next line to enable packet forwarding for IPv4
    net.ipv4.ip_forward=1
    ....
    

    Save and close the file.

  3. Apply the changes.

    console
    $ sudo sysctl -p
    
  4. Create a new NAT table to handle network address translation (NAT) for your server.

    console
    $ sudo nft add table nat
    

    The above command creates a new nat table, where you can define NAT rules for translating addresses in outgoing traffic.

  5. Create a postrouting chain in the NAT table to process packets after routing.

    console
    $ sudo nft add chain nat postrouting { type nat hook postrouting priority 100 \; }
    
  6. Add a masquerading rule for your internal network to enable internet connection sharing.

    console
    $ sudo nft add rule nat postrouting ip saddr 192.0.2.0/24 oif enp1s0 masquerade
    

    This rule tells nftables to perform NAT (masquerading) for outgoing traffic from the 192.0.2.0/24 network. The oif enp1s0 part specifies that the rule applies to traffic leaving the enp1s0 interface, which is typically the network interface connected to the internet.

Save Rules Persistently Across Reboots

In this section, you will save nftables rules persistently across system reboots by saving them to the configuration file.

  1. Save your current firewall configuration to the /etc/nftables.conf file.

    console
    $ sudo nft list ruleset | sudo tee  /etc/nftables.conf
    

    The above command stores the current nftables rules to the /etc/nftables.conf file, ensuring that they can be restored after a reboot.

  2. Apply saved rules from the configuration /etc/nftables.conf file.

    console
    $ sudo nft -f /etc/nftables.conf
    

    Reloads the firewall rules from the saved configuration file (/etc/nftables.conf).

  3. Restart the nftables service.

    console
    $ sudo systemctl restart nftables
    

    This reloads the firewall rules and ensures they persist after reboots.

Advanced Rule Configuration

  1. Implement rate limiting for SSH connections.

    console
    $ sudo nft add rule inet my_table input tcp dport 22 limit rate 3/minute accept
    

    The above command adds a rule that targets SSH traffic (port 22), limits connections to 3 per minute, and accepts connections within the limit to help prevent brute force attacks.

  2. Configure port forwarding for web traffic.

    1. Create the prerouting chain in the nat table (if it doesn't exist).

      console
      $ sudo nft add chain ip nat prerouting { type nat hook prerouting priority 0 \; }
      
    2. Add the port forwarding rule.

      console
      $ sudo nft add rule nat prerouting tcp dport 80 dnat to 192.0.2.10
      

      The above command adds a rule that captures incoming HTTP traffic (port 80), forwards it to an internal server (192.0.2.10), and enables hosting internal web services.

  3. Enable logging for dropped packets.

    console
    $ sudo nft 'add rule inet my_table input log prefix "nftables-drop: " drop'
    

    The above command adds a rule that logs packets before dropping them, adds a custom prefix for easy filtering, helps troubleshoot connection issues, and stores logs in the system journal.

  4. Flush all the nftables rules.

    console
    $ sudo nft flush ruleset
    
    Warning
    Be cautious when flushing the ruleset, as this will remove all existing nftables rules, effectively resetting your firewall configuration

Conclusion

You have installed and configured nftables on Linux. You created tables, set up chains with different policies, and managed firewall rules. The nftables framework modernizes packet filtering by providing unified management of IPv4 and IPv6 traffic, atomic rule updates, and improved performance through optimized packet processing. With built-in features like connection tracking and advanced logging capabilities, nftables simplifies the complex task of network security management. Visit the official nftables wiki for more information and advanced configurations.

Comments

No comments yet.