Website Vidya
SecurityStep-by-Step Guide

iptables Command in Linux: Manage Firewall Rules and Packet Filtering

Learn iptables command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

RR
Rajesh RayLead Systems Educator
Published:
10 min read
PDF Cheat Sheet
iptables Command in Linux: Manage Firewall Rules and Packet Filtering
AI Executive SummaryWebsiteVidya AI

10 min read

Learn iptables command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

Key Highlights
  • What iptables Does and When to Use It
  • Availability and Installation Across Linux Distributions
  • Command Syntax, Arguments, and Exit Status Codes
Grounded in full engineering runbookWebsiteVidya AI Engine

Interactive Builder for this Guide

Build your custom firewall syntax (iptables Command in Linux: Manage Firewall Rules and Packet Filtering)

Generated POSIX Command
sudo ufw allow port 443 proto tcp comment 'Production HTTPS'
UFW rule to ALLOW port 443/tcp.
Flag-by-Flag Breakdown
ufw allowallow matching inbound packets
port 443Match destination port 443
proto tcpFilter TCP transport traffic

The iptables command in linux has stood as the cornerstone of Linux network security and packet filtering for over two decades. Interfacing directly with the Linux kernel's Netfilter subsystem, iptables inspects, alters, redirects, and drops IPv4 packets as they traverse network interfaces.

Modern server administration demands strict perimeter defense: protecting open databases from unauthorized networks, enforcing default-deny ingress policies, and mitigating denial-of-service floods. By evaluating packet headers against organized tables and chains of ordered rules, iptables allows administrators to define granular security boundaries matching protocols, IP subnets, port ranges, interface devices, and connection tracking states.

While modern distributions are transitioning toward nftables as the underlying kernel subsystem, iptables remains ubiquitous. On contemporary enterprise systems (such as Debian, Ubuntu, and RHEL), iptables is typically provided via iptables-nft, a compatibility translation layer that converts familiar iptables command syntax into native nftables bytecode while maintaining complete operational backward compatibility.

Advertisement
iptables Command in Linux: Manage Firewall Rules and Packet Filtering — syntax, flags, and practical terminal workflow diagram
iptables Command in Linux: Manage Firewall Rules and Packet Filtering — command syntax, key options, and production workflow reference.

What iptables Does and When to Use It

Architecturally, iptables organizes packet inspection into tables based on operational purpose: the filter table (default packet filtering: INPUT, FORWARD, OUTPUT chains), the nat table (Network Address Translation: PREROUTING, POSTROUTING, OUTPUT chains), the mangle table (packet header alteration), and the raw table (bypassing connection tracking). Packets pass through hooks in the kernel network stack, traversing chains sequentially from rule 1 to rule N until a terminating target match occurs.

A critical component of iptables is the connection tracking module (conntrack). Instead of treating every packet as an isolated datagram, conntrack maintains a dynamic state table in kernel memory (/proc/net/nf_conntrack). Packets are classified into four states: NEW (initiating a connection), ESTABLISHED (associated with an active session), RELATED (initiating a secondary connection, like FTP data channels), or INVALID. This allows stateful firewalls to accept return traffic automatically with a single rule.

At the operating system level, iptables interacts with the Linux kernel networking stack through netlink sockets (AF_NETLINK), raw packet sockets, or standard POSIX resolver APIs. When running iptables in cloud instances or Kubernetes worker nodes, combining flags such as -t TABLE, -L, -A CHAIN, -I CHAIN [NUM] lets you bypass slow reverse DNS lookups and inspect numeric IPv4/IPv6 addresses and socket states directly.

Availability and Installation Across Linux Distributions

The iptables utility is packaged in iptables across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:

Advertisement

Before running administrative tasks or automation scripts, verify whether iptables is installed and inspect which binary path and version your shell resolves:

type -a iptables
iptables --version 2>/dev/null || man -f iptables

# Illustrative output (reviewed against documentation)
iptables is /usr/bin/iptables
iptables (iptables)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y iptables

# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y iptables

# Arch Linux
sudo pacman -S --noconfirm iptables

# Alpine Linux
sudo apk add --no-cache iptables

Command Syntax, Arguments, and Exit Status Codes

iptables [-t table] {COMMAND} chain [rule-specification]

The iptables syntax follows: iptables [-t TABLE] COMMAND CHAIN [MATCH_CONDITIONS] -j TARGET. If -t is omitted, iptables defaults to the filter table. COMMAND flags specify the table operation: -A (append rule to end of chain), -I (insert rule at specified position), -D (delete rule), -L (list rules), -F (flush all rules), and -P (set default chain policy).

MATCH_CONDITIONS filter packets by protocol (-p tcp/udp/icmp), source IP (-s), destination IP (-d), input interface (-i), output interface (-o), and port numbers (--dport/--sport). The -j (jump) flag directs matching packets to a TARGET, such as ACCEPT, DROP, REJECT, LOG, MASQUERADE, or DNAT.

  • 0 — Successful rule addition, deletion, modification, or table listing.
  • 1 — Operational error; invalid match condition, missing module, or permission denied.
  • 2 — Command-line syntax error, unrecognized table name, or malformed parameter.

Important Options and Flags Reference

Option / FlagLong Form / ArgumentTechnical Behavior and Purpose
-t TABLE--tableSpecifies the target Netfilter table to operate on (filter, nat, mangle, raw; default: filter).
-L--listLists all active rules in the specified chain or across the entire selected table.
-A CHAIN--appendAppends a new rule to the end of the specified chain.
-I CHAIN [NUM]--insertInserts a new rule at position NUM in the chain (defaults to position 1 if omitted).
-D CHAIN [NUM]--deleteDeletes a rule from the chain by its sequential line number or matching rule specification.
-F [CHAIN]--flushFlushes (deletes) all rules in the specified chain or entire table if no chain is named.
-P CHAIN TARGET--policySets the default policy for a built-in chain (e.g., iptables -P INPUT DROP).
-v--verboseEnables verbose rule listing, displaying packet and byte counters, interface bindings, and options.
-n--numericOutputs numeric IP addresses and port numbers instead of resolving hostnames and service names.

When inspecting active firewall configurations, always combine -L, -v, -n, and --line-numbers (e.g., sudo iptables -L -v -n --line-numbers). The --line-numbers flag displays index numbers needed for precise rule deletion (-D), while -n avoids hanging on slow DNS lookups.

Advertisement

Understanding the difference between -A (append) and -I (insert) is crucial. Because iptables evaluates rules from top to bottom and stops at the first terminating match, appending a rule with -A after a generic DROP rule will render the new rule ineffective. Use -I CHAIN 1 to position critical allow rules at the top of the chain.

When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.

Practical Basic and Advanced Usage Examples

1. List All Firewall Rules with Line Numbers and Packet Counters

Inspect all active filter rules with numerical addresses, interface bindings, and byte counters.

sudo iptables -L -v -n --line-numbers

# Illustrative output (reviewed against documentation)
Chain INPUT (policy ACCEPT 1420 packets, 112K bytes)
num   pkts bytes target     prot opt in     out     source               destination         
1     3410  250K ACCEPT     all  --  lo     *       0.0.0.0/0            0.0.0.0/0           
2    18200 2410K ACCEPT     all  --  *      *       0.0.0.0/0            0.0.0.0/0            ctstate RELATED,ESTABLISHED
3      450 27000 ACCEPT     tcp  --  eth0   *       0.0.0.0/0            0.0.0.0/0            tcp dpt:22 ctstate NEW

Chain FORWARD (policy DROP 0 packets, 0 bytes)
num   pkts bytes target     prot opt in     out     source               destination         

Chain OUTPUT (policy ACCEPT 12040 packets, 1850K bytes)
num   pkts bytes target     prot opt in     out     source               destination

The output lists INPUT, FORWARD, and OUTPUT chains, displaying packet counters, match parameters, and line numbers.

2. Allow Established and Related Inbound Connections (Stateful Inspection)

Configure stateful packet filtering so established TCP connections and related helper sessions are accepted automatically.

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

# Illustrative output (reviewed against documentation)
# Rule appended cleanly to the INPUT chain.

This fundamental stateful rule allows return traffic for outgoing requests initiated by the server without opening broad inbound ports.

3. Allow Incoming SSH Connections on Port 22

Permit new inbound SSH connections on TCP port 22 from any source IP address.

sudo iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -j ACCEPT

# Illustrative output (reviewed against documentation)
# Rule added to allow incoming SSH connections.

The rule filters for TCP destination port 22 in the NEW connection tracking state, allowing initial SSH handshakes.

4. Block a Specific Malicious IP Address or Subnet

Drop all incoming traffic originating from a known attacker IP address or CIDR network block.

sudo iptables -I INPUT 1 -s 198.51.100.42 -j DROP

# Illustrative output (reviewed against documentation)
# Malicious IP blocked at position 1 of INPUT chain.

The -I INPUT 1 syntax places the drop rule at the very top of the chain, ensuring packets from 198.51.100.42 are discarded immediately.

5. Delete a Firewall Rule by Line Number

Remove an obsolete firewall rule from the INPUT chain using its line index.

sudo iptables -D INPUT 4

# Illustrative output (reviewed against documentation)
# Rule at line 4 removed from INPUT chain.

The -D INPUT 4 command deletes the fourth rule in the INPUT chain, shifting subsequent rules up by one position.

6. Configure NAT Masquerading for Outbound Internet Access

Enable Source NAT (masquerading) on the external interface to route private subnet traffic to the internet.

sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

# Illustrative output (reviewed against documentation)
# Masquerading enabled on WAN interface eth0.

In the nat table's POSTROUTING chain, this rule dynamically translates private client source IP addresses to the public IP of eth0.

Real-World Workflows, Pipelines, and Shell Automation

Complete Production Server Stateful Firewall Hardening

Deploy a production-grade default-deny stateful firewall policy that allows loopback, established sessions, SSH, HTTP, and HTTPS while blocking all other ingress.

#!/usr/bin/env bash
set -euo pipefail

echo "=== Applying Production Firewall Hardening ==="

# 1. Flush existing rules in filter table
sudo iptables -F
sudo iptables -X

# 2. Allow all loopback (localhost) traffic
sudo iptables -A INPUT -i lo -j ACCEPT
sudo iptables -A OUTPUT -o lo -j ACCEPT

# 3. Allow established and related return traffic
sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

# 4. Allow incoming SSH (port 22)
sudo iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -j ACCEPT

# 5. Allow incoming HTTP (80) and HTTPS (443)
sudo iptables -A INPUT -p tcp -m multiport --dports 80,443 -m conntrack --ctstate NEW -j ACCEPT

# 6. Set default policies: DROP incoming/forwarding, ACCEPT outgoing
sudo iptables -P INPUT DROP
sudo iptables -P FORWARD DROP
sudo iptables -P OUTPUT ACCEPT

echo "=== Firewall Hardening Applied Successfully ==="
sudo iptables -L -v -n --line-numbers

# Illustrative output (reviewed against documentation)
=== Applying Production Firewall Hardening ===
=== Firewall Hardening Applied Successfully ===
Chain INPUT (policy DROP 0 packets, 0 bytes)
num   pkts bytes target     prot opt in     out     source        destination         
1        0     0 ACCEPT     all  --  lo     *       0.0.0.0/0     0.0.0.0/0           
2        0     0 ACCEPT     all  --  *      *       0.0.0.0/0     0.0.0.0/0    ctstate RELATED,ESTABLISHED
3        0     0 ACCEPT     tcp  --  *      *       0.0.0.0/0     0.0.0.0/0    tcp dpt:22 ctstate NEW
4        0     0 ACCEPT     tcp  --  *      *       0.0.0.0/0     0.0.0.0/0    multiport dports 80,443 ctstate NEW

This production hardening script sets a default-deny policy (INPUT DROP) while ensuring loopback, established connections, SSH, and web traffic remain accessible.

Port Forwarding (DNAT) from Public Port to Internal Container

Forward incoming public traffic on port 8443 to an internal container listening on 10.0.3.50:443 using Destination NAT.

#!/usr/bin/env bash
set -euo pipefail

# Enable kernel IP forwarding
sudo sysctl -w net.ipv4.ip_forward=1

# 1. Forward inbound port 8443 on eth0 to internal container IP on port 443
sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 8443 \
  -j DNAT --to-destination 10.0.3.50:443

# 2. Allow forwarding traffic through the FORWARD chain to the container
sudo iptables -A FORWARD -p tcp -d 10.0.3.50 --dport 443 \
  -m conntrack --ctstate NEW,ESTABLISHED,RELATED -j ACCEPT

echo "DNAT port forwarding configured successfully."

# Illustrative output (reviewed against documentation)
net.ipv4.ip_forward = 1
DNAT port forwarding configured successfully.

The PREROUTING rule rewrites destination packet headers, and the FORWARD rule permits routed packets to pass between the physical WAN interface and container bridge.

Pipelines, Redirection, Quoting, and Shell Expansion

When embedding iptables inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.

Permissions, Security Implications, and Safe Execution

Configuring iptables requires root privileges or the Linux CAP_NET_ADMIN capability. Unprivileged users cannot view or modify kernel firewall tables.

Rules added via iptables exist only in kernel volatile memory and will be completely lost upon system reboot. To make rules persistent across reboots, install iptables-persistent (Debian/Ubuntu) or iptables-services (RHEL), and run sudo iptables-save > /etc/iptables/rules.v4.

GNU/Linux, BSD, and BusyBox Implementation Differences

On modern Linux systems, iptables commands typically execute via the iptables-nft translation layer, which writes rules into the kernel's nftables subsystem. You can verify whether your system uses legacy iptables or iptables-nft by running iptables --version.

High-level firewall management utilities like UFW (Ubuntu) and Firewalld (RHEL/Fedora) act as abstraction wrappers that generate underlying iptables/nftables rules. Mixing direct iptables commands with UFW or Firewalld can cause rule conflicts and unexpected packet drops.

Troubleshooting Common Errors and Diagnostics

Locked out of remote SSH session after applying firewall rules

Root Cause: The default policy was set to DROP before allowing SSH traffic, or rule order placed a generic DROP ahead of the SSH accept rule.

Resolution: Access the server via cloud provider web console, out-of-band IPMI, or recovery mode and restore the default policy: sudo iptables -P INPUT ACCEPT.

sudo iptables -P INPUT ACCEPT
sudo iptables -F

Rules disappear after server reboot

Root Cause: Iptables rules were added in memory but were not persisted to the distribution's static configuration file.

Resolution: Install iptables-persistent and save rules with iptables-save or netfilter-persistent.

sudo apt-get install -y iptables-persistent
sudo netfilter-persistent save

Port forwarding fails despite correct DNAT rules

Root Cause: The Linux kernel has packet forwarding disabled (net.ipv4.ip_forward=0), or the FORWARD chain is dropping packets.

Resolution: Enable kernel IP forwarding in /etc/sysctl.conf and verify the FORWARD chain policy.

sudo sysctl -w net.ipv4.ip_forward=1
sudo iptables -A FORWARD -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
DROP silently discards the packet with no notification sent back to the sender, causing the connection attempt to hang and time out. REJECT discards the packet and sends an explicit error reply (ICMP Port Unreachable or TCP RST), letting the sender know immediately that the port is closed.
On Debian/Ubuntu, run sudo netfilter-persistent save. On RHEL/Rocky, run sudo iptables-save > /etc/sysconfig/iptables and ensure the iptables service is enabled.
UFW and firewalld are higher-level user-friendly frontends that generate and manage iptables or nftables rules under the hood. Advanced administrators can inspect the generated rules directly using iptables -L -n -v.
Rules in a chain are evaluated sequentially from top to bottom (rule 1, rule 2, etc.). When a packet matches a rule's criteria, it executes the target (ACCEPT, DROP). If no rules match, the packet falls through to the chain's default policy (-P).
RR
Written byVerified Author

Rajesh Ray

I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout