India English
Kenya English
United Kingdom English
South Africa English
Nigeria English
United States English
United States Español
Indonesia English
Bangladesh English
Egypt العربية
Tanzania English
Ethiopia English
Uganda English
Congo - Kinshasa English
Ghana English
Côte d’Ivoire English
Zambia English
Cameroon English
Rwanda English
Germany Deutsch
France Français
Spain Català
Spain Español
Italy Italiano
Russia Русский
Japan English
Brazil Português
Brazil Português
Mexico Español
Philippines English
Pakistan English
Türkiye Türkçe
Vietnam English
Thailand English
South Korea English
Australia English
China 中文
Somalia English
Netherlands Nederlands

How to Set Up Basic Firewall Rules on a New VPS

Buy domains, business emails, hosting, VPS and more: Get Started

Cheapest Domains in South Africa

Get your .Co.Za or .Com domain now for just 75.00 ZAR

.CO.ZA for 75.00 ZAR | .COM for 155.00 ZAR

You deploy a fresh VPS, log in for the first time, and open the auth log out of curiosity. Within minutes, you often see lines like these: Nov 25 09:14:02 vps sshd[1823]: Failed password for invalid user admin from 203.0.113.45 port 51022 ssh2.

The IP addresses above are placeholders in the documentation, but the pattern is real.

Automated bots scan new servers and try common usernames. They don’t know you, and they don’t care who you are. A firewall stops most of that traffic before it reaches any service.

This guide shows you how to build a default-deny firewall with UFW in about ten minutes. You will block all incoming traffic, then allow SSH, HTTP, and HTTPS.

The steps work on Ubuntu and Debian, and you need no firewall experience. A short section near the end covers firewalld for AlmaLinux and Rocky Linux.

What a VPS Firewall Does (and Why a New Server Needs One Today)

Managed VPS Hosting in South Africa

A firewall is a filter. It checks every incoming connection against a list of rules. Each rule says allow or deny.

A new VPS usually has no rules. Therefore, every service listening on a port is reachable from the internet. Your SSH daemon is one example. A database you install tomorrow could become another.

Default-deny reverses that starting point. The firewall blocks all incoming traffic unless a rule allows it. You then open only the ports your server needs.

This guide builds three layers of rules. First come the default policies. Next comes an SSH rule, followed by web traffic rules.

UFW, iptables, or firewalld: Which Tool Should You Use?

Linux firewalls all use the same packet filter in the kernel. The tools differ in how much work they ask of you.

ToolBest forDifficultyCommon distros
UFWBeginners and single serversLowUbuntu, Debian
firewalldZone-based rules and service namesMediumAlmaLinux, Rocky Linux, CentOS Stream, Fedora
iptablesCustom and scriptable rulesHighAny distro

UFW is a front end to iptables. Newer systems run nftables underneath, but UFW and firewalld hide that detail. Either way, your rules land in the same place.

Pick UFW if you run Ubuntu or Debian. Pick firewalld if you run a Red Hat family distro. Skip raw iptables until you need custom chains.

This guide uses UFW. The commands work on current Ubuntu LTS releases and recent Debian versions.

Before You Touch Any Firewall Rules: Your Safety Net

Most firewall disasters are self-inflicted. You enable the firewall, forget to allow SSH, and your session dies. Prepare for that moment before you start.

Run through this checklist first:

  • A non-root user with sudo rights. Test it with sudo whoami.
  • Your server’s public IP address. Your provider’s dashboard shows it.
  • Your own public IP address. You need it if you restrict SSH later.
  • Access to your provider’s web console. Most hosts offer a VNC or noVNC console, or a rescue mode. Log in there once now, so you know it works.

Then open two SSH windows. Keep the first one connected for the whole process. Test every change from the second window.

If the second window can’t connect, the first one still lets you fix the problem. Existing sessions often survive a bad rule, but new logins will fail.

The most common lockout has one cause. People enable the firewall before they allow SSH. The steps below put the SSH rule first.

Step 1: Install UFW and Check Its Status

sudo apt update && sudo apt install ufw -y

Next, check the current status:

sudo ufw status verbose

Ubuntu usually ships with UFW. Debian images vary. Run this command on either system, since it does no harm when UFW already exists:

sudo apt update && sudo apt install ufw -y

Next, check the current status:

sudo ufw status verbose

On a new server, you should see this:

Status: inactive

Inactive means the firewall filters nothing yet. A server in this state is open on every port a service listens on.

Now check IPv6 support:

grep IPV6 /etc/default/ufw

The output should read IPV6=yes. Most current images set this already. If it says no, open the file with sudo nano /etc/default/ufw and change the value. Otherwise, your server’s IPv6 address stays unfiltered.

Step 2: Set Default Firewall Rules (Deny Incoming, Allow Outgoing)

sudo ufw default deny incoming

sudo ufw default allow outgoing

Default policies decide what happens to traffic that no rule covers. Set them like this:

sudo ufw default deny incoming

sudo ufw default allow outgoing

The first command blocks all unsolicited incoming connections. The second lets your server reach the internet.

Outgoing traffic deserves a word of caution. Denying it breaks package updates, DNS lookups, and API calls. You would then need a rule for every destination. Beginners should leave outgoing traffic open.

Nothing changes yet, since UFW is still disabled. The rules take effect when you enable it in Step 5.

Step 3: Allow SSH Before You Enable the Firewall

This step prevents the lockout described earlier. Choose one of these three commands:

CommandWhat it does
sudo ufw allow sshLooks up the SSH port by service name (port 22)
sudo ufw allow 22/tcpOpens port 22 for TCP traffic
sudo ufw allow OpenSSHUses the OpenSSH application profile on Ubuntu

All three open port 22 to everyone. Pick one and run it.

Did you move SSH to a custom port? Then open that port instead:

sudo ufw allow 2222/tcp

The rule must match the port in your sshd_config file. A mismatch locks you out.

You can also restrict SSH to your own address:

sudo ufw allow from 198.51.100.10 to any port 22 proto tcp

This rule sharply reduces the attack surface. However, it carries a risk. Many home connections change IP addresses without warning. If yours does, you lose SSH access and must use the provider console.

Use this restriction only with a static IP or a VPN. If you add it, delete the broader SSH rule afterward.

Step 4: Open Ports for Web Traffic and Other Services

sudo ufw allow 80/tcp

sudo ufw allow 443/tcp

Websites need two ports. Open them like this:

sudo ufw allow 80/tcp

sudo ufw allow 443/tcp

You can also use service names. The commands sudo ufw allow http and sudo ufw allow https do the same job.

Port ranges use a colon. UFW requires a protocol with ranges:

sudo ufw allow 6000:6007/tcp

UDP services work the same way. For example, WireGuard uses this rule:

sudo ufw allow 51820/udp

Use this table as a quick reference:

ServicePortOpen it?
SSH22/tcp (or your custom port)Yes, on every server you manage remotely
HTTP80/tcpYes, if the server hosts a website
HTTPS443/tcpYes, if the server hosts a website
Mail (SMTP)25, 465, 587/tcpOnly on a mail server
MySQL or MariaDB3306/tcpNo. Keep it closed and connect through localhost or an SSH tunnel
PostgreSQL5432/tcpNo. Keep it closed for the same reason.

The rule of thumb is short. Open a port only when a service listens on it. Every open port adds attack surface.

Databases deserve extra care. If your app and database share one server, the database should listen on localhost. Then nobody outside needs a firewall rule to reach it.

Step 5: Enable UFW and Verify Your VPS Firewall Rules

Your SSH rule is in place. Now turn the firewall on:

sudo ufw enable

UFW warns that the command may disrupt existing SSH connections. Type y to continue. Your SSH rule keeps you connected.

Then list the rules with numbers:

sudo ufw status numbered

The output should look like this:

Status: active

     To                         Action      From

     --                         ------      ----

[ 1] 22/tcp                     ALLOW IN    Anywhere

[ 2] 80/tcp                     ALLOW IN    Anywhere

[ 3] 443/tcp                    ALLOW IN    Anywhere

[ 4] 22/tcp (v6)                ALLOW IN    Anywhere (v6)

[ 5] 80/tcp (v6)                ALLOW IN    Anywhere (v6)

[ 6] 443/tcp (v6)               ALLOW IN    Anywhere (v6)

The (v6) rows cover IPv6. UFW writes both sets automatically when IPv6 support is on.

Run sudo ufw status verbose as well. The default line should read deny (incoming), allow (outgoing).

Now use your second SSH window:

ssh youruser@your-server-ip

Close the first window only after this login works.

Step 6: Add Basic Hardening (Rate Limiting, Logging, IP Rules)

Your firewall now blocks unwanted ports. The next four additions tighten it further.

Rate-limit SSH

sudo ufw limit 22/tcp

sudo ufw delete allow 22/tcp

The limit rule slows down brute-force attempts. UFW denies an address that opens more than 6 connections within 30 seconds.

sudo ufw limit 22/tcp

sudo ufw delete allow 22/tcp

Add the limit rule first. Then delete the plain allow rule, so you never lose SSH access in between.

Turn on logging

Logging records blocked connections:

sudo ufw logging on

sudo tail -f /var/log/ufw.log

Blocked attempts appear with a [UFW BLOCK] tag. Press Ctrl+C to stop the live view.

Allow or deny a single IP address

Block one address with this command:

sudo ufw deny from 203.0.113.45

Rule order changes the result here. UFW reads rules from top to bottom, and the first match wins. A deny rule added below a broad allow rule never fires for that port. Place it at the top instead:

sudo ufw insert 1 deny from 203.0.113.45

Delete rules and reset UFW.

List your rules with sudo ufw status numbered. Then delete one by its number:

sudo ufw delete 3

Numbers shift after each deletion, so list the rules again before the next one. You can also delete by rule name, such as sudo ufw delete allow 80/tcp.

To wipe everything, run sudo ufw reset. This disables UFW and removes every rule. Add your SSH rule again before you re-enable it.

How to Test Your Firewall From the Outside

The status command shows what UFW believes. A port scan shows what the internet sees. Only the scan proves the firewall works.

Run nmap from a different machine, such as your laptop:

nmap -Pn your-server-ip

Scan only servers you own. Then read the results with these definitions in mind:

  • Open: a service answers on that port.
  • Closed: the packet arrived, but no service listens there.
  • Filtered: the firewall dropped the packet without a reply.

A port you allowed shows as closed when no service runs on it yet. For example, port 80 reads closed until you install a web server. That result is normal. Every port you did not allow should read filtered.

Next, compare the scan with the server’s own view:

sudo ss -tulpn

This command lists every listening service. Investigate anything bound to 0.0.0.0 that you don’t recognize.

Finally, test persistence. Reboot the server, log back in, and run these checks:

sudo ufw status

systemctl is-enabled ufw

The first should report active. The second should report enabled.

UFW and Docker: Why Published Ports Can Bypass Your Rules

Many people install Docker on day one. That choice creates a gap in your firewall.

Docker writes its own iptables rules for published ports. Those rules take effect before UFW sees the traffic. As a result, a container port can remain reachable from the internet even when UFW denies access to it.

Here is a typical example:

docker run -d -p 3306:3306 mysql

This command publishes the database to every network interface. Your ufw status output shows nothing wrong, yet the port is open.

The simple fix binds the port to localhost:

docker run -d -p 127.0.0.1:3306:3306 mysql

Docker Compose files use the same pattern:

ports:

  - "127.0.0.1:3306:3306"

Public services like a web server are different. You want those ports open, so publish them on purpose. Then confirm the result with an external nmap scan.

Advanced users can filter container traffic through the DOCKER-USER chain. The Docker documentation on packet filtering and firewalls explains that method.

Use Your Host’s Firewall Too (Network Layer Plus Server Layer)

Many VPS providers offer a network firewall in their dashboard. It filters traffic before the packets reach your server. UFW, in contrast, runs on the server itself.

Two layers cover each other’s mistakes. Suppose you open port 3306 by accident. The provider firewall can still block it. Likewise, if Docker bypasses UFW, the network layer can catch the traffic.

Check how your host orders its rules. Many panels also use top-down matching, so the first match wins. Some panels add new rules at the top of the list.

Keep both rule sets in agreement. Allow 22, 80, and 443 on both layers, and nothing more.

Basic Firewall Rules on AlmaLinux, Rocky, and CentOS (firewalld)

Red Hat family systems use firewalld. Install it if it is missing, then start it:

sudo dnf install firewalld -y

sudo systemctl enable --now firewalld

Now add the same three services:

sudo firewall-cmd --permanent --add-service=ssh

sudo firewall-cmd --permanent --add-service=http

sudo firewall-cmd --permanent --add-service=https

sudo firewall-cmd --reload

The --permanent flag saves a rule to disk. It does not apply the rule until you reload. The default public zone already allows SSH and blocks other incoming traffic.

Check the result:

sudo firewall-cmd --list-all

This table maps the two tools side by side:

TaskUFWfirewalld
Allow SSHufw allow 22/tcpfirewall-cmd –permanent –add-service=ssh
Allow HTTPufw allow 80/tcpfirewall-cmd –permanent –add-service=http
Apply changesufw enablefirewall-cmd –reload
List rulesufw statusfirewall-cmd –list-all

Common Firewall Mistakes and How to Recover From a Lockout

Most firewall problems trace back to six errors:

  • Enabling UFW before allowing SSH.
  • Allowing port 22 after moving SSH to another port.
  • Forgetting IPv6 rules, or leaving IPV6=no in the config.
  • Opening a database port to the whole internet.
  • Assuming UFW protects Docker-published ports.
  • Placing a deny rule below a broader allow rule.

If you lock yourself out, stay calm. You can fix it in five steps:

  1. Open your provider’s web console.
  2. Log in with your sudo user.
  3. Run sudo ufw status numbered to see the current rules.
  4. Add the missing rule with sudo ufw allow 22/tcp. If you can’t tell what is wrong, run sudo ufw disable.
  5. Test SSH from a new window. Then re-enable UFW if you disabled it.

Some hosts also offer a rescue mode. Use it if the console fails to load.

FAQs

Is UFW enough to secure a VPS?

Should I change the default SSH port?

Do I need a firewall if my hosting provider already has one?

How do I delete or reset UFW rules?

How do I block a single IP address on a VPS?

Lock Down the Rest of Your New VPS

You now have a firewall that denies everything by default and allows only SSH, HTTP, and HTTPS. You also tested it from the outside, which most guides skip. That test is what proves the setup works.

Firewall rules cover only one layer. Your next three tasks are clear. Set up SSH key login and turn off password login. Install fail2ban to ban repeated failed logins. Then turn on automatic security updates with unattended-upgrades.

Do you need a server to practice these steps on? Deploy your next project on a Truehost VPS with full root access and console recovery.

You can apply every rule in this guide with a safety net from your first login. Then follow our SSH key setup guide to finish the job.

Elias N
Author

Elias N

SEO Expert Nairobi, KEN

SEO nerd by trade. Obsessing over keywords, content, and why Google does what it does.

View All Posts