I have a new VPS with SSH, Nginx and MySQL. I want to block everything except SSH, HTTP and HTTPS. What are the right ufw commands and the order to avoid losing access?
DEV3 Developer Forum
How do I set up a basic firewall with ufw on an Ubuntu server without locking myself out?
Ask a question
Every post is reviewed first. Usually reviewed within 24 hours.
dev3 ·
0
1 reply
dev3 · Accepted answer
Allow SSH before enabling the firewall, otherwise you cut your own session.
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow OpenSSH # or: sudo ufw allow 22/tcp
sudo ufw allow 'Nginx Full' # 80 and 443
# sudo ufw allow 80,443/tcp # equivalent without the app profile
sudo ufw enable
sudo ufw status verbose
Notes
- If SSH runs on a custom port, allow that port, not 22.
- Rate limit SSH brute force attempts:
sudo ufw limit OpenSSH. - MySQL (3306) and MongoDB (27017) should not be opened to the world. The app on the same host uses localhost. For a remote admin, allow a single IP:
sudo ufw allow from 203.0.113.10 to any port 3306 proto tcp, or use an SSH tunnel:ssh -L 3307:127.0.0.1:3306 user@host. - Remove rules by number:
sudo ufw status numbered, thensudo ufw delete 3. - IPv6: make sure
IPV6=yesin/etc/default/ufwso rules also cover IPv6.
Docker caveat. Docker publishes ports by editing iptables directly, which bypasses ufw rules. A container started with -p 3306:3306 can be reachable from the internet even if ufw denies it. Bind to localhost (127.0.0.1:3306:3306), do not publish internal services, or manage rules in the DOCKER-USER chain.
Cloud providers also have their own security groups; both layers must allow the traffic.
Lockout recovery: use the provider's web console, then sudo ufw disable and fix the rule.
Test from another machine with nmap -Pn your.host or an online port check, and re-run it after changes.
0