For our Blog Visitor only Get Additional 3 Month Free + 10% OFF on TriAnnual Plan YSBLOG10
Grab the Deal

How to Use IPTables on Linux Server? Secure Baseline and Common Rules

Iptables is the built-in Linux firewall that filters network traffic using tables and chains. To use iptables on a Linux server: set default policies, allow essential services (like SSH), permit established connections, open required ports (HTTP/HTTPS, database), drop everything else, then save rules for persistence. Always test carefully to avoid locking yourself out.

Learning how to use iptables on a Linux server gives you granular control over inbound and outbound traffic. This guide shows you, step by step, how to design a secure baseline, add common rules, persist changes, and troubleshoot—using simple commands that work on popular distributions like Ubuntu, Debian, CentOS, Rocky Linux, and AlmaLinux.

What Is IPTables and Why It Matters

Iptables is a userspace utility that configures the Linux kernel’s netfilter firewall. It lets you create rule sets to ACCEPT, DROP, or REJECT packets based on criteria like protocol, port, source/destination IP, and connection state. For most VPS and dedicated servers, iptables is a lightweight, powerful way to harden your perimeter quickly.

What Is IPTables and Why It Matters

Modern distributions increasingly use nftables under the hood. On many systems, the iptables command is a compatibility wrapper. That’s fine—your workflow remains similar. If you prefer higher-level tools, UFW (Ubuntu) or firewalld (RHEL family) sit on top of iptables/nftables, but iptables gives you maximum control.

Before You Start: Safety Checklist

  • Have out-of-band console access (cloud/VPS console or IPMI) in case you lock out SSH.
  • Ensure sudo or root privileges.
  • Know your SSH port (default 22) and any services you must keep reachable (80/443, database, etc.).
  • Back up current rules: iptables-save > /root/iptables.backup.
  • Plan a timed rollback during testing so you can recover automatically.

IPTables Basics: Tables, Chains, Policies

Iptables rules live in “tables,” and each table contains “chains” that packets traverse. The essentials:

  • Tables: filter (default packet filtering), nat (SNAT/DNAT/port forwarding), mangle (packet alteration), raw (connection tracking exemptions).
  • Chains: INPUT (to local server), OUTPUT (from local server), FORWARD (through server), plus PREROUTING/POSTROUTING in nat/mangle.
  • Targets: ACCEPT, DROP, REJECT, or jump to user-defined chains.
  • Stateful filtering: conntrack allows rules like “permit established connections.”

Quick-Start: Build a Secure Baseline

This baseline allows loopback, established/related traffic, SSH, HTTP/HTTPS, optional ping, and drops everything else on INPUT. Adjust ports as needed.

# 1) Backup current rules
iptables-save > /root/iptables.backup

# 2) Set default policies (be careful: add allows before setting DROP if you're remote)
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT

# 3) Allow loopback
iptables -A INPUT -i lo -j ACCEPT

# 4) Allow established/related
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

# 5) Allow SSH (change 22 if custom)
iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -j ACCEPT

# 6) Allow web traffic (HTTP/HTTPS)
iptables -A INPUT -p tcp -m multiport --dports 80,443 -m conntrack --ctstate NEW -j ACCEPT

# 7) Optional: allow ping (ICMP echo-request)
iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT

# 8) Drop everything else (already handled by default policy)
# No explicit rule necessary, but you can log before dropping (see later section)

Test SSH in a second terminal before closing your current session. If something goes wrong, restore immediately:

iptables-restore < /root/iptables.backup

Common IPTables Tasks (Practical Examples)

Allow or Deny Specific Ports

# Allow SMTP and submission
iptables -A INPUT -p tcp -m multiport --dports 25,587 -m conntrack --ctstate NEW -j ACCEPT

# Block Telnet explicitly
iptables -A INPUT -p tcp --dport 23 -j DROP

Allow by Source IP/Subnet

# Only allow PostgreSQL from a private subnet
iptables -A INPUT -p tcp -s 10.0.0.0/24 --dport 5432 -m conntrack --ctstate NEW -j ACCEPT

Block a Host or Network

# Drop all packets from a hostile IP
iptables -A INPUT -s 203.0.113.77 -j DROP

# Drop a CIDR block
iptables -A INPUT -s 198.51.100.0/24 -j DROP

Rate-Limit SSH to Throttle Brute Force

This simple approach drops new SSH attempts if there are too many in a short window.

# Allow a burst of 10 new SSH connections per minute, then slow down
iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -m recent --set
iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -m recent --update --seconds 60 --hitcount 10 -j DROP

Port Forwarding (DNAT) and Source NAT (SNAT)

Enable IP forwarding in sysctl and forward traffic coming to a public port to an internal host/port.

# Enable IP forwarding (persist by editing /etc/sysctl.conf)
sysctl -w net.ipv4.ip_forward=1

# Forward public :2222 to internal 10.0.0.10:22
iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 2222 -j DNAT --to-destination 10.0.0.10:22
iptables -A FORWARD -p tcp -d 10.0.0.10 --dport 22 -m conntrack --ctstate NEW,ESTABLISHED,RELATED -j ACCEPT
iptables -t nat -A POSTROUTING -p tcp -d 10.0.0.10 --dport 22 -j MASQUERADE

# Generic outbound SNAT for internal network via eth0
iptables -t nat -A POSTROUTING -s 10.0.0.0/24 -o eth0 -j MASQUERADE

Control ICMP (Ping)

# Allow ping to the server
iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT

# Or block ping explicitly
# iptables -A INPUT -p icmp --icmp-type echo-request -j DROP

Persisting IPTables Rules Across Reboots

By default, iptables rules are stored in memory. Save them to load on boot.

Debian/Ubuntu

apt-get update && apt-get install -y iptables-persistent
netfilter-persistent save
# Files: /etc/iptables/rules.v4 and /etc/iptables/rules.v6

RHEL/CentOS/Rocky/AlmaLinux (iptables-services)

yum install -y iptables-services
systemctl enable iptables
systemctl start iptables
service iptables save  # Saves to /etc/sysconfig/iptables

If your distro defaults to nftables, iptables may be an nft wrapper. That’s okay, but be consistent. On Debian-based systems, you can check and switch with:

update-alternatives --config iptables

Verify, Log, and Troubleshoot

Inspect Rules and Counters

iptables -L -n -v --line-numbers
iptables -t nat -L -n -v --line-numbers

Add Logging Before Dropping

Log at a limited rate to avoid flooding syslog. Review logs in /var/log/syslog or /var/log/messages depending on your distro.

# Create a logging rule above the final drop
iptables -A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables denied: " --log-level 7

Avoid Lockouts: Timed Rollback Trick

While testing remotely, schedule a rollback so changes revert if you lose access.

# Revert to backup after 2 minutes unless you cancel the job
(sleep 120; iptables-restore < /root/iptables.backup) &

# If everything works, kill the sleep process or overwrite the backup with new rules

Best Practices for a Production Server

  • Default-deny: DROP INPUT and FORWARD; allow only what you need.
  • Prefer stateful rules: always allow ESTABLISHED,RELATED first.
  • Separate concerns: use user-defined chains for clarity (e.g., SSH-IN, WEB-IN).
  • Remember IPv6: mirror rules with ip6tables if you have AAAA records or IPv6 connectivity.
  • Use rate-limiting on exposed services and complement with Fail2ban.
  • Document your firewall: keep rules in version control and include comments.
  • Change SSH port only alongside proper rules and security hardening; don’t rely on obscurity.

UFW and Firewalld vs IPTables vs Nftables

UFW (Ubuntu) and firewalld (RHEL) provide simpler syntax and profiles, great for quick setups and teams. Underneath, modern systems often use nftables. Iptables gives you explicit, fine-grained control and is perfect for power users, automation, and troubleshooting. Choose the tool your team can maintain consistently.

Real-World Scenarios

LAMP/LEMP Web Server

  • Allow 22, 80, 443.
  • Restrict database ports (3306 MySQL/MariaDB, 5432 PostgreSQL) to private subnets or specific IPs.
  • Enable HTTP/2/3 at the application/proxy layer; firewall stays protocol-agnostic for TCP/UDP.

Mail Server

  • Allow 25, 465, 587, 110, 995, 143, 993 as needed.
  • Rate-limit SMTP where appropriate to reduce inbound abuse.
  • Harden with Fail2ban and proper DNS (SPF, DKIM, DMARC).

Docker Hosts

Docker manipulates iptables automatically (nat and filter). Avoid manual rules that conflict with Docker’s chains. Place your custom rules before Docker’s catch-all where appropriate, and test container networking thoroughly after changes.

Flushing and Resetting Rules (Recovery)

If you need to wipe rules, switch default policies to ACCEPT first to avoid cutting your own access, then flush.

# Temporarily allow everything
iptables -P INPUT ACCEPT
iptables -P FORWARD ACCEPT
iptables -P OUTPUT ACCEPT

# Flush rules and delete user chains
iptables -F
iptables -t nat -F
iptables -t mangle -F
iptables -X

# Optionally restore from backup
iptables-restore < /root/iptables.backup

YouStable Tip: Secure Defaults on Day One

If you host your Linux VPS or dedicated server with YouStable, our support team can help you apply a production-ready iptables baseline, tailor rules to your stack, and set up persistence. That means you start with a least-privilege firewall and focus on scaling your apps safely.

Key Takeaways

  • Start with a default-deny stance and explicitly allow required services.
  • Use stateful rules, logging, and careful testing to avoid outages.
  • Persist your configuration and document it for future maintenance.
  • Choose the firewall tool (iptables, nftables, UFW, firewalld) your team can manage confidently.
  • On YouStable servers, you can launch with a hardened baseline and expert help when you need it.

FAQs

Is iptables still used, or should I switch to nftables?

Yes, iptables is still widely used. Many systems run iptables as a wrapper over nftables. If you’re starting fresh and want a modern syntax, nftables is great. If you maintain legacy scripts or prefer iptables semantics, continue using it—just stay consistent across your fleet.

How do I prevent locking myself out over SSH?

Always allow SSH before setting DROP policies, keep a second SSH session open for testing, and schedule a timed rollback with a sleep/restore command. Ideally, have console access via your provider’s panel for emergency recovery.

What’s the difference between DROP and REJECT?

DROP silently discards packets; REJECT actively informs the sender (e.g., with ICMP unreachable). DROP is stealthier, but REJECT can speed up client failures for legitimate users. Use each where it makes operational sense.

How can I make iptables rules persistent on Ubuntu?

Install iptables-persistent: apt-get install -y iptables-persistent, then run netfilter-persistent save. This writes rules to /etc/iptables/rules.v4 and rules.v6, which load on boot.

Do I need separate rules for IPv6?

Yes. IPv4 and IPv6 have separate rule sets. Use ip6tables for IPv6 (or nftables for unified management). If your domain has AAAA records or your host has IPv6 enabled, mirror your IPv4 policy with IPv6 equivalents.

Deepika Verma

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top