Configure UFW Firewall on Ubuntu VPS: Step-by-Step

Why UFW Belongs on Every Ubuntu VPS
A freshly provisioned VPS is an open door. Without a firewall, every port on your server is reachable from the public internet — SSH, databases, mail services, all of it. UFW (Uncomplicated Firewall) is Ubuntu's front-end for iptables, and its name is accurate: you can go from zero rules to a sensibly locked-down server in under ten minutes.
This tutorial walks through a complete setup to configure UFW firewall on Ubuntu VPS — specifically a Hostperl VPS running Ubuntu 22.04 or 24.04. You'll set default policies, open only the ports your services actually need, and verify everything before you log out. No prior firewall experience required.
Before You Start
Confirm a few things before touching any firewall rules:
- Root or sudo access — all commands below assume a non-root user with
sudoprivileges. - Know your SSH port — the default is 22, but some Hostperl VPS plans use a custom port. Run
grep Port /etc/ssh/sshd_configto check. Block the wrong port and you'll need console access to recover. - Have console access handy — your Virtualizor control panel provides an emergency console. Keep it open in another tab until your rules are confirmed.
Also confirm UFW is installed. On Ubuntu 22.04 and 24.04 it ships by default:
sudo ufw status
If the output says Status: inactive, you're ready. If UFW isn't installed at all, run sudo apt install ufw.
Step 1 — Set Default Policies
The most important decision in any firewall setup is what happens to traffic you haven't explicitly allowed. For almost every VPS, the right answer is: deny incoming by default, allow outgoing by default.
sudo ufw default deny incoming
sudo ufw default allow outgoing
Your server can still reach update servers, DNS resolvers, and external APIs — but nothing connects inbound unless you've added a rule for it. Don't enable UFW yet. Add your allow rules first.
Step 2 — Allow SSH Before Anything Else
This step is non-negotiable. Enable UFW without allowing SSH and you're locked out immediately.
If your SSH port is the default 22:
sudo ufw allow ssh
Or equivalently:
sudo ufw allow 22/tcp
If you've moved SSH to a custom port, say 2244:
sudo ufw allow 2244/tcp
Rate-limiting SSH is worth doing here too. UFW handles it with a single flag — it blocks IPs that attempt more than six connections in 30 seconds:
sudo ufw limit ssh
On a custom port, use sudo ufw limit 2244/tcp instead. For more thorough brute-force protection, the Fail2Ban setup guide pairs well with this.
Step 3 — Open Ports for Your Services
Now add rules for whatever your VPS is actually running. Here are the most common scenarios.
Web Server (Apache or Nginx)
For a web server you need ports 80 (HTTP) and 443 (HTTPS):
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
UFW also ships with named application profiles. Run sudo ufw app list to see what's available — you'll often find Apache Full or Nginx Full, which open both ports in one command:
sudo ufw allow 'Nginx Full'
Mail Server
If your VPS handles email directly (Postfix, Dovecot), you'll need several ports:
sudo ufw allow 25/tcp # SMTP
sudo ufw allow 587/tcp # Submission (authenticated outbound)
sudo ufw allow 993/tcp # IMAPS
sudo ufw allow 995/tcp # POP3S
Skip port 25 if you're only relaying mail through a third-party service. The Postfix mail relay guide covers that scenario in detail.
MySQL or MariaDB (Remote Access)
Database ports should almost never be open to the world. If another server needs access, restrict the rule to that specific IP:
sudo ufw allow from 203.0.113.50 to any port 3306 proto tcp
Replace 203.0.113.50 with the connecting server's actual IP. If your app and database live on the same VPS, leave port 3306 closed entirely.
Step 4 — Enable UFW
With your rules in place, enable the firewall:
sudo ufw enable
You'll see: Command may disrupt existing ssh connections. Proceed with operation (y|n)? Type y. UFW activates immediately and persists across reboots.
Open a second terminal and test your SSH connection right now. If it succeeds, your SSH rule is correct.
Reviewing and Managing Rules
Check the current state of all rules:
sudo ufw status verbose
The numbered view is useful when you need to delete something specific:
sudo ufw status numbered
To delete rule number 3:
sudo ufw delete 3
You can also delete by rule definition. To remove the HTTP rule:
sudo ufw delete allow 80/tcp
To temporarily disable UFW without wiping your rules — handy during troubleshooting:
sudo ufw disable
Then re-enable with:
sudo ufw enable
Allowing Traffic from Specific IP Ranges
To allow a block of IPs — your office network, a monitoring service — UFW accepts standard CIDR notation:
sudo ufw allow from 192.168.1.0/24
That opens all ports to the entire 192.168.1.x subnet. To restrict it to one port:
sudo ufw allow from 192.168.1.0/24 to any port 3306 proto tcp
This pattern is common when managing multiple client servers — you can whitelist your team's IP range for database or admin access without exposing those services publicly. The agency VPS playbook has broader guidance on structuring access across client environments.
Logging UFW Activity
UFW can log blocked connection attempts, which helps you spot port scans early. Start with the low level:
sudo ufw logging low
Entries land in /var/log/ufw.log, showing source IP, destination port, and protocol for each blocked packet. Repeated hits on port 3306 or 5432 from unfamiliar addresses is a clear sign those ports are being probed.
For a broader view across the whole server, the Logwatch daily digest setup consolidates everything into a single daily summary — no manual log tailing required.
A Practical Rule Set for a Typical Web VPS
Here's the full sequence for a VPS running Nginx, Certbot-managed SSL, and SSH on port 22 — a standard Hostperl setup:
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw limit ssh
sudo ufw allow 'Nginx Full'
sudo ufw enable
sudo ufw status verbose
Five commands. Your server is locked to SSH and web traffic only, with rate-limiting on SSH already active.
Before going live, cross-check your firewall config against the hosting uptime checklist, which covers the other pre-launch steps that sit alongside firewall hardening.
Common Mistakes to Avoid
- Enabling UFW before adding SSH rules. Always add SSH first. Always.
- Opening port 3306 globally. Your database should never be reachable from arbitrary internet IPs. Use IP-restricted rules or keep it localhost-only.
- Forgetting custom SSH ports after a rebuild. A server reinstall resets
sshd_config. Document your non-standard port somewhere you'll actually find it. - Conflicting rules. UFW processes rules top-down. An
allow 22/tcpfollowed later by adeny 22/tcpstill allows access — the first match wins. Useufw status numberedto check rule order. - Not testing from outside. After enabling, connect from a different network to confirm allowed ports work and blocked ones are genuinely unreachable.
Hostperl VPS plans on Ubuntu 22.04 and 24.04 come with a clean slate — no pre-configured firewall rules to untangle before you can start. Whether you're running a single site or managing several client environments, Hostperl VPS hosting gives you full root access and complete control over how you lock things down. For higher-traffic workloads that need dedicated resources, dedicated server hosting is worth a look.
Frequently Asked Questions
Does UFW replace Fail2Ban?
No — they work at different layers. UFW controls which ports are reachable. Fail2Ban watches log files and dynamically bans IPs showing suspicious behaviour, like repeated failed SSH logins. Running both together gives you significantly stronger protection than either alone.
Will my UFW rules survive a reboot?
Yes. Once you run sudo ufw enable, UFW registers as a systemd service and your rules persist through reboots automatically.
How do I check if a port is actually blocked from outside?
Use nmap from another machine: nmap -p 3306 your-vps-ip. A result of filtered means the port is blocked. Open means your rule isn't working as expected. Online port-check tools work too if you don't have a second server available.
Can I use UFW alongside a control panel like cPanel or Plesk?
With care. Control panels often manage their own firewall rules — ConfigServer Security & Firewall (CSF) is common with cPanel. Running UFW alongside CSF can produce rule conflicts. On control panel servers, you're usually better off using the panel's built-in firewall tools rather than UFW directly.
What if I'm locked out after enabling UFW?
Use the VNC/console access in your Virtualizor control panel. Log in from there and run sudo ufw disable to restore access, then review your rules before re-enabling.
