Key takeaways
- Deny incoming by default and allow only required ports.
- Allow SSH before enabling UFW to avoid lockout.
- Provider firewalls and UFW must both allow a port.
UFW (Uncomplicated Firewall) is the simplest way to manage firewall rules on Ubuntu.
Default policy
Deny incoming connections and allow outgoing ones:
sudo ufw default deny incoming
sudo ufw default allow outgoing
Allow what you need
Always allow SSH before enabling the firewall:
sudo ufw allow OpenSSH
Then the services you run:
sudo ufw allow 'Nginx Full' # ports 80 and 443
sudo ufw allow 25,465,587/tcp # only if you run a mail server
Restrict a service to one IP address — for example a database accessed only by your app server:
sudo ufw allow from 198.51.100.7 to any port 3306 proto tcp
Enable and check
sudo ufw enable
sudo ufw status verbose
Rate-limit SSH
Slow down password-guessing by limiting repeated connections:
sudo ufw limit OpenSSH
Remove a rule
sudo ufw status numbered
sudo ufw delete 3