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.
10 min read
Learn iptables command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.
- What iptables Does and When to Use It
- Availability and Installation Across Linux Distributions
- Command Syntax, Arguments, and Exit Status Codes
Interactive Builder for this Guide
Build your custom firewall syntax (iptables Command in Linux: Manage Firewall Rules and Packet Filtering)
sudo ufw allow port 443 proto tcp comment 'Production HTTPS'
ufw allowallow matching inbound packetsport 443Match destination port 443proto tcpFilter TCP transport trafficThe 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.
The iptables command in Linux configures the kernel Netfilter packet filtering and Network Address Translation (NAT) framework. System administrators use iptables to inspect incoming and outgoing IP packets, enforce stateful firewall policies, block abusive IP addresses, forward ports, and configure masquerading for container networks and router gateways.
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.
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:
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 / Flag | Long Form / Argument | Technical Behavior and Purpose |
|---|---|---|
-t TABLE | --table | Specifies the target Netfilter table to operate on (filter, nat, mangle, raw; default: filter). |
-L | --list | Lists all active rules in the specified chain or across the entire selected table. |
-A CHAIN | --append | Appends a new rule to the end of the specified chain. |
-I CHAIN [NUM] | --insert | Inserts a new rule at position NUM in the chain (defaults to position 1 if omitted). |
-D CHAIN [NUM] | --delete | Deletes a rule from the chain by its sequential line number or matching rule specification. |
-F [CHAIN] | --flush | Flushes (deletes) all rules in the specified chain or entire table if no chain is named. |
-P CHAIN TARGET | --policy | Sets the default policy for a built-in chain (e.g., iptables -P INPUT DROP). |
-v | --verbose | Enables verbose rule listing, displaying packet and byte counters, interface bindings, and options. |
-n | --numeric | Outputs 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.
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
Executing iptables -F (flush) or setting the default policy iptables -P INPUT DROP over an active remote SSH session without first adding an explicit allow rule for SSH will instantly lock you out of the server permanently until physical or out-of-band console access is restored.
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
Alternatives, Related Commands, and Related Tutorials
- How to Check Open Ports in Linux: nmap, netcat, and Bash — Practical syntax, flags, and examples for
nc. - ss Command in Linux: Display Socket Statistics and Listening Ports — Practical syntax, flags, and examples for
ss. - netstat Command in Linux: Network Connections, Routing, and Statistics — Practical syntax, flags, and examples for
netstat. - Netcat (nc) Command in Linux: Port Scanning, Transfers, and Debugging — Practical syntax, flags, and examples for
nc. - 25 Best Linux Commands Every Sysadmin Should Know — Core command-line utilities for daily Linux server administration.
- How to Find a File in Linux from the Command Line — Practical file search patterns across Linux directories.
- Linux Commands Knowledge Hub (#linux-commands) — Browse all Linux command-line tutorials and system administration references.
Authoritative References and Official Documentation

The Linux Command Line, 2nd Edition: A Complete Introduction
Frequently Asked Questions
Quick answers to common questions and configurations
/etc/sysconfig/iptables and ensure the iptables service is enabled.Editorial Disclosure: Website Vidya is supported by our readers. When you purchase hosting, tools, or software through our verified partner links, we may earn an affiliate commission at no extra cost to you. We only recommend solutions we trust and rigorously verify.
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.
Most Read Guides
TrendingUbuntu Server Not Booting? 10 Simple Steps to Fix It Fast
How to Create a 3D Button in HTML and CSS: Easy Steps
How to Install Python and Pip on Ubuntu 24.04 LTS
How to Install Nginx on Ubuntu 24.04
How to Install Python on Ubuntu 24.04 LTS
Related Technical Guides
Tested runbooks, server administration walkthroughs, and troubleshooting guides


Join the Conversation & Perspective
Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.
No comments on this guide yet. Be the first to share your thoughts or ask a question!