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.
Table of Contents
What a VPS Firewall Does (and Why a New Server Needs One Today)

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.
| Tool | Best for | Difficulty | Common distros |
|---|---|---|---|
| UFW | Beginners and single servers | Low | Ubuntu, Debian |
| firewalld | Zone-based rules and service names | Medium | AlmaLinux, Rocky Linux, CentOS Stream, Fedora |
| iptables | Custom and scriptable rules | High | Any 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

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)

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:
| Command | What it does |
|---|---|
sudo ufw allow ssh | Looks up the SSH port by service name (port 22) |
sudo ufw allow 22/tcp | Opens port 22 for TCP traffic |
sudo ufw allow OpenSSH | Uses 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

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:
| Service | Port | Open it? |
|---|---|---|
| SSH | 22/tcp (or your custom port) | Yes, on every server you manage remotely |
| HTTP | 80/tcp | Yes, if the server hosts a website |
| HTTPS | 443/tcp | Yes, if the server hosts a website |
| Mail (SMTP) | 25, 465, 587/tcp | Only on a mail server |
| MySQL or MariaDB | 3306/tcp | No. Keep it closed and connect through localhost or an SSH tunnel |
| PostgreSQL | 5432/tcp | No. 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

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:
| Task | UFW | firewalld |
|---|---|---|
| Allow SSH | ufw allow 22/tcp | firewall-cmd –permanent –add-service=ssh |
| Allow HTTP | ufw allow 80/tcp | firewall-cmd –permanent –add-service=http |
| Apply changes | ufw enable | firewall-cmd –reload |
| List rules | ufw status | firewall-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=noin 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:
- Open your provider’s web console.
- Log in with your sudo user.
- Run sudo ufw status numbered to see the current rules.
- Add the missing rule with
sudo ufw allow 22/tcp. If you can’t tell what is wrong, run sudo ufw disable. - 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?
No. UFW controls which ports are reachable. It does not protect the services behind those ports.
Add SSH key login and disable password login. Install security updates automatically. Also run fail2ban to ban repeat offenders.
Should I change the default SSH port?
A new port cuts log noise, since most bots target port 22. However, it doesn’t stop a determined scanner. Real protection comes from SSH keys.
If you do change the port, follow this order. Allow the new port in UFW first. Test a new session on it. Then remove the old port 22 rule.
Do I need a firewall if my hosting provider already has one?
Yes. The provider firewall and UFW protect different layers. If one has a gap, the other can still block the traffic.
How do I delete or reset UFW rules?
Run sudo ufw status numbered, then sudo ufw delete <number>. To remove everything, run sudo ufw reset. Step 6 covers both commands, including the lockout warning.
How do I block a single IP address on a VPS?
Run sudo ufw insert 1 deny from <ip-address>. The insert command places the rule at the top, so it takes precedence over later allow rules. To block one port only, add to any port 22.
Blocking bots one by one rarely works. Rate limiting and fail2ban handle repeat offenders better.
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.
Web Hosting
Windows HostingBuilt for Windows apps and websites – stability, speed and flexibility
Reseller HostingLaunch a hosting business without technical skills or expensive infrastructure
Affiliate ProgramRefer customers and earn commissions from sales across our platform
Domain SearchFind and secure a domain name in seconds with our quick lookup tool
CO ZA Domains
All DomainsExplore domain names from over 324 TLDs globally – all in one place
Free Whois Lookup Tool South Africa
VPS
SSLs



