Iptables Firewall Rules: Essential Linux Commands and Examples
Learn how to configure iptables safely with practical Linux firewall commands for ports, IP addresses, connection tracking, NAT, port forwarding, logging, persistence and troubleshooting.
What Is Iptables in Linux?
iptables is the traditional command-line frontend for the Linux kernel netfilter framework. It lets an administrator match packets by protocol, source or destination address, port, interface and connection state, then apply a target such as ACCEPT, DROP, REJECT, LOG, DNAT, SNAT or MASQUERADE.
This iptables guide works as an iptables tutorial for beginners and a Linux firewall cheat sheet for day-to-day administration. Modern Ubuntu commonly runs the iptables-nft compatibility frontend over nftables, so check the active backend before changing production rules.

Iptables Guide Contents
- How iptables works: tables, chains and targets
- Iptables syntax and rule order
- Safe baseline Linux server firewall rules
- SSH, HTTP, HTTPS, DNS, ping and service rules
- Allow or block ports, IP addresses and subnets
- NAT, MASQUERADE and port forwarding
- Logging, rate limiting and connection protection
- List, delete, save and restore rules
- Verification commands and descriptions
- Troubleshooting checklist
- Iptables vs nftables, UFW and firewalld
- Frequently asked questions
1. How Iptables Works: Tables, Chains and Targets
Packets pass through netfilter hooks in the kernel. Iptables rules are grouped into tables, then into ordered chains. The first terminating target that matches normally decides the packet's fate, so rule placement is as important as rule syntax.
| Table or chain | Traffic handled | Common use |
|---|---|---|
filter / INPUT | Packets addressed to this host | Allow SSH, web, DNS or monitoring; block hostile sources. |
filter / OUTPUT | Packets created by this host | Control egress such as SMTP, DNS or application connections. |
filter / FORWARD | Packets routed through this host | Gateways, VPNs, containers and forwarded services. |
nat / PREROUTING | Before routing | DNAT and inbound port redirection. |
nat / POSTROUTING | After routing | SNAT and MASQUERADE. |
mangle / raw | Specialized hooks | Marks, header changes and connection-tracking exceptions. |
ACCEPT permits matching traffic. DROP silently discards it. REJECT discards it and sends an error where supported. A custom chain groups reusable policy, but control returns to the calling chain unless the custom chain reaches a terminating verdict.
2. Iptables Syntax and Rule Order
Basic iptables syntax combines a table, operation, chain, match criteria and target. These iptables syntax examples show the pattern used by most Linux iptables commands.
sudo iptables [-t table] {-A|-I|-D|-C} CHAIN [matches] -j TARGET
# Append an HTTPS rule
sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT
# Insert an SSH allow rule at position 1
sudo iptables -I INPUT 1 -p tcp -s 192.0.2.10/32 --dport 22 -j ACCEPT
# Check whether the exact rule exists
sudo iptables -C INPUT -p tcp --dport 443 -j ACCEPT
Append with -A
Adds an iptables rule to the end of a chain. An earlier broad DROP may make the appended rule unreachable.
Insert with -I
Adds a rule at the top or at a selected line number. Use it carefully because it changes evaluation order.
Match with -p, -s, -d and ports
Choose a protocol, source, destination, source port, destination port, interface or conntrack state.
Choose a target with -j
ACCEPT, DROP, REJECT and LOG are common filter targets; DNAT, SNAT and MASQUERADE are NAT targets.
Build iptables commands one option at a time and review every generated rule before applying it.
3. Safe Baseline Linux Server Firewall Rules
Back up first, identify the real interface names, allow loopback and established return traffic, allow administrator access, test, and only then apply restrictive default policies.
# Back up the active IPv4 ruleset
sudo iptables-save > ~/iptables-backup-$(date +%F-%H%M).rules
# Allow localhost and established/related return traffic
sudo iptables -A INPUT -i lo -j ACCEPT
sudo iptables -A OUTPUT -o lo -j ACCEPT
sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
# Drop invalid connection-tracking state
sudo iptables -A INPUT -m conntrack --ctstate INVALID -j DROP
# Allow SSH from your actual management address
sudo iptables -A INPUT -p tcp -s 192.0.2.10/32 --dport 22 -m conntrack --ctstate NEW -j ACCEPT
# Set policies only after tests succeed
sudo iptables -P INPUT DROP
sudo iptables -P FORWARD DROP
sudo iptables -P OUTPUT ACCEPT
An OUTPUT policy of ACCEPT is common. A restrictive egress policy needs explicit rules for DNS, NTP, package repositories, monitoring and every application dependency.
4. Common Iptables Commands for SSH, Web, DNS and Ping
Iptables SSH rule: allow port 22 from a trusted subnet
sudo iptables -A INPUT -p tcp -s 203.0.113.0/24 --dport 22 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPTThis iptables allow SSH example limits management access instead of exposing port 22 to every source.
Iptables HTTP and HTTPS rules: ports 80 and 443
sudo iptables -A INPUT -p tcp -m multiport --dports 80,443 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPTUse separate rules when HTTP and HTTPS require different source restrictions or logging.
Iptables DNS rule: TCP and UDP port 53
sudo iptables -A INPUT -p udp --dport 53 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 53 -j ACCEPTDNS needs UDP for most queries and TCP for fallback, large replies and zone transfers. Do not expose an unrestricted recursive resolver.
Iptables ICMP rule: allow or rate-limit ping
sudo iptables -A INPUT -p icmp --icmp-type echo-request -m limit --limit 5/second --limit-burst 10 -j ACCEPTICMP supports diagnostics and path MTU behavior. Avoid blocking all ICMP without understanding the operational impact.
Database access from an application subnet
# MySQL 3306
sudo iptables -A INPUT -p tcp -s 10.20.0.0/16 --dport 3306 -j ACCEPT
# PostgreSQL 5432
sudo iptables -A INPUT -p tcp -s 10.20.0.0/16 --dport 5432 -j ACCEPTBind databases to private addresses and restrict both the source subnet and cloud firewall.
Rsync, NTP and mail examples
sudo iptables -A INPUT -p tcp -s 192.0.2.0/24 --dport 873 -j ACCEPT
sudo iptables -A OUTPUT -p udp --dport 123 -j ACCEPT
sudo iptables -A OUTPUT -p tcp --dport 25 -j REJECTPort 873 is rsync, UDP 123 is NTP, and blocking outbound TCP 25 can prevent unauthorized direct SMTP delivery.
5. Allow or Block Ports, IP Addresses and Subnets
An iptables allow port or iptables open port rule should specify TCP or UDP and should restrict the source when possible. An iptables block IP rule can DROP silently or REJECT with feedback. A /32 matches one IPv4 address; a /24 matches a full subnet.
# Whitelist one management IP for HTTPS
sudo iptables -I INPUT 1 -p tcp -s 192.0.2.10/32 --dport 443 -j ACCEPT
# Blacklist one source IP
sudo iptables -I INPUT 1 -s 198.51.100.25/32 -j DROP
# Block a subnet
sudo iptables -I INPUT 1 -s 198.51.100.0/24 -j DROP
# Allow a TCP port range
sudo iptables -A INPUT -p tcp --dport 8000:8080 -j ACCEPT
# Block a UDP port
sudo iptables -A INPUT -p udp --dport 1900 -j DROP
# Reject Telnet with a TCP reset
sudo iptables -A INPUT -p tcp --dport 23 -j REJECT --reject-with tcp-reset
For large blacklists, use nftables sets, ipset or an upstream firewall rather than thousands of linear iptables rules. Confirm ownership before blocking a subnet and watch counters to verify that the intended rule matches.
6. Iptables NAT, MASQUERADE and Port Forwarding
Iptables port forwarding requires more than a NAT rule. Enable IPv4 forwarding, add DNAT in PREROUTING, allow the flow in FORWARD, and ensure the destination has a valid return path. Cloud firewalls and the destination host must also permit the traffic.
# Enable IPv4 forwarding for this boot
sudo sysctl -w net.ipv4.ip_forward=1
# Iptables MASQUERADE example for a changing external address
sudo iptables -t nat -A POSTROUTING -s 10.0.0.0/24 -o eth0 -j MASQUERADE
# Forward public TCP 8080 to 10.0.0.5:80 with DNAT
sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 8080 -j DNAT --to-destination 10.0.0.5:80
sudo iptables -A FORWARD -p tcp -d 10.0.0.5 --dport 80 -m conntrack --ctstate NEW -j ACCEPT
sudo iptables -A FORWARD -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
# SNAT when the public address is fixed
sudo iptables -t nat -A POSTROUTING -s 10.0.0.0/24 -o eth0 -j SNAT --to-source 203.0.113.10
7. Iptables Security Rules: Logging, Rate Limits and Connection Limits
Iptables brute force protection and basic iptables DDoS protection should be narrow and measured. Host rules can reduce noise, but they do not replace upstream capacity, application authentication or a dedicated mitigation service.
# Log dropped packets at a controlled rate
sudo iptables -A INPUT -m limit --limit 5/min --limit-burst 10 -j LOG --log-prefix "iptables-drop: " --log-level 6
# Rate-limit new SSH connections per source
sudo iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -m hashlimit --hashlimit 6/min --hashlimit-burst 4 --hashlimit-mode srcip --hashlimit-name ssh_limit -j ACCEPT
# Limit concurrent connections to a service
sudo iptables -A INPUT -p tcp --syn --dport 443 -m connlimit --connlimit-above 100 --connlimit-mask 32 -j REJECT
Place LOG before the terminating DROP or REJECT that you want to observe. Without rate limiting, iptables logging can flood storage and hide more useful events. Connection tracking makes ESTABLISHED, RELATED, NEW and INVALID state matching possible.
8. List, Add, Delete, Flush, Save and Restore Iptables Rules
| Task | Command | What it does |
|---|---|---|
| Show rules | sudo iptables -S | Displays policies and rules in command-style syntax. |
| List with line numbers | sudo iptables -L INPUT -n -v --line-numbers | Shows order, counters and deletion numbers. |
| Delete by number | sudo iptables -D INPUT 2 | Deletes line 2; list again because numbers shift. |
| Delete by specification | sudo iptables -D INPUT -p tcp --dport 443 -j ACCEPT | Removes an exact matching rule. |
| Flush a chain | sudo iptables -F INPUT | Removes its rules but does not change its policy. |
| Save rules | sudo iptables-save > rules.v4 | Exports the active IPv4 ruleset. |
| Restore rules | sudo iptables-restore < rules.v4 | Loads a saved ruleset; validate access immediately. |
Persistent rules on Ubuntu and Debian
sudo apt install iptables-persistent
sudo netfilter-persistent save
sudo systemctl status netfilter-persistent
sudo iptables-save
sudo ip6tables-save
Iptables rules are normally runtime state and are not persistent by default. Reboot only in a safe window, then verify both saved and active IPv4/IPv6 policy.
9. Common Verification Commands and Descriptions
| Command | Description |
|---|---|
sudo iptables -S | Show filter rules and default policies in reproducible syntax. |
sudo iptables -L -n -v | List filter chains with numeric addresses, packets and bytes. |
sudo iptables -L INPUT -n -v --line-numbers | Check INPUT order and obtain rule numbers. |
sudo iptables -t nat -L -n -v | Inspect PREROUTING, POSTROUTING and NAT counters. |
sudo iptables -C INPUT ... | Check whether an exact rule exists without adding it. |
sudo iptables-save | Print the complete active IPv4 ruleset in restore format. |
sudo nft list ruleset | Show the effective nftables ruleset on an iptables-nft host. |
sudo ss -lntup | Confirm the application actually listens on the expected address and port. |
ip -br address | Identify current interface names and addresses. |
sysctl net.ipv4.ip_forward | Confirm whether IPv4 forwarding is enabled. |
Zero counters may mean traffic used IPv6, matched an earlier rule, never reached the host, or was blocked by a cloud firewall, router, load balancer or container chain.
10. Iptables Troubleshooting Checklist
- Confirm the service is listening with
sudo ss -lntup. - Confirm whether the client used IPv4 or IPv6.
- Read the selected chain from top to bottom.
- Run the test and compare packet/byte counters.
- Check cloud security groups, provider ACLs, routers and load balancers.
- Inspect Docker, Kubernetes, VPN and agent-created chains.
- For forwarding, verify IP forwarding and both directions of routing.
- Compare active rules with the file restored at boot.
- Use a second SSH session and provider console before recovery changes.
iptables -F can immediately remove the allow rules keeping your remote session alive. Set a safe policy or schedule an automatic rollback first.11. Iptables vs Nftables, UFW and Firewalld
| Tool | Best fit | Important point |
|---|---|---|
| iptables / iptables-nft | Existing automation, legacy rules and low-level troubleshooting | Modern distributions may translate commands into nftables rules. |
| nftables | New advanced rulesets, sets, maps and combined IPv4/IPv6 policy | The modern netfilter configuration framework. |
| UFW | Simple Ubuntu host-firewall policy | A readable higher-level frontend. |
| firewalld | Zone-based management on many enterprise distributions | Provides a dynamic high-level policy layer. |
The choice is not only iptables vs nftables or iptables vs UFW. First identify which tool owns the effective policy. Avoid independently managing the same firewall with multiple frontends.
Iptables Frequently Asked Questions
How do I configure iptables safely?
Back up the ruleset, allow loopback and established traffic, allow SSH from your real administrator address, add narrowly scoped service rules, test from a second session, then set restrictive policies and save only after verification.
How do I open a port with iptables?
Add an INPUT rule that matches TCP or UDP plus the destination port and jumps to ACCEPT. Restrict the source IP or subnet whenever the service is not public.
How do I block an IP with iptables?
Insert a source match near the top of INPUT, for example sudo iptables -I INPUT 1 -s 198.51.100.25/32 -j DROP, then verify counters and impact.
How do I allow SSH with iptables?
Allow TCP destination port 22 from your management IP or subnet before applying INPUT DROP. Keep another authenticated session open during testing.
How do I make iptables rules persistent?
Ubuntu/Debian commonly uses iptables-persistent and netfilter-persistent. Save, reboot during a safe window, and compare the restored IPv4 and IPv6 rules with the intended policy.
How do I reset the iptables firewall?
A reset can disconnect you. First ensure console access, set safe default policies, flush the intended chains and tables, remove custom chains, then rebuild and verify. Do not blindly paste a reset sequence into a remote server.
Is iptables still relevant?
Yes for existing scripts, compatibility and troubleshooting. Nftables is the preferred modern framework for many new Linux deployments, while iptables-nft keeps familiar commands working.
Does iptables secure IPv6?
No. IPv4 iptables rules do not cover IPv6. Review ip6tables or nftables and verify both address families.
Build Rules Online and Continue Learning
Build INPUT, OUTPUT, FORWARD, and NAT commands carefully, then review rule order, IPv6 coverage, cloud policy, and recovery access before applying anything.