Skip to main content

Linux Firewall

Updated: October 29, 2026
By Willya Randika

A Linux firewall decides which network packets may enter, leave, or be forwarded. On modern servers, the common tools are UFW as a simple frontend, nftables, and legacy iptables. The goal is not only to block attacks but also to reduce accidentally open ports.

Basic principles

Use default deny incoming and allow only required ports. Allow established and related connections so existing sessions keep working. Restrict SSH by source IP when possible. If the server uses IPv6, configure IPv6 rules too, because IPv4-only rules can leave a gap.

UFW example:

sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw limit OpenSSH
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw enable
sudo ufw status verbose

ufw limit throttles repeated connection attempts on that port. For stricter access, use sudo ufw allow from 203.0.113.10 to any port 22 proto tcp, then remove the open SSH rule.

nftables

sudo nft add table inet filter
sudo nft add chain inet filter input '{ type filter hook input priority 0; policy drop; }'
sudo nft add rule inet filter input ct state established,related accept
sudo nft add rule inet filter input iif lo accept
sudo nft add rule inet filter input tcp dport { 22, 80, 443 } accept

Rules are evaluated in order. Put the accept for established connections before drop rules. Save the configuration so it survives a reboot.

Docker and IPv6

Docker often adds its own NAT rules that bypass UFW. A port published with -p 5432:5432 can be open to the internet even when UFW blocks it. Bind to 127.0.0.1:5432:5432, use Docker networks, or add rules in the DOCKER-USER chain.

Test from another machine with nmap or nc. Do not trust ufw status alone. For IPv6, make sure the nftables inet family or ip6tables rules cover the same ports.

Common mistakes

Enabling the firewall before allowing SSH can lock you out. Have provider console access ready. Exposing database ports is also dangerous. MySQL and PostgreSQL should listen on localhost or a private network.

A firewall is not the only security control. Still patch, use 2FA, and restrict logins. A firewall complements SSH, brute force protection, and a WAF.

FAQ

UFW or nftables: which should I use?

UFW is enough for simple, readable rules. nftables is more flexible for complex rules, NAT, and logging. Do not mix them without understanding the translation.

Can a firewall replace fail2ban?

Not entirely. A firewall restricts ports. Fail2ban reacts to failed-login patterns. They can be used together.

Why is a Docker port still open after enabling UFW?

Docker writes its own NAT and filter rules. Use localhost binding, private networks, or DOCKER-USER rules to control them.

Disclaimer: Hosting Wiki articles are prepared for educational and reference purposes. Hosting technology keeps evolving, so some technical details may change over time.