Back to tutorials
Tutorial

UFW Firewall Setup Tutorial (2026): Lock Down an Ubuntu VPS for Web Hosting (SSH, HTTP/HTTPS, Fail2Ban-friendly)

UFW firewall setup tutorial for Ubuntu VPS in 2026: safe SSH rules, web ports, rate limits, and verification steps.

By Anurag Singh
Updated on Jun 01, 2026
Category: Tutorial
Share article
UFW Firewall Setup Tutorial (2026): Lock Down an Ubuntu VPS for Web Hosting (SSH, HTTP/HTTPS, Fail2Ban-friendly)

A misconfigured firewall doesn’t just break access. It can also leave “forgotten” services exposed to the internet. This UFW firewall setup tutorial gives you a clean, repeatable baseline for an Ubuntu VPS used for typical hosting: SSH administration, a web server (Nginx/Apache/LiteSpeed), and optional email or control panel ports.

The goal is simple. Allow only what you need. Log what matters. Keep a rollback path so you don’t lock yourself out.

What you’ll build in this UFW firewall setup tutorial

  • SSH access that’s harder to brute-force (non-destructive rules + rate limiting)
  • Web ports open (80/443) with minimal exposure
  • Optional rules for DNS, email, and common control panels
  • Clear verification steps (before/after checks, logging, and safe enablement)

Prerequisites (don’t skip these)

  • Ubuntu Server 24.04 LTS or 22.04 LTS on a VPS or dedicated server
  • Root access (or a sudo user)
  • At least one working SSH session open (keep it open until the end)

If you’re provisioning a new server, apply this baseline early. It’s a good first-hour task on a fresh HostMyCode VPS, before you install a control panel or point production traffic at it.

Step 1: Check what’s listening right now (your real attack surface)

Before you write any rules, confirm what’s actually listening on the box. This avoids the classic “I didn’t know that was running” surprise.

sudo ss -tulpn

Typical entries you might see:

  • sshd on 22/tcp (or your custom SSH port)
  • nginx/apache2/litespeed on 80/443
  • Database ports (3306, 5432) should usually be local-only on hosting boxes

If something shows up that you didn’t intend to run, stop and disable it first.

A firewall helps, but it shouldn’t be your only defense.

Step 2: Install and reset UFW to a known state

UFW is often present on Ubuntu. Still, it isn’t guaranteed to be installed everywhere.

sudo apt update
sudo apt install -y ufw

If this server was configured before, reset UFW first. Don’t stack new rules on top of unknown ones.

sudo ufw status verbose
sudo ufw reset

Note: ufw reset clears existing rules. On shared or production systems, confirm change control first.

Step 3: Set sane defaults (deny inbound, allow outbound)

This baseline fits most web hosting servers.

sudo ufw default deny incoming
sudo ufw default allow outgoing

Outbound access is usually required for updates, Let’s Encrypt, package repositories, and upstream APIs.

Inbound traffic should be explicit and minimal.

Step 4: Allow SSH first (and do it safely)

Don’t enable UFW until SSH is allowed.

If you can restrict SSH to known admin IPs, do it.

Option A (best): Allow SSH only from your admin IP

Replace 203.0.113.10 with your real public IP.

sudo ufw allow from 203.0.113.10 to any port 22 proto tcp

Option B (common): Allow SSH from anywhere + rate limit

If your admin IP changes often (travel, dynamic IP), allow SSH and add rate limiting:

sudo ufw allow 22/tcp
sudo ufw limit 22/tcp

ufw limit slows repeated connection attempts. It won’t fix weak SSH settings, but it reduces brute-force noise.

If you haven’t hardened SSH yet, pair this with key-based auth and disabling password logins.

(If you also use Nginx as a frontend, see this Nginx reverse proxy setup guide for a security posture that matches a tight firewall.)

Step 5: Open web ports (HTTP and HTTPS)

For WordPress, WooCommerce, landing pages, APIs, and most hosted sites, you usually need only two inbound ports.

sudo ufw allow 80/tcp
sudo ufw allow 443/tcp

If you plan to issue SSL certificates with Let’s Encrypt, this keeps the path simple.

For a full SSL walkthrough on Ubuntu + Nginx, follow this SSL certificate setup tutorial.

Step 6: (Optional) Add rules for common hosting services

Add rules only for services you actually run.

Every open port is something you must maintain, patch, and monitor.

Email hosting ports (only if this VPS is your mail server)

  • SMTP: 25/tcp (server-to-server). Some providers block 25 by default; verify first.
  • Submission: 587/tcp (recommended for clients)
  • SMTPS: 465/tcp (legacy but still used)
  • IMAP: 143/tcp, IMAPS: 993/tcp
  • POP3: 110/tcp, POP3S: 995/tcp
sudo ufw allow 25/tcp
sudo ufw allow 587/tcp
sudo ufw allow 465/tcp
sudo ufw allow 143/tcp
sudo ufw allow 993/tcp
sudo ufw allow 110/tcp
sudo ufw allow 995/tcp

If you’re not actively managing deliverability (SPF, DKIM, DMARC, reverse DNS, queue monitoring), don’t treat mail hosting as a casual add-on.

For many sites, a transactional email provider is easier to keep stable.

DNS ports (only if this server is authoritative DNS)

Authoritative DNS needs both UDP and TCP 53.

sudo ufw allow 53/udp
sudo ufw allow 53/tcp

In many setups, DNS stays with your domain provider.

If you need domain changes, HostMyCode offers domains and DNS management via HostMyCode Domains.

Control panels: cPanel/WHM, Plesk, DirectAdmin (use with care)

Control panel ports attract attention.

If you must expose them publicly, restrict access to your admin IP whenever possible.

  • cPanel: 2083/tcp (TLS), WHM: 2087/tcp (TLS)
  • Plesk: 8443/tcp
  • DirectAdmin: 2222/tcp
# Example: restrict WHM to a single admin IP
sudo ufw allow from 203.0.113.10 to any port 2087 proto tcp

If you’re not sure which panel fits your workflow, pause here and compare options first.

Don’t open panel ports until you’re ready to secure and maintain them.

FTP vs SFTP

Use SFTP (over SSH) instead of FTP.

Plain FTP adds firewall complexity (including port ranges). It also has a weak security story in 2026 unless you manage TLS correctly.

  • SFTP uses your SSH port (often 22/tcp). No extra rule needed.

Step 7: Enable logging (useful, but keep it controlled)

UFW logs help you spot scans and mistakes.

They can also get loud on public IPs, so start low.

sudo ufw logging low

Where to check logs on Ubuntu:

  • /var/log/ufw.log (if enabled)
  • journalctl -u ufw
sudo tail -n 50 /var/log/ufw.log
sudo journalctl -u ufw --no-pager | tail -n 50

Step 8: Do a “pre-flight” review of the rules

Before enabling UFW, list the rules in a format that’s easy to sanity-check.

sudo ufw status numbered

A minimal web hosting profile usually includes:

  • 22/tcp (or restricted by source IP)
  • 80/tcp
  • 443/tcp

Step 9: Enable UFW without locking yourself out

Keep your current SSH session open.

If you can, open a second session in another terminal as a safety net.

sudo ufw enable

Then confirm the active state and rules:

sudo ufw status verbose

If you lose access, you’ll need console access through your hosting provider to correct the rules.

That’s why some teams use managed VPS hosting for production. You keep control, but you also get backup during higher-risk changes.

Step 10: Verify from the outside (real testing, not assumptions)

Local checks don’t prove internet exposure.

Test the server from a different machine.

Use Nmap from your laptop or another server

nmap -Pn -sS -p 1-10000 YOUR_SERVER_IP

You should see only the ports you deliberately allowed.

Quick curl checks for the web server

curl -I http://YOUR_DOMAIN
curl -I https://YOUR_DOMAIN

If HTTPS fails but you expected it to work, confirm 443 is allowed.

Also confirm your web server is actually listening on 443.

Step 11: Tighten SSH beyond the firewall (high impact, low effort)

UFW limits what reaches the server.

SSH hardening reduces the odds that an attacker can log in anyway.

Edit:

sudo nano /etc/ssh/sshd_config

Common production-safe settings (adjust to your environment):

PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes

Reload SSH:

sudo systemctl reload ssh

Warning: Don’t disable password authentication until you’ve confirmed key-based login works in a new session.

Step 12: Make Fail2Ban and UFW work together (clean integration)

UFW rate limiting helps, but Fail2Ban goes further.

Fail2Ban bans IPs based on log activity. That includes repeated bad passwords, bot scans, and similar patterns.

If you run Fail2Ban, keep its firewall action consistent with your setup. Choose UFW or iptables/nftables and stick with it.

On Ubuntu, using the UFW action is common.

First, make sure Fail2Ban is installed and running:

sudo apt install -y fail2ban
sudo systemctl enable --now fail2ban

Create a minimal jail override:

sudo nano /etc/fail2ban/jail.d/sshd.local
[sshd]
enabled = true
bantime = 1h
findtime = 10m
maxretry = 5

Restart Fail2Ban and check status:

sudo systemctl restart fail2ban
sudo fail2ban-client status sshd

If you customize jails further, be conservative at first.

Overly aggressive settings can ban your own office IP after a few fat-fingered logins or password manager retries.

Common hosting pitfalls (and quick fixes)

  • You enabled UFW before allowing SSH. Use provider console access, then run ufw allow 22/tcp and re-enable.
  • Let’s Encrypt HTTP-01 challenge fails. Ensure port 80 is open and your server routes /.well-known/acme-challenge/ correctly.
  • Control panel “loads forever”. You opened 80/443 but not the panel port (e.g., 2087/8443/2222) or you restricted it to the wrong IP.
  • You exposed a database port publicly. Remove the rule and bind the database to localhost; don’t rely on firewall alone.

Production checklist: your UFW baseline for a hosting VPS

  • Defaults set: deny incoming, allow outgoing
  • SSH allowed (preferably restricted by source IP) + ufw limit enabled
  • Web ports open: 80/tcp and 443/tcp
  • No public DB ports unless you have a strong reason and strict IP allowlisting
  • Logging set to low (or medium if you actively review and rotate logs)
  • External scan confirms only expected ports are reachable

Summary: a safer VPS in under 20 minutes

A good firewall configuration is boring. That’s the point.

Keep inbound ports tight. Verify results from the outside. Remove “temporary” rules that linger for months.

With UFW in place, you can add SSL, a reverse proxy, or a control panel without exposing extra services.

If you’re setting this up for production sites, start with a HostMyCode VPS for full control. Or choose managed VPS hosting if you want help with hardening, updates, and higher-risk changes.

If you’re building a hosting stack on Ubuntu in 2026, a firewall baseline is one of the fastest wins you can deliver on day one. HostMyCode offers a flexible HostMyCode VPS for hands-on admins, plus managed VPS hosting for teams that want production guardrails while keeping root access.

FAQ

Will UFW break my website?

Not if you allow 80/tcp and 443/tcp (and your web server is listening).

Most “site down” reports come from forgetting 443 or accidentally restricting it by IP.

Should I open port 22 or change the SSH port?

Changing the port reduces background noise, but it doesn’t replace key-based auth and rate limiting.

If you keep 22, use ufw limit 22/tcp and disable password logins.

Do I need to open database ports for WordPress?

No. WordPress typically connects to MySQL/MariaDB on localhost.

Keep database ports closed publicly unless you intentionally run a remote database.

How do I remove a mistaken rule?

List numbered rules, then delete by number:

sudo ufw status numbered
sudo ufw delete 3

Is UFW enough, or do I also need Fail2Ban?

UFW is the baseline.

Fail2Ban is a strong next step for SSH and panel login protection because it reacts to real log activity and can ban abusive IPs quickly.

UFW Firewall Setup Tutorial (2026): Lock Down an Ubuntu VPS for Web Hosting (SSH, HTTP/HTTPS, Fail2Ban-friendly) | HostMyCode