Configure UFW Firewall on Ubuntu VPS to prevent attacks

Table of Contents

  1. What is UFW and Why Use a Firewall
  2. Prerequisites
  3. Check Status and Enable UFW
  4. Set Default Policies
  5. Allow Required Ports
  6. Manage UFW Rules
  7. Block Suspicious IPs
  8. Rate Limiting
  9. Logging and Monitoring
  10. Common UFW Commands
  11. FAQ
  12. Summary

What is UFW and Why Do You Need a Firewall on VPS?

UFW (Uncomplicated Firewall) is a frontend for iptables that ships with Ubuntu, making firewall management significantly easier without needing to write complex iptables syntax.

A VPS connected directly to the internet is constantly exposed to attacks — SSH brute force attempts, port scanning, and unauthorized access to services. A firewall acts as a gatekeeping layer, inspecting every packet entering and leaving your VPS.

💡 Key Fact: A VPS without a firewall is typically port-scanned within minutes of deployment. If any vulnerable service is exposed, exploitation can happen almost immediately.

UFW is ideal for:

Prerequisites

Before starting, ensure you have:

⚠️ Critical: Always allow your SSH port BEFORE enabling UFW. If you enable UFW without allowing SSH, new connections will be blocked and you'll need provider console access to fix it.

Check Status and Enable UFW

First, verify UFW is installed and check its current status:

sudo apt update
sudo apt install ufw -y

# Check current status
sudo ufw status verbose

If UFW is not yet enabled, you'll see Status: inactive. Configure basic rules before enabling.

ℹ️ Ubuntu 20.04+ comes with UFW pre-installed — no additional installation needed.

Set Default Policies

Default policies define baseline firewall behavior before any specific rules. Best practice is "deny all incoming, allow all outgoing":

# Block all incoming by default
sudo ufw default deny incoming

# Allow all outgoing (VPS can freely send traffic out)
sudo ufw default allow outgoing

This "whitelist" approach is more secure than allowing everything and blocking specific threats later.

Allow Required Ports (SSH, HTTP, HTTPS)

After setting default deny, open the necessary ports before enabling UFW:

# SSH (critical — must do before ufw enable)
sudo ufw allow ssh
# Or specify the port directly
sudo ufw allow 22/tcp

# Web server
sudo ufw allow http
sudo ufw allow https
# Equivalent to:
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp

# If SSH uses a custom port (e.g., 2222)
sudo ufw allow 2222/tcp

# Enable UFW (only AFTER allowing SSH)
sudo ufw enable

After running ufw enable, the system prompts for confirmation. Type y to proceed.

Manage UFW Rules

View all existing rules with numbers (useful for targeted deletion):

# Simple view
sudo ufw status

# Detailed numbered view
sudo ufw status numbered

# Delete rule by number (e.g., delete rule #3)
sudo ufw delete 3

# Delete rule by specification
sudo ufw delete allow 8080/tcp

ℹ️ Deleting with ufw delete allow removes both IPv4 and IPv6 rules simultaneously.

Block Suspicious IPs

If you detect IPs repeatedly scanning or attacking your server, block them immediately:

# Block a single IP
sudo ufw deny from 192.168.1.100

# Block an entire subnet
sudo ufw deny from 10.20.0.0/16

# Block IP from accessing a specific port
sudo ufw deny from 203.0.113.1 to any port 22

# View currently blocked IPs
sudo ufw status | grep DENY

Rules with deny take effect immediately and are evaluated before later allow rules.

Rate Limiting with UFW

UFW has built-in rate limiting that helps prevent brute force attacks without requiring Fail2Ban:

# Rate limit SSH connections
sudo ufw limit ssh
# Or
sudo ufw limit 22/tcp

The limit command blocks IPs that attempt more than 6 connections within 30 seconds, auto-unblocking after 60 seconds.

💡 For servers with many login users, combine ufw limit ssh with Fail2Ban for multi-layer protection.

Logging and Monitoring

Enable logging to track what your firewall is blocking:

# Enable logging (levels: low, medium, high)
sudo ufw logging low

# Watch logs in real-time
sudo tail -f /var/log/ufw.log

# View logs via journalctl
sudo journalctl -f | grep UFW

# Count blocked connections in the last 24 hours
sudo grep -c "UFW BLOCK" /var/log/ufw.log 2>/dev/null || \
  sudo journalctl --since "24 hours ago" | grep -c "UFW BLOCK"

The low logging level is ideal for production — it records blocked packets without excessive I/O overhead.

Common UFW Commands (Reference Table)

Command Effect
sudo ufw status verboseShow status and all rules
sudo ufw enableEnable UFW
sudo ufw disableDisable UFW (keeps rules)
sudo ufw resetReset to defaults (deletes all rules)
sudo ufw allow 80/tcpOpen port 80 TCP
sudo ufw deny 3306Block port 3306 (MySQL)
sudo ufw limit sshRate limit SSH
sudo ufw delete allow 80/tcpRemove rule opening port 80
sudo ufw allow from 203.0.113.0/24Allow entire subnet
sudo ufw deny from 198.51.100.0/24Block entire subnet
sudo ufw logging mediumSet log level to medium
sudo ufw app listList available app profiles

Frequently Asked Questions (FAQ)

What is UFW and how does it differ from iptables?
UFW (Uncomplicated Firewall) is a simplified frontend for iptables. While iptables is powerful, its syntax is complex. UFW translates simple commands into iptables rules automatically, making daily firewall management much easier.
Will enabling UFW drop my SSH connection?
If you run ufw allow ssh before ufw enable, your current session remains active. If you forgot to allow SSH, new connections will be blocked. Your current session may persist temporarily, but you'll need VNC console access to add the SSH rule.
How does UFW rate limiting work?
ufw limit blocks IPs that make more than 6 connection attempts within 30 seconds, then auto-unblocks after 60 seconds. It's a quick win for SSH brute force protection without installing additional tools.
Does UFW support IPv6?
Yes, but you need IPV6=yes in /etc/default/ufw first. After that change, rules added will apply to both IPv4 and IPv6 simultaneously.
Can UFW and Fail2Ban work together?
They work together excellently. Fail2Ban detects failed logins from log files and automatically adds UFW/iptables rules to block offending IPs. Using both creates a multi-layer security posture.

Summary

UFW is an easy-to-configure, effective firewall that ships with Ubuntu. With just a few commands, you can:

For VPS requiring higher security, combine UFW with Fail2Ban for comprehensive, multi-layer attack prevention.

Ready to Deploy Your Own Ubuntu VPS?

AsiaGB offers VPS in Thailand, Singapore, and OVHcloud Oregon (US-WEST-OR) with SSD storage, 99% Uptime, and Thai-language support.

View All VPS Plans