How to Set Up a Firewall on a Linux Server Using UFW (Beginner-Friendly Guide)
When you put a Linux server online, it becomes part of the wild internet — and the internet is… let’s just say… not always friendly.
Bots scan IP addresses all day long trying random ports, hoping to find something open. That’s why having a firewall is one of the simplest but most important layers of protection you can add.
On Ubuntu and many Debian-based systems, the easiest firewall tool is UFW (Uncomplicated Firewall). And honestly, the name fits — it is uncomplicated.
Here’s how I normally set it up on a fresh server.
🔹 Step 1 — Check if UFW Is Installed
Most Ubuntu servers already have it. Run:
If you see something like:
that means it’s installed — just not enabled yet.
If you get a “command not found”, install it:
Done 👍
🔐 Step 2 — Make Sure You Won’t Lock Yourself Out of SSH
This step is VERY important.
Before enabling the firewall, allow SSH. Otherwise, once UFW activates, you might lose connection — and trust me, that’s not a fun experience 😅
If your SSH runs on port 22:
If you changed SSH to another port, for example 2222:
Double-check the rule:
Good. Now it’s safe to continue.
🚀 Step 3 — Enable UFW
Turn it on:
You’ll see:
Type:
Boom. Your server now has a firewall 🎉
🌐 Step 4 — Allow Web Traffic (If You Run a Website)
For HTTP:
For HTTPS:
Or simply:
or:
(depending on your web server)
These presets open both 80 and 443 automatically.
🚫 Step 5 — Deny Everything Else (Default Policy)
By default, UFW blocks incoming connections and allows outgoing.
You can confirm with:
You should see something like:
Which means:
✔ Your apps can connect out
❌ Random strangers cannot connect in
Exactly what we want.
👁 Step 6 — View and Manage Rules
To see current rules:
You might see:
To delete a rule, use the number:
Simple and clean.
🔍 Step 7 — Enable Logging (Optional but Useful)
Logging helps when troubleshooting.
Logs go here:
Just don’t forget to rotate logs if needed.
🛡 Bonus: Allow Specific IPs Only
Let’s say you only want your office IP to access SSH.
Or allow a subnet:
⚠ Common Mistakes to Avoid
Here are mistakes I’ve personally seen (or made 😅):
❌ Enabling UFW before allowing SSH
❌ Blocking SSH accidentally
❌ Forgetting HTTPS for websites
❌ Opening ports “just in case”
So always think:
👉 “Do I really need this port open?”
If not — keep it closed.
🎯 Final Thoughts
Setting up UFW is one of the simplest upgrades you can make to server security. It takes maybe 5–10 minutes, but it protects you 24/7.
With UFW you get:
✅ A clean, simple firewall
✅ SSH protection
✅ Controlled access
✅ Peace of mind
And best of all — you don’t need to be a Linux guru to use it.
Small effort. Big benefit.