
You can run a beautifully tuned web stack and still lose the box if one stray port stays exposed. This UFW firewall configuration tutorial shows how to build a hosting-friendly ruleset on Ubuntu and Debian. It keeps SSH reachable, serves sites normally, and avoids breaking mail or a control panel.
The mindset is simple. Allow only what you use, and only from where you need it.
Log enough to debug real problems, but not so much that you stop reading the logs. Use a safe rollout sequence and a couple of rollback moves. That way, “I locked myself out” doesn’t become a late-night incident.
What you’ll build (and what you should not do)
- Default-deny inbound, allow outbound (typical for hosting VPS and dedicated servers).
- SSH protected with a safe rollout sequence, optional IP allowlisting, and rate limiting.
- HTTP/HTTPS allowed for web hosting (Nginx/Apache/LiteSpeed behind it).
- Optional mail ports only if your VPS is actually handling SMTP/IMAP/POP.
- Optional control panel ports only if you run a panel on the server.
Do not paste a generic “open everything” ruleset. It defeats the point of having a firewall.
Also avoid running UFW alongside another firewall manager (like firewalld). Only do this if you understand chain order and ownership.
Pick one tool per server and keep it consistent.
Prerequisites for this UFW setup
- Ubuntu 22.04/24.04 LTS or Debian 12/13 (UFW works the same for this use case).
- Root access (or a sudo user).
- Console access via your hosting provider’s panel (recommended). If you can’t get console access, be extra cautious.
If you’re provisioning a new server for web hosting, start clean. Don’t inherit mystery rules or half-removed services.
A predictable baseline is easier to secure and maintain on a HostMyCode VPS. It’s even easier if you want OS hardening and routine checks handled on managed VPS hosting.
Step 1: Inventory the ports your server actually uses
Before you touch the firewall, check what’s listening right now. This prevents two common mistakes. You won’t open ports you don’t need, and you won’t forget ports you do.
sudo ss -lntup
sudo ss -lnup | head -200
Typical hosting services:
- SSH: 22/tcp (or a custom port)
- Web: 80/tcp and 443/tcp
- Mail (only if you host mail): 25/tcp, 465/tcp, 587/tcp, 110/tcp, 995/tcp, 143/tcp, 993/tcp
- Control panels (only if installed): varies by panel
Also confirm whether you’re on IPv6. If you are, plan to apply rules to both stacks.
ip -br a
Step 2: Install and sanity-check UFW
sudo apt update
sudo apt install -y ufw
Confirm what UFW thinks the current state is:
sudo ufw status verbose
If it shows “inactive”, that’s normal on a fresh install. Leave it inactive for now.
Step 3: Configure defaults (deny inbound, allow outbound)
For most hosting servers, inbound should be explicit. Outbound can usually stay open.
Your server needs outbound access for updates, upstream APIs, and certificate validation.
sudo ufw default deny incoming
sudo ufw default allow outgoing
If you’re in a locked-down environment (compliance, internal-only apps), you can restrict outbound too. Expect extra work.
DNS, NTP, package mirrors, and mail relays will need explicit allow rules.
Step 4: Prevent SSH lockouts (safe rollout sequence)
SSH is your lifeline. Don’t treat it as “just another port.”
Use this order every time:
- Allow SSH first.
- Enable UFW.
- Verify from a second session before closing the first one.
Allow SSH by service name (preferred) or port:
sudo ufw allow OpenSSH
# or
sudo ufw allow 22/tcp
If you run SSH on a custom port (example: 2222):
sudo ufw allow 2222/tcp
Optional but recommended: rate limit SSH to reduce brute-force noise. This doesn’t replace strong auth. It does cut background hammering.
sudo ufw limit OpenSSH
If your admin IPs are stable (office IP, VPN egress IP), tighten SSH with allowlisting. Don’t leave it open globally unless you must:
sudo ufw delete allow OpenSSH
sudo ufw allow from 203.0.113.10 to any port 22 proto tcp
Before you get aggressive with restrictions, keep one “break glass” path available. That’s usually a VPN or your provider’s console.
If you want a deeper SSH baseline (keys, sudo, safe defaults), pair this guide with SSH key setup tutorial.
Step 5: Allow web traffic (HTTP and HTTPS)
Standard web hosting needs ports 80 and 443.
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
If you use Let’s Encrypt HTTP validation, port 80 must remain reachable. This matters at least during issuance and renewals.
If renewals fail, don’t guess. Work through a focused checklist in SSL renewal troubleshooting tutorial.
Step 6: Add mail ports only if your VPS hosts email
Many hosting setups send mail through a relay and never accept inbound mail. If that’s your model, you often need no inbound mail ports. Outbound is already allowed by default.
If your server receives mail for domains (MX points to this IP), allow SMTP:
sudo ufw allow 25/tcp
If you support authenticated submission from users and apps:
sudo ufw allow 587/tcp
sudo ufw allow 465/tcp
If you host mailboxes (Dovecot), allow IMAP/IMAPS. Only allow POP if you really must:
sudo ufw allow 143/tcp
sudo ufw allow 993/tcp
# optional legacy
sudo ufw allow 110/tcp
sudo ufw allow 995/tcp
Mail deliverability depends heavily on DNS and reverse DNS. If mail starts bouncing after changes, verify SPF/DKIM/DMARC and rDNS using Email Deliverability Troubleshooting Tutorial (2026) and PTR record troubleshooting.
Step 7: Control panel ports (cPanel, Plesk, DirectAdmin) — be selective
Control panels save time. They’re also popular targets.
If you don’t run a panel, don’t open panel ports. If you do, restrict them by IP whenever you can.
cPanel/WHM common ports (verify in your environment):
- WHM: 2087/tcp (TLS), 2086/tcp (non-TLS)
- cPanel: 2083/tcp (TLS), 2082/tcp (non-TLS)
- Webmail: 2096/tcp (TLS), 2095/tcp (non-TLS)
Example: allow WHM only from your admin IP:
sudo ufw allow from 203.0.113.10 to any port 2087 proto tcp
If you need broader access temporarily (travel, dynamic IP), use a VPN endpoint or a bastion VPS. That’s usually safer than opening panel ports to the internet.
For a panel-specific lock-down checklist, use cPanel Hardening Tutorial (2026) and the companion cPanel 2FA setup guide.
Step 8: Enable IPv6 safely (don’t secure IPv4 and forget IPv6)
If your VPS has IPv6 enabled and your services bind to it, firewall it too. UFW can manage IPv6, but only if it’s enabled in /etc/default/ufw.
sudo nano /etc/default/ufw
Set:
IPV6=yes
After you’ve added rules and enabled UFW, reload so the IPv6 setting applies.
If you don’t use IPv6 at all, disable it at the OS/network level. Don’t leave it half-on and unfiltered.
Step 9: Turn on logging (use “low” first)
Logs help the moment something times out. On a busy node, they can also get noisy.
Start with “low” and adjust later.
sudo ufw logging low
UFW logs land in system logs. Common locations include /var/log/ufw.log or journalctl, depending on your distro logging setup:
sudo ls -lah /var/log/ufw.log
sudo journalctl -u ufw --no-pager | tail -200
Step 10: Enable UFW (and verify from a second SSH session)
Enable the firewall, but keep your current SSH session open.
sudo ufw enable
From a second terminal, SSH in again. Once the second login succeeds, you can close the first session.
Check status and rule ordering:
sudo ufw status numbered
If a rule is wrong, delete it by number:
sudo ufw delete 3
Step 11: Add practical hardening rules for hosting environments
These rules are optional. They match how many hosting servers are operated in practice.
Allow a monitoring agent from a specific IP
If you run Netdata or a similar dashboard, keep it off the public internet. Allow access only from your VPN or admin IP.
sudo ufw allow from 203.0.113.10 to any port 19999 proto tcp
If you’re building a monitoring baseline, follow Server Monitoring Setup Guide (2026) and keep access tight.
Block noisy ports you never use
With default-deny inbound, you don’t need explicit “deny” rules. Some teams still add them for documentation.
This is common during migrations, audits, or handoffs.
sudo ufw deny 23/tcp # telnet
sudo ufw deny 21/tcp # ftp (use SFTP instead)
If clients need file access, use SFTP with chroot and keys. It avoids plaintext transfers and reduces password reuse. See SFTP Setup Guide (2026).
Protect an admin panel behind an SSH tunnel instead of opening ports
For internal dashboards (Redis admin, database admin UI, Netdata), an SSH tunnel is often the cleanest option. You keep the port private and still get easy access.
ssh -L 8080:127.0.0.1:8080 user@your-vps-ip
Then browse http://127.0.0.1:8080 locally. For a step-by-step walkthrough, use SSH Tunnel Setup Guide Tutorial (2026).
Step 12: Quick diagnostics if a website “randomly” stops working
After firewall changes, failures often look like app bugs. You might see timeouts, broken webhooks, or “ERR_CONNECTION_RESET”.
Start with quick checks before you chase the wrong layer.
Confirm ports are open locally
sudo ss -lntp | egrep ':22|:80|:443'
curl -I http://127.0.0.1/
curl -Ik https://127.0.0.1/
Confirm UFW isn’t blocking (look at logs)
sudo tail -200 /var/log/ufw.log 2>/dev/null || true
sudo journalctl -k --no-pager | tail -200
Test externally from another machine
nc -vz your.vps.ip.address 22
nc -vz your.vps.ip.address 80
nc -vz your.vps.ip.address 443
If SSH locks you out, the fastest recovery is usually your provider console (out-of-band access). For a systematic recovery flow, see Firewall Troubleshooting Tutorial (2026).
Step 13: A baseline UFW ruleset for a typical hosting VPS (copy, then tailor)
This example assumes:
- SSH on 22
- Web on 80/443
- No inbound mail hosting
- Optional admin IP restrictions
sudo ufw --force reset
sudo ufw default deny incoming
sudo ufw default allow outgoing
# SSH (option A: open to world)
sudo ufw allow 22/tcp
sudo ufw limit 22/tcp
# Web
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
# Optional: allow Netdata only from admin IP
# sudo ufw allow from 203.0.113.10 to any port 19999 proto tcp
sudo ufw logging low
sudo ufw enable
sudo ufw status verbose
If you’re migrating sites and doing DNS cutovers, do firewall work before you flip traffic. This reduces moving parts and avoids surprises.
For planning, use DNS Cutover Tutorial (2026).
Step 14: Maintenance checklist (keep it correct over time)
- After every new service install: run
ss -lntup, then explicitly allow only the needed port(s). - After major updates: confirm UFW is enabled and rules still exist (
ufw status numbered). - Quarterly: remove old allow rules for services you retired.
- Before marketing campaigns: validate 80/443 and any webhook endpoints (payment gateways often hit your site from fixed IP ranges).
- After incident response: tighten panel access and require IP allowlisting where feasible.
Summary: a hosting-safe firewall is boring—and that’s the point
The pattern is reliable. Default-deny inbound, allow only required ports, and put SSH rules in place before you enable UFW.
Follow that, and you reduce attack surface without avoidable downtime.
If you run client sites, hosting is easier with stable networking, predictable images, and optional admin help. For production workloads, consider a HostMyCode VPS. If you’d rather hand off routine hardening and checks, use managed VPS hosting.
If you’re setting up a new hosting server and want a clean, secure baseline from day one, start on a HostMyCode VPS with predictable networking and full root control. If you prefer fewer operational chores, managed VPS hosting can handle routine security and maintenance while you focus on your sites and customers.
FAQ
Will UFW break my website?
Not if you explicitly allow 80/tcp and 443/tcp, and your web server actually listens on those ports. Most “breaks” happen when people enable UFW before allowing web/SSH ports.
Should I open port 22 to the world?
Allowlisting SSH to trusted IPs or using a VPN/bastion is safer. If you can’t, keep it on 22 (changing ports doesn’t buy much), use keys, and apply ufw limit.
Do I need to allow port 53 for DNS?
For a typical web hosting VPS, no. Outbound DNS is allowed by default when you allow outgoing traffic. You only open 53 inbound if your server is a public DNS resolver/authoritative server.
What’s the fastest way to recover if I lock myself out?
Use your provider’s console (out-of-band access), then run ufw disable or fix rules and re-enable. Keep at least one fallback method before doing firewall work.
Should I use UFW or raw iptables?
UFW is easier to audit and maintain for most hosting servers. If you need a highly customized ruleset (complex NAT, multi-interface routing), raw iptables/nftables can be a better fit—but expect more operational overhead.