Setting up a Linux firewall with UFW and firewalld
Make sure your server can be reached only on the ports you actually need. In this guide you will set up a default-deny firewall with UFW on Ubuntu and Debian and with firewalld on AlmaLinux, without locking yourself out, and verify it from outside.
The basic approach: deny by default, open what you need
A firewall accepts or rejects incoming connections according to its rules. A solid configuration rests on one principle: deny all incoming traffic by default and open only the ports of the services you publish. Traffic leaving the server and replies to connections you started are allowed; because the firewall tracks connection state (stateful), they need no separate rules.
Hostimor servers are an unmanaged service, so filtering the traffic that reaches your server is your responsibility. UFW and firewalld are tools that manage the netfilter framework (nftables/iptables) in the Linux kernel. Pick the one that matches your distribution and never run both at the same time:
- Ubuntu 24.04 / 26.04: UFW usually comes preinstalled but inactive.
- Debian 12 / 13: you install UFW with
apt install ufw. - AlmaLinux 9: firewalld is used; if it is not installed or running, enable it with the steps below.
Before writing rules, see which service listens on which address. 0.0.0.0 or * marks services listening on all interfaces, which are exposed to the internet without a firewall; 127.0.0.1 marks services reachable only from the server itself.
# Listening TCP/UDP services, their addresses and process names
ss -tulpnOur servers have IPv4 addresses only. By default, UFW also creates an IPv6 counterpart for every rule (shown with (v6) in the output); these rules do no harm and you do not need to change the setting.
Allow SSH first, then enable the firewall
The most common mistake is enabling the firewall without allowing the SSH port: the current session may stay open for a while, but new connections are refused. If you moved SSH to a port other than 22, write the rule for that port. When working on a remote server, a safety net is also a good habit: the command below creates a temporary systemd timer that disables UFW on its own after five minutes. Once you have confirmed that your connection works, you cancel the timer; if you forget, UFW turns off and you need to enable it again with ufw enable.
# Right before enabling UFW: a temporary timer that disables UFW after 5 minutes
systemd-run --on-active=5m --unit=ufw-safety /usr/sbin/ufw disable
# ... add your rules, run ufw enable, test SSH in a new terminal ...
# If the connection works, cancel the timer
systemctl stop ufw-safety.timerIf you have locked yourself out, connect to the server independently of the network with the VNC Console in the client area and restore access with ufw disable (on AlmaLinux, firewall-cmd --add-service=ssh). Then fix the rule and enable the firewall again.
UFW on Ubuntu and Debian
The sequence below sets up a basic configuration that allows only SSH and web traffic. Run the commands as root or prefix them with sudo.
apt update && apt install -y ufw # Needed on Debian; usually preinstalled on Ubuntu
ufw status verbose # Initially: Status: inactive
ufw default deny incoming
ufw default allow outgoing
ufw allow OpenSSH # If you moved SSH: ufw allow 2222/tcp
ufw allow 80,443/tcp # If you serve a website
ufw enable # Answer the prompt with y
ufw status verboseOpenSSH is an application profile shipped with the OpenSSH server package. Profiles define ports by service name; when you install Nginx or Apache, new profiles such as Nginx Full are added:
ufw app list
ufw app info "Nginx Full"
ufw allow "Nginx Full" # Can be used instead of the 80,443/tcp ruleRate limiting and IP-specific rules
ufw limit refuses new connections from an IP address that has tried to open 6 or more connections in the last 30 seconds. It is a good extra layer for SSH, but it can also affect automation tools that open many connections in a short time. Open management services such as databases only to known static IP addresses. If you also want SSH open to your office IP only, add the IP-specific rule and delete the general OpenSSH rule; keep in mind that you will need the VNC Console if your IP changes.
ufw limit OpenSSH # Turns the existing allow rule into a limit rule
ufw allow from 198.51.100.25 to any port 3306 proto tcp # MariaDB/MySQL open to your office IP onlyListing and deleting rules, and logs
Because numbers shift after a deletion, list the rules again each time if you delete more than one. Blocked connections are written to /var/log/ufw.log when rsyslog is installed and to the kernel log otherwise; a default Debian 12 or 13 installation does not include rsyslog.
ufw status numbered
ufw delete 3 # Take the number from the list; numbers shift after each deletion
ufw logging low # Log blocked packets
journalctl -k | grep "UFW BLOCK" # Without rsyslog; with rsyslog: /var/log/ufw.logfirewalld on AlmaLinux
firewalld groups rules into zones; your network interface is usually in the default public zone. There are two configuration layers: the runtime configuration takes effect immediately but is lost on a reload or reboot, while the permanent configuration takes effect after --reload and persists.
dnf install -y firewalld # If it is not installed
systemctl enable --now firewalld
firewall-cmd --state
firewall-cmd --get-default-zone
firewall-cmd --get-active-zones
firewall-cmd --list-allOn AlmaLinux, the ssh service is open in the public zone by default; on most installations cockpit and dhcpv6-client are listed as well. Remove the services you do not use and add the ones you need:
firewall-cmd --permanent --add-service=ssh
firewall-cmd --permanent --add-service=http --add-service=https
firewall-cmd --permanent --add-port=2222/tcp # If you moved SSH
firewall-cmd --permanent --remove-service=cockpit # If you do not use the Cockpit web console
# MariaDB/MySQL open to your office IP only (rich rule)
firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="198.51.100.25" port port="3306" protocol="tcp" accept'
firewall-cmd --reload
firewall-cmd --list-all
firewall-cmd --list-rich-rulesTrying a risky change in the runtime configuration first is a safe method. Add the rule without --permanent, test it and, if everything works, make it permanent. If a mistake cuts off your access, rebooting the server from the panel with Restart Server brings back the last permanent configuration.
# Without --permanent: effective immediately, lost on reload
firewall-cmd --add-service=http
# After testing, make the runtime configuration permanent
firewall-cmd --runtime-to-permanentWhich ports should be open?
The table below is a general starting point for common services. The safest method is to have management services listen on the local address only (for example bind-address = 127.0.0.1 in MariaDB); the firewall adds a second layer on top of that.
| Service | Port | Open to everyone? |
|---|---|---|
| SSH | 22/tcp or a custom port | Yes, or to your static IP addresses only; with key-based login and limit. |
| HTTP / HTTPS | 80/tcp, 443/tcp | Yes if you serve a website. Port 80 must also stay open for Let's Encrypt HTTP validation. |
| MariaDB / MySQL | 3306/tcp | No; local or specific IP addresses only. |
| PostgreSQL | 5432/tcp | No; local or specific IP addresses only. |
| Redis | 6379/tcp | No; a default installation may not ask for a password. |
| cPanel / WHM | 2083, 2087/tcp | If you installed the panel; with an IP restriction where possible. |
| Plesk | 8443/tcp | If you installed the panel; with an IP restriction where possible. |
| DirectAdmin | 2222/tcp | If you installed the panel; in that case, do not move SSH to 2222. |
| Email (SMTP, IMAP) | 25, 465, 587, 993/tcp | Only if you run a mail server. |
When rules are bypassed: Docker and control panels
Docker: for ports published with ports:, Docker writes its own NAT and forwarding rules into netfilter. This traffic is forwarded to the container without passing through the input (INPUT) chain that UFW evaluates; even if ufw status shows the port as closed, a mapping such as 8080:80 is exposed to the outside world. On systems with firewalld, also assume that published ports can be opened regardless of zone rules, and test from outside. The fix is to publish ports on the local address only, as in 127.0.0.1:8080:80, and put a reverse proxy such as Nginx in front; see the Docker installation guide for details.
Control panels: cPanel, Plesk or DirectAdmin may use their own firewall tool (for example CSF or Imunify). When two tools try to manage the same rules, they overwrite each other's settings. If you installed a panel, use the tool it recommends and disable UFW or firewalld accordingly; see the control panel guide for details.
A firewall does not stop brute-force attempts against open ports. For SSH, switch to key-based login and block IP addresses that keep trying with Fail2ban; Fail2ban can add its ban rules through UFW or firewalld.
Verify the rules from outside, and common errors
The lists on the server show that a rule was written, not that access is actually blocked. Do the final check from another computer. Use scanning tools only against your own server; scanning other people's systems without permission violates the Acceptable Use Policy.
# From another computer, against your own server only
nmap -Pn 203.0.113.10
nmap -Pn -p 22,80,443,3306 203.0.113.10
nc -vz 203.0.113.10 3306The ports you opened should show as open and the others as filtered or closed. If a port you never opened shows as open, it may be a port published by Docker or a rule added by a panel; on the server, find the process listening on it with ss -tulpn.
ERROR: Could not find a profile matching 'OpenSSH': the profile is not available; write the rule with the port number instead (ufw allow 22/tcp).FirewallD is not running: the service is stopped; start it withsystemctl enable --now firewalld.- A firewalld rule has no effect: the rule may have been added with
--permanentwithout a--reload, or added to the runtime configuration only and lost on reload. Check withfirewall-cmd --list-all. - The port is open but connections fail: the service may be listening on
127.0.0.1; in that case the problem is the service's listening address, not the firewall.
Frequently asked questions
Can I use UFW and firewalld together?
No. Both manage the same netfilter rules and can overwrite each other's rules. Use UFW on Ubuntu and Debian and firewalld on AlmaLinux; do not install the other one, or disable it.
Should I restrict outgoing traffic too?
For most servers, there is no need. Package updates, DNS queries, time synchronization and sending email all require outgoing connections. If you decide to restrict outgoing traffic, first list the destinations and ports you need, then add the rules one by one.
Do my rules survive a reboot?
If UFW is enabled, its rules are loaded automatically at boot; user rules are kept in /etc/ufw/user.rules. In firewalld, permanent rules are stored in XML files under /etc/firewalld/zones/, while rules you added without --permanent are lost.
Related articles
- Sign in with an SSH key and turn off password login
- Blocking brute-force attacks on SSH and web services with Fail2ban
- Installing Docker and Docker Compose: watch out for ports that bypass your firewall
- Reach your server without SSH or RDP using the VNC Console
- Your first 30 minutes on a new VDS or VPS: a post-setup checklist
Thanks for your feedback!