Flash Sale:75% Off Hosting + Free DomainEnds in13h47m14sView Plans
Hostvento logoHostvento

Set Up a Simple Firewall with iptables

This guide needs root access, so it is for VPS and dedicated server owners. You will build a basic firewall with iptables.

Firewall2 min read11 steps

What is iptables?

A firewall is a guard for your server. It decides which network traffic may come in and which may not. iptables is a tool on Linux that lets you write those rules.

Traffic enters through numbered doors called ports. For example, websites use port 80 and 443. SSH, the remote login, usually uses port 22.

Warning: A wrong rule can lock you out of your own server. Keep a second login window open while you work. Also note down the current rules before changing anything.

Steps

  1. Log in to your server as root using SSH.
  2. Save your current rules as a backup:
iptables-save > /root/iptables-backup.txt

This writes all current rules into a file.

  1. See the current rules:
iptables -L -n -v

This lists every rule with numbers instead of names.

  1. Allow traffic that belongs to connections already open. This keeps your SSH session alive:
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
  1. Allow traffic on the local loopback. This is the server talking to itself:
iptables -A INPUT -i lo -j ACCEPT
  1. Allow SSH so you can still log in:
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
  1. Allow web traffic:
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT
  1. Block one bad IP address if needed. Replace the example number with the real one:
iptables -I INPUT -s 203.0.113.25 -j DROP
  1. Only after the allow rules are in place, drop everything else:
iptables -P INPUT DROP

This sets the default answer to "no" for anything not allowed above.

  1. Open a new SSH window and check you can still log in.
  2. Make the rules survive a reboot. On many systems you can run service iptables save. On Debian or Ubuntu, install the iptables-persistent package.

If you get locked out

Use the console or rescue tool from your provider. Ask Hostvento support if you are unsure. You can open a support ticket. Then restore the backup with iptables-restore < /root/iptables-backup.txt.

Quick recap

  • iptables writes firewall rules on Linux.
  • Back up the rules before you start.
  • Allow established traffic, SSH and web ports first.
  • Set the default policy to DROP last.
  • Test in a second window and save the rules.