What is a port?
A server is like a building with many numbered doors. Each door is a port. Web traffic uses port 80 and 443. Remote login with SSH uses port 22.
A firewall is the guard at the doors. It keeps most doors locked. When you install a program that needs a door, you must tell the firewall to open it.
UFW stands for Uncomplicated Firewall. It comes with Ubuntu and is easy to use.
Before you start
Open only the ports you really need. Every open door is a chance for attackers. Also, make sure SSH is allowed before you turn the firewall on, or you will lock yourself out.
Steps
- Connect to your server with SSH. Use root, or add
sudobefore each command. - Check the state of the firewall:
sudo ufw status
This shows if UFW is active and lists the open ports.
- Allow SSH first, so you never lose access:
sudo ufw allow 22/tcp
If you use a different SSH port, use that number instead.
- Open the port you need. This example opens port 8080:
sudo ufw allow 8080/tcp
TCP is the most common way data travels. Use udp if your program asks for that.
- For web servers, you can use a ready-made name:
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
- Turn the firewall on, if it was off:
sudo ufw enable
- Check the list again:
sudo ufw status numbered
You should see your new rule in the list.
Limit who can use a port
You can open a port for one IP address only. This is safer:
sudo ufw allow from 203.0.113.5 to any port 3306 proto tcp
This lets only that address reach port 3306.
Close a port
sudo ufw delete allow 8080/tcp
This removes the rule you added.
Quick recap
- A port is a numbered door on your server.
- Allow SSH first, then add other ports with
ufw allow. - Open only what you need, and limit by IP when you can.
- Check with
sudo ufw status. - Close ports you no longer use.