Your server currently accepts connections on every port anything is listening on. The default posture should be the opposite: nothing is reachable unless you said so.
UFW, in the correct order
The order matters. Allow SSH before enabling the firewall, or you will disconnect yourself.
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow OpenSSH # or: sudo ufw allow 2222/tcp
sudo ufw enable
sudo ufw status verbose
Read that status output before doing anything else. If SSH is not listed, do not close your current session — fix it first.
When you reach the web chapter, add:
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
Those three are all the world needs. Databases, caches, admin panels and application ports stay closed and are reached through SSH tunnels.
The Docker exception, which surprises people
Worth knowing before the next chapter: Docker writes its own
iptables rules and can bypass UFW. A container published with
-p 5432:5432 may be reachable from the internet even though UFW
says that port is denied.
The fix is to bind published ports to localhost:
# reachable only from the server itself
-p 127.0.0.1:5432:5432
Do that for every service that does not need to be public. It has caught out a great many people who believed their firewall covered them.
fail2ban
sudo apt install fail2ban -y
sudo systemctl enable --now fail2ban
sudo fail2ban-client status sshd
It watches the logs and temporarily bans addresses that fail repeatedly. With key-only authentication already in place this is a second layer rather than the main defence, but it keeps your logs readable.
Automatic security updates
The most common reason a server is compromised is a known vulnerability nobody patched.
sudo apt install unattended-upgrades -y
sudo dpkg-reconfigure --priority=low unattended-upgrades
Check it is actually doing something:
cat /var/log/unattended-upgrades/unattended-upgrades.log | tail -20
Security updates install themselves; kernel updates still need a reboot. Either schedule one or check occasionally for:
ls /var/run/reboot-required 2>/dev/null && echo "reboot needed"
A five-minute audit
# what is listening, and on which interface
sudo ss -tulpn
# recent failed logins
sudo grep "Failed password" /var/log/auth.log | tail
# who can use sudo
getent group sudo
In ss -tulpn, look at the address column. Something bound to
127.0.0.1 is local only. Something on 0.0.0.0 is
listening to the world and should have a reason.