How to Set Up a Firewall on Your VPS
What is a Firewall?
A firewall is like a security guard for your server. It controls what can connect to your VPS and what cannot.
A firewall helps keep your VPS safe by blocking bad connections and only allowing the ones you want.
Why Do You Need a Firewall?
- Stop hackers from getting into your server
- Block unwanted traffic that could slow down your VPS
- Only allow safe connections to your websites and apps
- Protect your data from being stolen
Important
Always be careful when setting up a firewall. If you block the wrong ports, you might lose access to your server!
Setting Up UFW (Uncomplicated Firewall)
UFW is the easiest firewall to use on Linux servers. It comes pre-installed on Ubuntu and many other Linux systems.
Step 1: Check if UFW is Installed
sudo ufw statusIf it says "Status: inactive", UFW is installed but not running.
Step 2: Set Default Rules
# Block all incoming connections by default
sudo ufw default deny incoming
# Allow all outgoing connections
sudo ufw default allow outgoingStep 3: Allow SSH (Very Important!)
# Allow SSH connections (port 22)
sudo ufw allow sshWarning
If you don't allow SSH, you will lose access to your server! Always do this first.
Step 4: Allow Web Traffic (if you have a website)
# Allow HTTP (port 80)
sudo ufw allow 80
# Allow HTTPS (port 443)
sudo ufw allow 443Step 5: Allow Game Server Ports (if needed)
# Example: Allow Minecraft server (port 25565)
sudo ufw allow 25565
# Example: Allow FiveM server (port 30120)
sudo ufw allow 30120Step 6: Turn On the Firewall
sudo ufw enableStep 7: Check Your Firewall Status
sudo ufw status verboseCommon Ports You Might Need
| Port | What it's for | Command |
|---|---|---|
| 22 | SSH (always allow this!) | sudo ufw allow 22 |
| 80 | HTTP websites | sudo ufw allow 80 |
| 443 | HTTPS websites | sudo ufw allow 443 |
| 21 | FTP | sudo ufw allow 21 |
| 3306 | MySQL database | sudo ufw allow 3306 |
| 25565 | Minecraft server | sudo ufw allow 25565 |
| 30120 | FiveM server | sudo ufw allow 30120 |
How to Remove a Rule
If you made a mistake and need to remove a rule:
# Remove a rule by port number
sudo ufw delete allow 80
# Or remove by rule number (check with ufw status numbered)
sudo ufw delete 1Testing Your Firewall
You can test if your firewall is working:
# Check what ports are open
sudo ufw status
# Test if a port is reachable (from another computer)
telnet your-server-ip 80Good Job!
Your VPS is now much safer with a firewall running. Remember to only open the ports you actually need!