There is a lot of attempts on the internet which try to do it with iptables. Don't do it. For most cases you just need this jucy tool called ufw, also known as Uncomplicated Firewall.

All you need:

apt install ufw
ufw default deny
ufw default allow outgoing
ufw allow 22/tcp
ufw allow 80/tcp
ufw allow 443/tcp
ufw allow 53
ufw enable

This will close inbound ports apart:

  • HTTP (80)
  • HTTPS (443)
  • SSH (22) - needed to connect to the server

The rules will be persisted after any reboot.

Check the status:

ufw status numbered

ℹ We recommend to allow this set of ports for any webserver, if you need any additional ports open for debug, e.g. MySQL/Postgres/Mongo etc, use SSH tunneling. Also SQL UI-based tools have built-in SSH tunneling (you can just specify SSH key and a host and it will all work over secured 22 port)

ℹ Some rare dedicated server providers might need some system ports to operate (rarly this happens with VPS instances), better google "How to Configure a Firewall on Your Server" for certain provider