
How to Set Up a Firewall (UFW) for Ubuntu Server
Ubuntu Server comes with an easy-to-use firewall tool called UFW (Uncomplicated Firewall). It simplifies managing firewall rules and enhances server security. In this guide, we’ll walk you through setting up UFW on your Ubuntu Server.
Step 1: Install UFW (If Not Installed)
Most Ubuntu installations include UFW by default. However, if it’s not installed, run:
sudo apt update && sudo apt install ufw
Step 2: Enable UFW
Before enabling UFW, check its status:
sudo ufw status
To enable it, run:
sudo ufw enable
Step 3: Allow Essential Services
To avoid losing SSH access, allow SSH connections:
sudo ufw allow OpenSSH
If using a custom SSH port, allow it explicitly (e.g., port 2222):
sudo ufw allow 2222/tcp
Step 4: Allow Specific Ports
For a web server (HTTP and HTTPS):
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
For other services, adjust the rules accordingly.
Step 5: Deny All Incoming Traffic by Default
For better security, set the default incoming policy to deny:
sudo ufw default deny incoming
sudo ufw default allow outgoing
Step 6: Enable UFW Logging (Optional)
To log firewall activity:
sudo ufw logging on
Step 7: Reload and Verify UFW Rules
Reload UFW to apply changes:
sudo ufw reload
Check the current rules:
sudo ufw status verbose
Step 8: Disable UFW (If Needed)
If you need to disable UFW, run:
sudo ufw disable
Conclusion
Setting up UFW on your Ubuntu Server is a simple yet effective way to enhance security. By carefully configuring rules and allowing only necessary services, you can protect your server from unauthorized access.
How to Set Up a Firewall (UFW) for Ubuntu Server (F.A.Q)
How do I check if UFW is installed?
Run sudo ufw status
. If UFW is not installed, use sudo apt install ufw
.
How can I reset UFW to default settings?
Run sudo ufw reset
, then reconfigure the rules.
What happens if I enable UFW without allowing SSH?
If you enable UFW without allowing SSH, you might get locked out of your server. Always allow SSH access before enabling UFW.
Can I allow only specific IPs through UFW?
Yes, for example, to allow SSH from a specific IP:sudo ufw allow from 192.168.1.100 to any port 22