One command. That's all it takes to turn a healthy Ubuntu box into a server that refuses to answer you. Running sudo ufw enable puts a default-deny policy into force the instant you press Enter, and if no rule allows your SSH port, your next login attempt simply hangs until it times out.
So the question isn't only how to setup UFW firewall rules. It's what order to run them in.
Quick Answer: Install UFW, set ufw default deny incoming and ufw default allow outgoing, add your SSH rule with sudo ufw allow OpenSSH, confirm it with sudo ufw show added, then run sudo ufw enable. Keep your current session open and log in from a second terminal before closing anything. As of September 2026 this sequence works unchanged on Ubuntu 22.04, 24.04 and 26.04.
Our engineers resolve 20 to 30 client issues every day, and firewall lockouts turn up in that queue most weeks, nearly always from someone who ran enable before allow. This guide is written from the Hostaccent side of those tickets, in the same order we'd walk a customer through it on a live server.
You don't need a control panel for any of this. A terminal, sudo access, and five quiet minutes will do.
What UFW Actually Does on an Ubuntu Server
UFW is a front end. That's the entire idea behind it: it writes rules into the kernel's packet filter using syntax a tired human can read at 2am, instead of raw iptables chains nobody wants to debug under pressure.
The Uncomplicated Firewall ships with every Ubuntu release and sits inactive until you switch it on. It filters traffic at the host level, which means it protects the one machine it runs on, not your wider network. On a stock Ubuntu 24.04 server with a LAMP stack and UFW inactive, at least four ports accept connections from anywhere on the internet: 22, 80, 443 and very often 3306. The official Ubuntu Server firewall documentation confirms the tool's scope is deliberately narrow: simple host rules, nothing more.
What it does well is answer one question per packet. Is this port open, and is this source allowed to reach it? Yes or no.
What it cannot do is worth saying out loud, because plenty of guides skip it. UFW does not inspect what travels over port 443, so a vulnerable plugin on your site is still a vulnerable plugin. It does not slow down password guessing against a port you've deliberately opened, which is Fail2ban's job. And it will not save you from a volumetric flood, because the traffic still arrives at your network card before the kernel drops it.
Insider Insight: From our ticket queue: according to Hostaccent's support-queue data (July 2026), brute-force and malware cases make up about 25% of monthly tickets, with general Linux server issues another 25%. A host firewall prevents part of the first category and almost none of the second. Think of it as a door policy, not a bodyguard.
Do I actually need UFW if my provider already has a network firewall?
Yes, and the reason is boring but real. A provider-level firewall usually filters at the edge and often ships with a permissive default. UFW sits on the host itself, so it still applies when traffic arrives from inside the same private network, from a neighbouring container, or from a VPN tunnel that bypasses the edge entirely. Two layers cost you nothing. One layer costs you everything on the day it's misconfigured, which is exactly the defence-in-depth logic Cloudflare's learning centre lays out for edge and origin protection.
The Three-Key Check: What to Confirm Before You Touch the Firewall
Before a single rule gets written, run what we call the Three-Key Check. Three answers, ninety seconds, and the lockout risk drops close to zero. Skip it and you're relying on luck.
Key one: which port is SSH actually listening on? Don't assume 22. Plenty of servers were hardened months ago by someone else.
bashsudo grep -Ei '^\s*Port' /etc/ssh/sshd_config sudo ss -tulpn | grep sshd
The second command is the honest one, because it shows what the daemon is really bound to right now rather than what the config file hopes for. Note the number down. That number is the one rule you cannot get wrong.
Key two: do you have a way in that isn't SSH? On a KVM or Proxmox host this is the noVNC console. On a cloud VPS it's the provider's web console or serial connection. Open it once, right now, and confirm you can reach a login prompt. Discovering that your console password expired is a very different experience before you enable a firewall than after.
Key three: is there a snapshot or a backup from today? Firewall rules are cheap to rebuild, but if you're about to harden several things at once, a snapshot turns an hour of recovery into a two-minute rollback. Our full Linux VPS security baseline for Ubuntu 24.04 covers where this step fits in a wider hardening pass.
Pro Tip: Give yourself an undo button before you enable anything. Run
echo "ufw disable" | sudo at now + 10 minutesfirst. If your rules are wrong and you lose access, the firewall switches itself off ten minutes later and you're back in. If everything works, cancel the job withsudo atqthensudo atrm <job-number>. Installatwithsudo apt install atif it isn't there. This one trick has saved more customer servers than any other line in this guide.
How to Setup UFW Firewall on Ubuntu, Step by Step
Seven steps, in this exact order. The order is the whole point: change it and you're gambling with your own access.
Step 1: confirm UFW is installed. It usually is, but a minimal cloud image may have dropped it. To configure UFW on Ubuntu from a clean state:
bashsudo apt update sudo apt install ufw sudo ufw status verbose
A fresh install reports Status: inactive, which is correct and intentional. UFW stays dormant so you can build a rule set before anything starts filtering.
Step 2: set the default policies. This is the backbone of the whole configuration.
bashsudo ufw default deny incoming sudo ufw default allow outgoing
That pair does the heavy lifting. ufw default deny incoming means anything you haven't explicitly permitted gets dropped, so you stop playing whack-a-mole with ports and start working from a clean deny-by-default position. Outgoing stays open because your server needs to fetch packages, resolve DNS and renew certificates.
Step 3: allow SSH, before anything else. Run the ufw allow ssh port rule now, every single time, no exceptions:
bashsudo ufw allow OpenSSH # or, if you prefer explicit numbers: sudo ufw allow 22/tcp # custom port from the Three-Key Check: sudo ufw allow 2222/tcp
If your admin IP is static, tighten it further. This is the single strongest improvement most people never make:
bashsudo ufw allow from 203.0.113.10 to any port 22 proto tcp
Step 4: verify the rule exists while the firewall is still off. This step takes two seconds and is missing from nearly every tutorial on page one:
bashsudo ufw show added
Read the output. If your SSH port isn't in that list, stop and fix it now.
Step 5: enable. UFW warns that the operation may disrupt existing SSH connections. Type y. The trick to enable UFW without losing SSH is sequence, not syntax, and you've already done the sequencing.
bashsudo ufw enable
Step 6: test from a second terminal. Leave your current session open and untouched. Open a brand new SSH connection from a different window. If it logs in, you're safe. If it hangs, your first session is still alive and you can run sudo ufw disable to recover.
Step 7: read the final state.
bashsudo ufw status numbered
Those numbers matter later when you delete a rule. Full hardening beyond the firewall is covered in our complete 2026 VPS hardening guide.
Still working through this server issue?
Send the symptoms, error output, and what you have already tried. We can work with Hostaccent services or infrastructure hosted with another provider.
Opening the Ports Your Stack Actually Needs
Open the minimum. A web server needs two public ports, not twelve. Every extra open port is another service whose patch level you're now responsible for, and in our experience the forgotten ones are always the dangerous ones.
Here's the working reference for a typical hosting stack, including who each port should be open to:
| Service | Port | UFW command | Open to whom |
|---|---|---|---|
| SSH | 22 (or custom) | sudo ufw limit 22/tcp | Your admin IP only, if possible |
| HTTP | 80 | sudo ufw allow 80/tcp | Everyone (needed for certificate renewal) |
| HTTPS | 443 | sudo ufw allow 443/tcp | Everyone |
| SMTP submission | 587 | sudo ufw allow 587/tcp | Everyone, only if you send mail |
| IMAPS | 993 | sudo ufw allow 993/tcp | Everyone, only if you host mailboxes |
| DNS | 53 | sudo ufw allow 53 | Only if the box is authoritative |
| MySQL / MariaDB | 3306 | sudo ufw allow from 10.0.0.5 to any port 3306 | Private IPs only, never the internet |
| cPanel / WHM | 2083, 2087 | sudo ufw allow from 203.0.113.10 to any port 2087 | Your admin IP only |
| FTP | 21 | sudo ufw allow 21/tcp | Avoid entirely; use SFTP over 22 |
Ubuntu also ships application profiles, which are easier to read six months later than bare port numbers:
bashsudo ufw app list sudo ufw allow 'Nginx Full'
On the stack we run at Hostaccent (Cloudflare in front, an Nginx reverse proxy, Apache behind it, MariaDB on NVMe SSD storage), only 22, 80 and 443 face the public internet on a standard web node. Database traffic never crosses a public interface at all. If you've been fighting a MySQL root password reset or watching an FTP 530 authentication failure, check your firewall rules before assuming the service itself is broken, because a silently dropped packet looks a lot like a credential problem.
Keep port 80 open even on a HTTPS-only site. Let's Encrypt's HTTP-01 challenge needs it, and closing it is a common cause of the renewal failures we cover in fixing Certbot renewal errors.
Pro Tip: If your site sits behind Cloudflare, don't leave 80 and 443 open to the whole internet. Allow only Cloudflare's published IP ranges to reach your origin, and attackers who discover your real server IP find nothing listening. It's fifteen minutes of work and it removes an entire class of origin-direct attacks.
Locked Out Already? How to Get Back In
If you found this page because SSH is already timing out, start here. The firewall is not corrupt and your data is fine. You simply need a path to the machine that isn't SSH.
Use the console. Every serious virtualization platform provides one: noVNC on Proxmox, the web console on a cloud VPS, IPMI or KVM-over-IP on dedicated hardware. Log in there as root or your sudo user and run:
bashsudo ufw disable
Access returns immediately. Now add the missing rule, verify it with sudo ufw show added, and enable again.
If the console won't accept a login, boot into recovery mode from the provider panel, mount the root filesystem read-write, and edit /etc/ufw/ufw.conf. Change ENABLED=yes to ENABLED=no and reboot. UFW starts disabled and your rules stay intact for inspection.
If you allowed the wrong IP, that's the sneaky variant. The rule exists, so nothing looks broken, but your source address doesn't match it. Dynamic residential IPs change, and VPN exits change constantly. Check what the world sees as your address with curl ifconfig.me from any working machine, then compare it to the rule.
If you rolled out changes across several servers, restore the snapshot from the Three-Key Check rather than fixing each one by hand.
The community Ubuntu UFW reference documents the config file layout in more depth if you need to inspect rules offline before re-enabling.
Pro Tip: After any recovery, run
sudo ufw status numberedand actually read every line before you enable again. Half the repeat lockouts we see happen because someone fixed the rule that broke them and left a second, equally wrong rule further down the list.
The UFW Mistakes We See Most in Support Tickets
Across the 4,000+ site migrations our team has run since 2012, firewall configuration is one of the most common things that arrives copied over and quietly broken. These five account for most of it.
Docker walks straight past your rules
This one catches experienced admins. Docker writes its own chains directly into the packet filter, below where UFW operates, so a container published with -p 3306:3306 is reachable from the internet even when sudo ufw status shows the port as blocked. Bind containers to localhost with -p 127.0.0.1:3306:3306, or use a tool designed to reconcile the two. Never assume UFW output tells the truth about a containerised service.
Rule order decides the outcome
UFW evaluates rules top to bottom and stops at the first match. A broad allow 22/tcp sitting above a narrow deny from 198.51.100.0/24 means the deny never fires. Use sudo ufw insert 1 deny from 198.51.100.0/24 to put restrictive rules where they'll actually be read.
IPv6 rules that were never switched on
If IPV6=no in /etc/default/ufw, your careful rule set covers half the internet. Modern Ubuntu images default to yes, but older or custom images often don't. Check it, then reload.
ufw reset is not a soft reset
It disables the firewall and wipes every rule you wrote. On a remote server that's a two-stage disaster: you lose your protection, then you rebuild from memory. Back up /etc/ufw/ first.
Expecting a host firewall to absorb a flood
UFW drops packets after they've already consumed your bandwidth and interrupt budget. Under a real flood the server can still fall over while the firewall does exactly what you asked. Mitigation has to happen upstream, which is why our guide to stopping a DDoS attack in the first ten minutes starts at the network edge rather than the host. For the wider picture on layered defence, OWASP's guidance is a better starting point than any single tool's manual.
We've been running Linux servers for customers since 2012 and have been a UK-registered company since 2018, and the pattern hasn't changed in that time: firewalls fail from misconfiguration far more often than from attack.
Your Next Step: A Server Where This Isn't a Solo Job
Now you know how to setup UFW firewall rules in the order that keeps you connected: allow SSH, enable, verify from a second session. The only open question is who's holding the console at 3am when a rule goes wrong. You can keep that job, or start on a server where root access comes with engineers who pick up. The Basic Linux VPS plan at $7.99/mo gives you full root access, free 30 Gbps DDoS protection and a 99.9% uptime guarantee, with 30 days money back. One honest caveat: no VPS at this price includes a cPanel licence, so budget separately if you want a panel. Tell Hostaccent what your stack needs.
Frequently Asked Questions About UFW on Ubuntu
How to setup UFW firewall on a live production server without downtime?
Work in this order and nothing goes offline. Set your default policies, add the SSH rule, then list every port your services are actually listening on with sudo ss -tulpn and allow those before enabling. Established connections survive because the kernel tracks them as already open. The risk is never the websites on 80 and 443, it's the admin or mail port nobody remembered. Check that listening list twice.
Will ufw enable disconnect my current SSH session?
No, and the reason is worth understanding. Connection tracking treats your existing session as established traffic, so it passes even though UFW warns that the operation may disrupt SSH. The connection that dies is the next one you attempt, and only if no rule permits that port. That's precisely why you should open a second terminal and log in fresh before closing the session you're working in. Test, then trust.
Should I use ufw allow ssh or ufw limit ssh?
Use limit on any server exposed to the open internet. It permits the connection but blocks a source IP that opens six or more connections within 30 seconds, which cuts background brute-force noise significantly without any extra software. Use plain allow when SSH is already restricted to a specific admin IP, since rate limiting adds nothing there. Neither replaces key-based authentication, which remains the setting that actually stops password attacks.
Why do my Docker containers ignore UFW rules?
Because Docker inserts its own rules into the packet filter beneath the layer UFW manages, so published container ports bypass your deny policy entirely. A container started with -p 5432:5432 is publicly reachable even though ufw status reports that port as closed. Bind to localhost instead with -p 127.0.0.1:5432:5432, or put the service behind your reverse proxy. Always verify from an outside machine rather than trusting the firewall's own output.
How do I delete a UFW rule I added by mistake?
Run sudo ufw status numbered to list every active rule with an index, then remove the one you want with sudo ufw delete 4. The numbers shift after each deletion, so re-run the status command between removals rather than deleting several in sequence from one listing. You can also delete by matching the original syntax, for example sudo ufw delete allow 8080/tcp, which is safer inside scripts.
Is UFW enough to stop a DDoS attack?
No. UFW drops unwanted packets only after they have already crossed your network interface and used your bandwidth, so a volumetric flood can still exhaust the server while every rule works correctly. Real mitigation happens upstream at the network edge, before traffic reaches your machine. Hostaccent VPS plans include free 30 Gbps DDoS protection for that reason, and pairing an edge layer with a tight host firewall is the combination that holds up.











Discussion
Have a question or tip about this topic? Share it below — your comment will appear after review.