How do I configure a firewall on Linux?
Choosing a tool
Most Linux systems use either UFW (Uncomplicated Firewall) or firewalld as a front end to iptables or nftables. Ubuntu and Debian typically ship UFW; RHEL, CentOS, and Fedora use firewalld. Both are easier than writing raw iptables rules.
If you're on a cloud server, also check the provider's security group or network firewall — it may block traffic before it reaches your server, so you need to allow ports in both places.
Basic UFW commands
Before enabling UFW, allow SSH so you don't lock yourself out: sudo ufw allow ssh (or allow 22/tcp). Then enable with sudo ufw enable. Check status with sudo ufw status verbose.
To allow web traffic, run sudo ufw allow 80/tcp and sudo ufw allow 443/tcp. You can allow by service name (e.g., sudo ufw allow 'Nginx Full') or by port and protocol. Deny rules: sudo ufw deny 3306. To delete a rule, use sudo ufw delete allow 80/tcp.
- sudo ufw allow ssh
- sudo ufw allow 80/tcp
- sudo ufw allow 443/tcp
- sudo ufw enable
- sudo ufw status verbose
Basic firewalld commands
On RHEL-based systems, firewalld uses zones. The default zone is usually public. To allow a service: sudo firewall-cmd --permanent --add-service=http, then sudo firewall-cmd --reload. For a port: sudo firewall-cmd --permanent --add-port=8080/tcp.
Check active rules with sudo firewall-cmd --list-all. To remove a rule, replace --add with --remove and reload. Always use --permanent for changes that should survive a reboot.
Common mistakes
- Enabling a firewall without allowing SSH first, which locks you out of the server.
- Forgetting to reload firewalld after adding rules, so changes don't take effect.
- Assuming the Linux firewall is enough when the cloud provider also has a network firewall that must be configured separately.
