How to set up a firewall with UFW
Updated 7/20/2026
A firewall allows only the ports you need and blocks the rest. UFW (Uncomplicated Firewall) makes that simple on Ubuntu.
1. Install
apt-get update -y
apt-get install -y ufw
2. Allow SSH before enabling
Very important: allow SSH first, otherwise you lock yourself out:
ufw allow OpenSSH
3. Allow web services
ufw allow 80/tcp
ufw allow 443/tcp
4. Enable the firewall
ufw enable
ufw status verbose
5. Useful rules
# allow a port only from a specific IP
ufw allow from 1.2.3.4 to any port 3306
# delete a rule
ufw delete allow 80/tcp
The golden rule
Open only the strictly necessary ports. A database, for example, should not be publicly exposed, see Connect to a remote database. Continue with fail2ban protection.
Put this guide into practice on your own VPS
EU cloud servers, billed hourly, ready in minutes, with one-click installs for dozens of apps.
See pricingRelated tutorials
How to scan your server for malware with ClamAV
Install ClamAV, an open-source antivirus, and periodically scan your server for infected files.
Updated 7/20/2026SecurityHow to check which ports are open on your server
Find out which services are listening for connections on your server and close what you do not need, for less exposure.
Updated 7/20/2026SecurityHow to add security headers to your website
A few HTTP headers protect your visitors from common attacks like clickjacking and content injection.
Updated 7/20/2026