Biggest deals of the year. 30-day money-back guarantee. Limited time deals. 24/7 support. Don't miss out

Iptables tutorial: How to configure a Linux firewall on VPS

Oct 27, 2026 / 9 min Read
Iptables tutorial: How to configure a Linux firewall on VPS

Iptables is a Linux firewall tool that lets you control traffic to and from your VPS by configuring rules to allow, block, forward, and filter data packets. It works through the netfilter framework in the Linux kernel and gives you precise control over which packets reach your server. 

Iptables organizes rules into tables, chains, matches, and targets. The safest setup order starts with allowing SSH and established connections before applying any DROP rules. Rules must be saved explicitly to persist after a reboot. Both UFW and nftables are viable alternatives depending on your needs.

The main steps to configure iptables are:

  1. Check and install iptables.
  2. List existing rules.
  3. Allow SSH before applying restrictive rules.
  4. Add basic firewall rules.
  5. Open common service ports.
  6. Delete or flush rules.
  7. Save rules permanently.

What is iptables?

Iptables is a command-line firewall tool that manages Linux firewall rules. It works via the netfilter framework, a packet-filtering system built into the Linux kernel. Every packet that enters or leaves your server passes through netfilter. Iptables supplies the rules that decide whether to allow, block, or handle the traffic.

Iptables handles IPv4 traffic. For IPv6, you need ip6tables. This uses the same syntax but operates on a different set of rules.

Understanding iptables starts with knowing these five core concepts:

ConceptWhat it is
TableA collection of chains grouped by purpose. The main tables are filter, nat, and mangle.
ChainA list of rules within a table. Built-in chains include INPUT, OUTPUT, and FORWARD.
RuleA condition that a packet is checked against. Iptables applies the target if the packet matches, 
MatchThe criteria used to evaluate a packet – source IP, destination port, protocol, and so on.
TargetThe action taken when a packet matches a rule: ACCEPT, DROP, RETURN, or REJECT.

Basic VPS security configurations use the filter table containing three default chains. INPUT handles incoming packets to the server. OUTPUT handles packets leaving the server. FORWARD handles packets routed to a destination other than the server.

How does iptables work?

Iptables evaluates packets one by one, from top to bottom. For each packet, it starts at the top of a chain and checks the rules in order until it finds a match. When a packet matches a rule, iptables applies that rule’s target (such as ACCEPT or DROP) and stops checking the remaining rules in the same chain.

Rule order is critical. An earlier rule can allow or block traffic before iptables ever evaluates later rules. If a broad DROP rule appears before your SSH allow rule, matching traffic is dropped immediately, and the SSH rule is never reached.

There are two ways to add rules: 

  1. The -A flag appends a rule to the bottom of a chain.
  2. The -I flag inserts a rule at a specific position.  

You’ll lock yourself out if you append a broad DROP rule before your SSH allow rule. Adding rules in the right order prevents that.

Always add essential allow rules (especially for SSH) before adding restrictive firewall rules to block or drop traffic.

What is the difference between iptables, ip6tables, and nftables?

While iptables handles IPv4 firewall rules, ip6tables handles IPv6 firewall rules using the same command syntax. That said, the two rule sets are completely separate, so rules in iptables don’t affect IPv6 traffic, and vice versa.

Nftables is the newer Linux firewall framework. It replaces both iptables and ip6tables, handling both IPv4 and IPv6 traffic in a single rule set using a cleaner syntax. On modern Ubuntu versions, iptables commands can run through an nftables backend transparently, meaning your iptables rules are actually stored and processed by nftables even though you continue using the familiar iptables syntax.

For users who want simpler firewall management on Ubuntu without writing iptables rules directly, UFW is covered later in this guide.

ToolHandlesKey points
iptablesIPv4 onlyUses classic syntax. Rules apply only to IPv4 traffic and have no effect on IPv6
ip6tablesIPv6 onlyUses the same command syntax as iptables. Rules are completely separate from iptables and apply only to IPv6 traffic
nftablesIPv4 and IPv6Newer Linux firewall framework that replaces both iptables and ip6tables. Uses a single rule set for both protocols and cleaner syntax. On modern Ubuntu, iptables commands often run through an nftables backend. Iptables rules are processed by nftables

How to configure iptables on Ubuntu VPS

The safest way to set up a VPS firewall with iptables is to build rules in a specific order: check existing rules first, then allow SSH, established connections, and required service ports before blocking anything. 

Apply DROP rules last – skipping this order can lock administrators out of a server they can no longer reach.

1. Check and install iptables

Iptables comes preinstalled on most Linux distributions. This tutorial uses Ubuntu VPS as the main example. To check whether iptables is already available on your system, run:

iptables --version 

You’ll know iptables is already installed if the command returns a version number. On modern Ubuntu versions, this may show a reference to the nftables backend, meaning iptables commands are processed by nftables under the hood. The syntax stays the same either way.

If iptables is not installed, run:

sudo apt update 

sudo apt install iptables 

2. List existing iptables rules

Check your existing rules before adding new ones. An existing rule may already allow or block traffic you intend to configure, and adding duplicate or conflicting rules causes unpredictable behavior.

List all current rules with verbose output and line numbers:

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

The -n flag prints IP addresses and port numbers numerically instead of resolving them to hostnames, which is faster and easier to read. Line numbers identify each rule’s position in the chain – you will need them to delete or insert rules at specific positions. 

The packet and byte counters in the output show whether traffic actually matches each rule, which helps with troubleshooting.

3. Allow SSH before changing firewall rules

Warning

Applying restrictive firewall rules before allowing SSH will lock you out of your VPS. There is no error message – the connection simply drops, and you lose access.

 

Allow SSH before adding any DROP or REJECT rules. The default SSH port is 22:

sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT 

This rule allows SSH from any IP address. For stronger security, restrict it to a trusted IP or range later. If you’ve changed your VPS SSH port, replace 22 with that port number instead. Check your server configuration by opening this file if you’re not sure:

sudo nano /etc/ssh/sshd_config 

Passwords are the most common SSH authentication method, but setting up SSH keys is more secure and worth doing before you lock down your firewall.

After adding the SSH rule, keep your current session open and test access from a second terminal window before saving any restrictive rules. It’s safe to continue if the second connection succeeds.

4. Add basic iptables firewall rules

The remaining rules build out your firewall in order of priority. Add them in the sequence below to avoid blocking traffic you need.

Allow localhost traffic

Traffic on the loopback interface stays within the server itself. Blocking it breaks internal communication between services running on the same machine, such as a web application connecting to a local database:

sudo iptables -A INPUT -i lo -j ACCEPT 

Allow established and related connections

This rule allows traffic that belongs to connections your server already initiated or accepted. Without it, responses to outgoing requests get blocked:

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

Allow HTTP and HTTPS

Open ports 80 and 443 to allow web traffic:

sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT 

sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT 

Block a specific IP address

To drop all traffic from a single IP address:

sudo iptables -A INPUT -s 192.0.2.1 -j DROP 

Block an IP range

Use the iprange module to drop traffic from a range of addresses:

sudo iptables -A INPUT -m iprange --src-range 192.0.2.1-192.0.2.254 -j DROP 

Drop invalid packets

Invalid packets don’t belong to any known connection and are often used in network attacks. Drop them before they reach your services:

sudo iptables -A INPUT -m conntrack --ctstate INVALID -j DROP 

Drop all other incoming traffic

Add this rule last. It drops any incoming traffic that hasn’t matched an earlier ACCEPT rule. Placing it before your allow rules will block everything, including SSH:

sudo iptables -A INPUT -j DROP 

You can set the INPUT chain policy to DROP instead (`iptables -P INPUT DROP`). Both approaches work; the rule above is simpler and safer while you’re still testing.

5. Open common service ports with iptables

Each service running on your VPS uses a specific port, and iptables needs an explicit rule to allow traffic on that port:

ServiceProtocolPortNotes
SSHTCP22Change the default port if possible
HTTPTCP80Required for unencrypted web traffic
HTTPSTCP443Required for encrypted web traffic
MySQLTCP3306Restrict to trusted IPs only
PostgreSQLTCP5432Restrict to trusted IPs only
SMTPTCP25 or 587Only if running a mail server (use 587 for client submission)
IMAPTCP993Only if running a mail server

Database ports like 3306 and 5432 should never be opened to the public internet. Restrict them to a trusted IP address or a private network interface instead:

sudo iptables -A INPUT -p tcp --dport 3306 -s 192.0.2.1 -j ACCEPT 

Replace 192.0.2.1 with the IP address of the machine that needs database access.

6. Delete or flush iptables rules

Deleting a specific rule removes it without touching the rest of your configuration; flushing removes all rules at once.

Deleting a specific rule

To remove one rule without affecting the rest, use its line number. First, list rules with line numbers:

sudo iptables -L INPUT --line-numbers 

Then delete the rule at the position you want to remove. To delete rule number 3 from the INPUT chain:

sudo iptables -D INPUT 3 

Flushing all rules

To remove all rules at once, use the -F flag:

sudo iptables -F 

Warning

Flushing the rules on a remote VPS removes all allow rules and all block rules.  Flushing leaves you locked out if your default chain policy is DROP. When the default policy is ACCEPT, flushing exposes all ports. Know your default policy before flushing.

 

DROP vs REJECT

When blocking traffic, you have two options. DROP silently discards the packet: the sender gets no response and the connection eventually times out. REJECT discards the packet and sends an error response to the sender, making troubleshooting easier but also confirming to the sender that the port exists.

Use DROP for public-facing rules where you don’t want to reveal information about your server. Use REJECT in internal or development environments where faster feedback is useful.

7. Save iptables rules permanently

Iptables rules are stored in memory and don’t survive a reboot by default. To keep your rules after restarting the VPS, save them to a file.

Install iptables-persistent

The iptables-persistent package automatically saves and loads rules. On Ubuntu, installing it also installs netfilter-persistent, which is the underlying service that loads the saved rules at boot:

sudo apt install iptables-persistent 

During installation, you’ll be prompted to save your current IPv4 and IPv6 rules. Choose Yes for both.

Save rules manually

If you installed iptables-persistent, the /etc/iptables/ directory already exists. After adding or changing rules, save them so they persist through reboots:

sudo netfilter-persistent save 

This writes both IPv4 and IPv6 rules to /etc/iptables/rules.v4 and /etc/iptables/rules.v6, respectively.”

Restore rules manually

When you need to reload saved rules without rebooting:

sudo iptables-restore < /etc/iptables/rules.v4 

sudo ip6tables-restore < /etc/iptables/rules.v6 

Verify after reboot

After restarting your VPS, confirm that the rules loaded correctly:

sudo iptables -L -v -n 

The output should match the rules you saved before rebooting.

How to configure NAT and port forwarding with iptables

NAT and port forwarding let your VPS act as a gateway, router, VPN endpoint, or traffic forwarder. They route packets between networks or redirect traffic from one port to another. These rules use the NAT table, not the filter table.

Port forwarding also requires IP forwarding to be enabled in the kernel. To enable it temporarily:

sudo sysctl -w net.ipv4.ip_forward=1 

To make it permanent, add the following line to /etc/sysctl.conf:

net.ipv4.ip_forward=1 

Then apply the change:

sudo sysctl -p 

To forward traffic arriving on port 80 to a different host on your network:

sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to-destination 192.0.2.1:80 

sudo iptables -t nat -A POSTROUTING -j MASQUERADE 

If your FORWARD chain policy is set to DROP, you also need to allow the forwarded traffic explicitly:

sudo iptables -A FORWARD -p tcp -d 192.0.2.1 --dport 80 -j ACCEPT

iptables vs UFW: Which firewall tool should you use?

Iptables gives you direct control over every aspect of your firewall, such as rule order, NAT, port forwarding, custom chains, and compatibility with existing scripts. But that control comes at a cost – the syntax is verbose, rule order is strict, and mistakes on a remote VPS can lock you out instantly.

UFW (Uncomplicated Firewall) is a frontend for iptables that simplifies common firewall tasks on Ubuntu. When you only need to allow SSH, HTTP, and HTTPS, you can configure a firewall on Ubuntu using UFW with a handful of commands and no risk of rule-ordering mistakes.

Nftables is the more modern long-term replacement for iptables. It handles IPv4 and IPv6 in a single rule set and uses a cleaner syntax, but it requires learning a new framework from scratch.

The right tool depends on what you need:

  • Use UFW if you only need basic rules like SSH, HTTP, and HTTPS on an Ubuntu VPS.
  • Use iptables if you need custom rules, NAT, port forwarding, strict rule order, or compatibility with existing scripts.
  • Use nftables if you are setting up a new server and want a modern firewall framework without legacy constraints.
ToolBest forStrengthsTrade-offs
iptablesBasic Ubuntu VPS rules (SSH, HTTP, HTTPS)Simple commands; low risk of rule-order mistakesLimited control for custom rules, NAT, or complex setups
nftablesCustom rules, NAT, port forwarding, strict rule order, or existing scriptsFull control over every aspect of the firewallVerbose syntax; rule order is strict; easy to lock yourself out on a remote VPS

How to troubleshoot iptables rules

When iptables rules are not behaving as expected, start by checking your active rules with verbose output and line numbers:

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

Check three things in the command output: rule order, line numbers, and the packet and byte counters.

Rule order determines which rule applies first. Line numbers help you delete or insert rules at a specific position. Counters show whether traffic is actually matching a rule.

On modern Ubuntu, also check the active backend:

iptables --version

If the output includes (nf_tables), your iptables commands are running through the nftables backend.

Rule order determines which rule applies first; misplaced ACCEPT or DROP rules produce unexpected results. Counters show whether traffic is actually matching a rule, which helps you confirm whether a rule is working or being bypassed entirely. 

On modern Ubuntu systems, verify whether iptables is running through the nftables backend. This can affect how rules are stored and applied.

SSH lockout recovery

Getting locked out of your VPS via SSH is a common and disruptive mistake. An SSH connection refused error after applying firewall rules usually means a restrictive rule is blocking port 22 before the ACCEPT rule is reached. 

Hostinger VPS users can regain access via the browser-based hPanel terminal without an SSH connection. Then, you can delete the blocking rule or flush all rules to restore access.

When to reset rules

Resetting all rules with iptables -F is useful when your rule set has become too complex to debug or when you want to start from a clean state.

Key takeaways for using iptables

Iptables is still a solid choice when you need precise firewall control, custom rules, NAT, port forwarding, and compatibility with existing scripts. 

For straightforward Ubuntu VPS setups where you only need to allow SSH, HTTP, and HTTPS, UFW gets the job done with less complexity. When you’re building a new server from scratch, nftables is worth learning as the modern long-term replacement for iptables.

Firewall rules decide which traffic reaches your VPS, but they don’t stop repeated login attempts from addresses that are technically allowed through. To block those brute-force attacks automatically, configure Fail2Ban alongside your iptables rules for stronger overall protection.

This article is a localized version of Iptables tutorial: How to configure a Linux firewall on VPS, originally published in English.

Bruno is a Content Writer at Hostinger, focused on creating and optimizing helpful, engaging articles about web development and marketing. With a background in journalism, he combines storytelling with practical insights to make complex topics easier to understand. He has also contributed to publications like MacMagazine and Jornal A Tarde. Outside of work, Bruno enjoys exploring art, cooking, and technology.

Trusted by 4+ million website owners worldwide

See our 73,633 reviews on Trustpilot