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.

Iptables TutorialLinux FirewallNetfilterNATSecurity
Iptables Essentials: Common Firewall Rules & cheat sheet: use this quick map before reading the detailed sections.

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.

Primary IPv4 tablefilter
Host trafficINPUT / OUTPUT
Routed trafficFORWARD
Address translationnat
Remote-server safety: allow your current administrator IP to SSH before a default INPUT DROP policy. Keep a second session and provider console available until testing is complete.
Iptables cheat sheet showing packet flow through INPUT, OUTPUT, FORWARD, PREROUTING and POSTROUTING with common Linux firewall commands
Iptables packet flow and command cheat sheet for filter rules, NAT and safe verification.

Iptables Guide Contents

  1. How iptables works: tables, chains and targets
  2. Iptables syntax and rule order
  3. Safe baseline Linux server firewall rules
  4. SSH, HTTP, HTTPS, DNS, ping and service rules
  5. Allow or block ports, IP addresses and subnets
  6. NAT, MASQUERADE and port forwarding
  7. Logging, rate limiting and connection protection
  8. List, delete, save and restore rules
  9. Verification commands and descriptions
  10. Troubleshooting checklist
  11. Iptables vs nftables, UFW and firewalld
  12. 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 chainTraffic handledCommon use
filter / INPUTPackets addressed to this hostAllow SSH, web, DNS or monitoring; block hostile sources.
filter / OUTPUTPackets created by this hostControl egress such as SMTP, DNS or application connections.
filter / FORWARDPackets routed through this hostGateways, VPNs, containers and forwarded services.
nat / PREROUTINGBefore routingDNAT and inbound port redirection.
nat / POSTROUTINGAfter routingSNAT and MASQUERADE.
mangle / rawSpecialized hooksMarks, header changes and connection-tracking exceptions.
table → chain → ordered match rules → target

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 ACCEPT

This 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 ACCEPT

Use 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 ACCEPT

DNS 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 ACCEPT

ICMP 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 ACCEPT

Bind 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 REJECT

Port 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
DNAT changes the destination before routing. SNAT and MASQUERADE change the source after routing. MASQUERADE is convenient for dynamic addresses; SNAT is clearer for a fixed public IP.

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

TaskCommandWhat it does
Show rulessudo iptables -SDisplays policies and rules in command-style syntax.
List with line numberssudo iptables -L INPUT -n -v --line-numbersShows order, counters and deletion numbers.
Delete by numbersudo iptables -D INPUT 2Deletes line 2; list again because numbers shift.
Delete by specificationsudo iptables -D INPUT -p tcp --dport 443 -j ACCEPTRemoves an exact matching rule.
Flush a chainsudo iptables -F INPUTRemoves its rules but does not change its policy.
Save rulessudo iptables-save > rules.v4Exports the active IPv4 ruleset.
Restore rulessudo iptables-restore < rules.v4Loads 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

CommandDescription
sudo iptables -SShow filter rules and default policies in reproducible syntax.
sudo iptables -L -n -vList filter chains with numeric addresses, packets and bytes.
sudo iptables -L INPUT -n -v --line-numbersCheck INPUT order and obtain rule numbers.
sudo iptables -t nat -L -n -vInspect PREROUTING, POSTROUTING and NAT counters.
sudo iptables -C INPUT ...Check whether an exact rule exists without adding it.
sudo iptables-savePrint the complete active IPv4 ruleset in restore format.
sudo nft list rulesetShow the effective nftables ruleset on an iptables-nft host.
sudo ss -lntupConfirm the application actually listens on the expected address and port.
ip -br addressIdentify current interface names and addresses.
sysctl net.ipv4.ip_forwardConfirm 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

  1. Confirm the service is listening with sudo ss -lntup.
  2. Confirm whether the client used IPv4 or IPv6.
  3. Read the selected chain from top to bottom.
  4. Run the test and compare packet/byte counters.
  5. Check cloud security groups, provider ACLs, routers and load balancers.
  6. Inspect Docker, Kubernetes, VPN and agent-created chains.
  7. For forwarding, verify IP forwarding and both directions of routing.
  8. Compare active rules with the file restored at boot.
  9. Use a second SSH session and provider console before recovery changes.
Flush warning: if INPUT policy is DROP, running 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

ToolBest fitImportant point
iptables / iptables-nftExisting automation, legacy rules and low-level troubleshootingModern distributions may translate commands into nftables rules.
nftablesNew advanced rulesets, sets, maps and combined IPv4/IPv6 policyThe modern netfilter configuration framework.
UFWSimple Ubuntu host-firewall policyA readable higher-level frontend.
firewalldZone-based management on many enterprise distributionsProvides 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.

Continue learning

Use these related resources to apply or verify the concepts on this page: