Every port a server listens on is a door, and a host firewall decides which doors anyone outside can knock on. When a database is exposed to the internet by accident, the cause is rarely a clever attack: someone started a service that listened on all interfaces and nothing stood in front of it. A firewall turns “everything that listens is reachable” into “only what we allowed is reachable”, and as a DevOps engineer you are the person who writes that list.
In this lesson you learn how Linux filters packets, where the host firewall sits among the other layers of defence, and how to configure it with ufw on Ubuntu and firewalld on Rocky Linux. You also read the real nftables ruleset underneath, deal with the classic Docker surprise and practise a change routine that cannot lock you out.
Warning: This lesson needs the Multipass VM from lesson 1. WSL and containers do not let you manage a real firewall, and multipass shell itself connects over SSH, so the lock-out risk discussed below is real on your lab too.
What a host firewall does
The kernel looks at every packet that arrives and runs it through a list of rules before any program sees it. Each rule matches some properties (source address, destination port, protocol, interface, connection state) and gives a verdict: accept, drop (silently discard) or reject (discard and tell the sender). The first matching rule usually wins; if nothing matches, the chain’s policy applies.
Two policies cover almost every server: deny incoming by default, so nothing from outside gets in unless a rule allows it and a forgotten service stays invisible, and allow outgoing by default, so the server reaches package mirrors, DNS and APIs without a rule for each. High-security environments also filter outgoing traffic (so a compromised process cannot call home), but get these two right first.
Stateful filtering
Modern Linux firewalls are stateful: the kernel’s connection tracking (conntrack) remembers every connection it has seen. When orbit-web-01 asks a package mirror for an update, the reply packets are part of a connection the server started, so they are marked established and accepted even though incoming traffic is denied by default. Without state tracking you would have to open every high port for replies, which is what old stateless firewalls forced people to do.
Drop or reject? A dropped packet leaves the sender waiting for a timeout, which slows scanners and reveals less, so it is the usual internet-facing default. A rejected one fails immediately with “connection refused”, which is kinder on internal networks where colleagues need to debug quickly.
Defence in layers
A packet travelling to Orbit’s database crosses several filters, and each one is owned by a different team or tool. Knowing them saves hours of “but I opened the port!”.
| Layer | Where it lives | Stateful? | Typical Orbit rule |
|---|---|---|---|
| Network ACL | Cloud subnet (AWS NACL, Azure NSG on a subnet) | No: replies need their own rule | Block known bad ranges for the whole subnet |
| Security group | Cloud, attached to the VM’s network interface | Yes | Allow 443 from anywhere to the web servers only |
| Host firewall | The Linux kernel (nftables, driven by ufw or firewalld) | Yes | Allow 5432 on orbit-db-01 only from orbit-web-01 |
| Bind address | The application itself | Not a filter | The API listens on 127.0.0.1:3000, so only nginx on the same box can reach it |
The last row is the strongest of all: a service bound to 127.0.0.1 cannot be reached from the network no matter what the firewalls say. Use ss -tlnp (from lesson 10) to see which addresses your services bind to before you write a single rule. Cloud filters and the host firewall overlap on purpose: if someone loosens a security group in a hurry, the host still says no.
nftables, iptables and the front ends
Inside the kernel, packet filtering is done by netfilter, and since Linux 3.13 the modern way to program it is nftables with the nft command. Its predecessor, iptables, is legacy: on Ubuntu 26.04 and RHEL 10 the iptables command still exists, but it is the iptables-nft compatibility layer that translates old syntax into nftables rules (sudo iptables -V prints (nf_tables) after the version).
You rarely write raw nft rules on a single server. Instead you use a friendly front end that writes them for you:
| Tool | Default on | Model | Strength |
|---|---|---|---|
| ufw | Ubuntu, Debian (optional) | Simple allow/deny list | Readable, quick, hard to get badly wrong |
| firewalld | RHEL, Rocky, Alma, Fedora | Zones with services and ports | Runtime versus permanent changes, D-Bus API for other tools |
| nft directly | Any | Tables, chains, sets, maps | Full power, one atomic file, great for appliances and routers |
Tip: Use one front end per machine. Running ufw and firewalld together, or hand-editing nftables under ufw, produces rules that fight each other and a ruleset nobody understands.
ufw on Ubuntu
ufw (uncomplicated firewall) is installed on Ubuntu but inactive by default: sudo ufw status verbose prints Status: inactive on a fresh server.
Set the defaults and allow SSH first
The order matters. If you enable a deny-incoming firewall before allowing SSH, the next packet of your own session may be dropped and you are locked out. Allow SSH before you enable anything:
$ sudo ufw default deny incoming
Default incoming policy changed to 'deny'
$ sudo ufw default allow outgoing
Default outgoing policy changed to 'allow'
$ sudo ufw limit OpenSSH
Rules updated
Rules updated (v6)
$ sudo ufw enable
Command may disrupt existing ssh connections. Proceed with operation (y|n)? y
Firewall is active and enabled on system startup
default deny incoming/default allow outgoingset the policies, andenableactivates the firewall now and at every boot.limit OpenSSHallows SSH but blocks an address that opens 6 or more connections within 30 seconds: a cheap brake on password-guessing bots. Useallowinstead oflimitfor bastion hosts that legitimately open many sessions, such as an Ansible control node.- Rules are added for IPv4 and IPv6 at once (the “(v6)” line), as long as
IPV6=yesin/etc/default/ufw, which is the default.
Open the web ports for nginx
Orbit’s nginx listens on 80 and 443. Packages can ship application profiles in /etc/ufw/applications.d/ so you allow a name instead of remembering ports:
$ sudo ufw app list
Available applications:
Nginx Full
Nginx HTTP
Nginx HTTPS
OpenSSH
$ sudo ufw allow "Nginx Full"
Rule added
Rule added (v6)
sudo ufw app info "Nginx Full" shows that the profile means 80 and 443/tcp, so sudo ufw allow 80,443/tcp would do the same thing. Note that the API port 3000 is not opened: nginx reaches it over loopback, and ufw never filters the lo interface.
Allow the database only from the web server
On orbit-db-01, PostgreSQL must accept connections from orbit-web-01 (private IP 10.0.1.11) and nobody else:
$ sudo ufw allow from 10.0.1.11 to any port 5432 proto tcp comment 'orbit-web-01 to postgres'
Rule added
from restricts the source, to any port 5432 the destination port, proto tcp the protocol, and comment explains the rule to the next person. Use a subnet such as 10.0.1.0/24 when several web servers need access.
Read, number and delete rules
$ sudo ufw status numbered
Status: active
To Action From
-- ------ ----
[ 1] OpenSSH LIMIT IN Anywhere
[ 2] Nginx Full ALLOW IN Anywhere
[ 3] 5432/tcp ALLOW IN 10.0.1.11 # orbit-web-01 to postgres
[ 4] OpenSSH (v6) LIMIT IN Anywhere (v6)
[ 5] Nginx Full (v6) ALLOW IN Anywhere (v6)
$ sudo ufw delete 3
Deleting:
allow from 10.0.1.11 to any port 5432 proto tcp comment 'orbit-web-01 to postgres'
Proceed with operation (y|n)? y
Rule deleted
Numbers shift after every deletion, so run status numbered again before deleting a second rule. You can also delete by repeating the rule: sudo ufw delete allow "Nginx Full". To insert a rule at a given position (for example a deny from a noisy address that must come before the allows), use sudo ufw insert 1 deny from 203.0.113.50.
Logging: sudo ufw logging low (the default once enabled) logs blocked packets that do not match any rule; medium and high log more and get noisy. Entries carry the prefix [UFW BLOCK] and go to the kernel log, so you find them with journalctl -k -g "UFW BLOCK" or in /var/log/ufw.log when rsyslog is installed. Lesson 18 covers reading logs properly.
firewalld on Rocky Linux
The old orbit-reports box runs Rocky Linux 10, where firewalld is active out of the box. Instead of one list of rules, it groups interfaces and source addresses into zones (public, internal, trusted, drop and others), each with its own allowed services and ports. A fresh server puts its network interface into public, which allows SSH and little else. firewall-cmd --state and --get-active-zones confirm what is running; --list-all shows the whole zone.
$ sudo firewall-cmd --list-all
public (active)
interfaces: eth0
sources:
services: cockpit dhcpv6-client ssh
ports:
rich rules:
Runtime versus permanent
Every firewalld change happens either in the runtime configuration (active now, gone after a reload or reboot) or in the permanent configuration (saved to disk, active after the next reload). This trips up everyone once:
$ sudo firewall-cmd --permanent --add-service=https
success
$ sudo firewall-cmd --permanent --add-port=8443/tcp
success
$ sudo firewall-cmd --reload
success
$ sudo firewall-cmd --list-services
cockpit dhcpv6-client https ssh
--add-service=httpsopens the ports defined in the service file/usr/lib/firewalld/services/https.xml. Prefer services over raw ports: they are self-documenting.--add-port=8443/tcpopens a port with no service definition.--permanentwrites to disk only;--reloadloads the permanent configuration into the running firewall.--remove-serviceand--remove-portundo rules the same way.
The runtime/permanent split doubles as a safety net: add a rule without --permanent, test it, and if it broke something a --reload throws it away. When it works, save it with sudo firewall-cmd --runtime-to-permanent.
Rich rules
For “this port, but only from that address”, firewalld uses rich rules:
$ sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="10.0.1.11/32" port port="5432" protocol="tcp" accept'
success
$ sudo firewall-cmd --reload
success
For several web servers it scales better to put the web servers’ subnet into the internal zone as a source (--zone=internal --add-source=10.0.1.0/24) and allow PostgreSQL in that zone only.
Red Hat and SELinux: opening a port in firewalld is not always enough on RHEL-family systems. If a service listens on a non-standard port, SELinux may also need to allow it (semanage port -a -t http_port_t -p tcp 8443). Check both when “the firewall is open but it still does not work”.
Read the real ruleset with nft
ufw and firewalld are both writing nftables rules in the end, and nft list ruleset shows you what the kernel actually enforces. The output is long; here is the part that matters on orbit-web-01, heavily trimmed (the exact match syntax depends on the iptables-nft version):
$ sudo nft list ruleset
table ip filter {
chain INPUT {
type filter hook input priority filter; policy drop;
counter packets 5120 bytes 412233 jump ufw-before-input
counter packets 1904 bytes 113020 jump ufw-user-input
...
}
chain ufw-user-input {
... tcp dport 22 ... jump ufw-user-limit
... 80,443 ... counter packets 1832 bytes 104512 accept
}
...
}
You can read three useful things here: the INPUT policy is drop, the web ports are accepted, and the counters show that real packets matched. If a counter stays at zero while you test, your traffic is not arriving or is matching an earlier rule. For comparison, a hand-written nftables configuration for the same server fits in a few lines of /etc/nftables.conf:
table inet orbit {
chain input {
type filter hook input priority 0; policy drop;
ct state established,related accept
iif "lo" accept
tcp dport 22 accept
tcp dport { 80, 443 } accept
ip saddr 10.0.1.11 tcp dport 5432 accept
icmp type echo-request accept
}
}
The inet family covers IPv4 and IPv6 in one table, and ct state established,related accept is the stateful rule from the start of this lesson. Load it with sudo nft -f /etc/nftables.conf and enable nftables.service to apply it at boot.
Docker and the ufw surprise
This one catches almost every team once. You run a container on orbit-web-01 with docker run -p 8080:80 nginx, ufw has no rule for 8080, and yet the port is reachable from the internet.
The reason: Docker writes its own netfilter rules. Traffic to a published port is translated (DNAT) to the container’s address before the INPUT chain, and then travels through the FORWARD chain, where Docker’s rules accept it. ufw’s rules live in INPUT, so they never see the packet. ufw status looks perfect while the port is wide open. Ways to handle it, from simplest to most flexible:
- Publish on loopback only.
-p 127.0.0.1:8080:80(or"127.0.0.1:8080:80"in Compose) makes the port reachable only from the host, and nginx on the host proxies to it. This is the right answer for most Orbit services. - Do not publish at all. Containers on the same Docker network reach each other by name; only the reverse proxy needs a published port.
- Use the
DOCKER-USERchain. Docker evaluates this chain before its own rules and never overwrites it, so you can put allow and drop rules for container traffic there. - Filter in the cloud layer. A security group that only allows 22, 80 and 443 stops the stray port regardless of what Docker does on the host.
Recent Docker Engine releases can also program nftables directly instead of using the iptables compatibility layer (an opt-in feature at the time of writing). The principle does not change: published ports bypass the host’s INPUT rules, so decide on purpose what you publish. The Docker Tutorial covers container networking in depth.
Test from the outside
A firewall rule is only proven by a connection attempt from another machine. Testing from the server itself goes through loopback, which the firewall does not filter. From your laptop (or another VM), find the lab’s address and knock:
$ multipass info orbit-lab | grep IPv4
IPv4: 192.168.64.5
$ nc -zv -w 3 192.168.64.5 80
Connection to 192.168.64.5 port 80 [tcp/http] succeeded!
$ nc -zv -w 3 192.168.64.5 5432
nc: connect to 192.168.64.5 port 5432 (tcp) timed out: Operation now in progress
-z only checks whether the port opens without sending data, -v prints the result and -w 3 gives up after three seconds; curl -I http://192.168.64.5 checks the web server itself. A timeout means a firewall dropped the packet; connection refused means the packet arrived but nothing listens (or a rule rejected it). That difference tells you which layer to look at.
A safe-change routine
Firewall changes on a remote server deserve a routine, because a mistake can cut the only connection you have. On cloud VMs, also know where the emergency door is before you need it: the provider’s serial console or session manager gets you in when SSH does not.
- Open a second SSH session and keep it open. Established connections usually survive a rule change thanks to connection tracking, so this session is your way back in.
- Schedule an automatic undo before you touch anything:
echo "ufw disable" | sudo at now + 5 minutes(installatfirst), or with no extra package,sudo systemd-run --on-active=5m /usr/sbin/ufw disable. - Make the change, then open a new SSH connection from your laptop to prove that SSH still works.
- Test the service ports from outside with
ncorcurl. - Cancel the safety net once everything works:
atqthensudo atrm <job>, orsudo systemctl stopon therun-*.timerunit thatsystemd-runprinted.
Practice lab
Orbit is going live on orbit-lab, and you are asked to lock the VM down so that only SSH and the web front end are reachable. If you skipped ahead, install nginx first with sudo apt install -y nginx.
- Check which ports are listening with
sudo ss -tlnp, then set default policies, allow SSH with rate limiting and enable ufw, with a 5-minute safety net in place. - Allow nginx with its application profile and prove from your host machine that port 80 answers.
- Add a rule that allows 5432/tcp only from 10.0.1.11 with a comment, check it in the numbered list, then delete it by number.
- Find your web rule in
sudo nft list rulesetand watch its counter grow while you curl the VM from the host. - Cancel the safety net and confirm with
sudo ufw status verbosethat the firewall is active and survives asudo reboot.
Show a solution
sudo ss -tlnp shows sshd on 22 and nginx on 80. Install the safety net with sudo apt install -y at and echo "ufw disable" | sudo at now + 5 minutes, then run sudo ufw default deny incoming, sudo ufw default allow outgoing, sudo ufw limit OpenSSH and sudo ufw enable, and open a fresh multipass shell orbit-lab to prove SSH still works. sudo ufw allow "Nginx Full" opens 80 and 443; from the host, multipass info orbit-lab gives the IP and nc -zv -w 3 <ip> 80 or curl -I http://<ip> succeeds. sudo ufw allow from 10.0.1.11 to any port 5432 proto tcp comment 'orbit-web-01 to postgres' adds the database rule, sudo ufw status numbered shows its number and sudo ufw delete <n> removes it. sudo nft list ruleset | grep -A4 "chain ufw-user-input" shows the rule for ports 80 and 443, and its packet counter rises each time you rerun the command after a curl. Finally atq lists the job and sudo atrm <job> cancels it; after sudo reboot, sudo ufw status verbose still says Status: active.
Exercise
You run sudo ufw default deny incoming and sudo ufw enable on orbit-web-02 over SSH, and your session freezes. What went wrong, and what would have prevented it?
Show answer
Answer: B. With incoming denied and no SSH rule, new SSH packets are dropped. Allow SSH before enabling the firewall, and keep a safety net such as an at or systemd-run job that disables ufw in a few minutes.
Exercise
ufw on orbit-web-01 allows only 22, 80 and 443, yet a security scan finds port 9000 open. ss -tlnp shows docker-proxy listening on 0.0.0.0:9000. What is the best fix?
Show answer
Answer: C. Docker’s DNAT and FORWARD rules handle published ports before ufw’s INPUT rules see them, so a ufw deny has no effect. Binding the published port to 127.0.0.1 keeps it off the network entirely.
Exercise
On the Rocky Linux box orbit-reports you run sudo firewall-cmd --permanent --add-service=https, but connections to port 443 still time out. What is the most likely reason?
Show answer
Answer: D. --permanent only writes the configuration to disk. A reload applies it to the running firewall. Alternatively, add the rule without --permanent to test it and then save it with --runtime-to-permanent.
Key takeaways
- A host firewall should deny incoming and allow outgoing by default; stateful tracking lets replies back in automatically.
- Defence is layered: cloud ACLs and security groups, the host firewall, and services bound to 127.0.0.1.
- nftables is the kernel framework; ufw and firewalld are front ends, and iptables is a legacy compatibility layer.
- Allow SSH first, keep a second session and schedule an automatic undo; then test from another machine.
- Published Docker ports bypass ufw; publish on loopback or filter in
DOCKER-USERor the cloud layer.
FAQ
Should I use ufw, firewalld or nftables directly?
Use the tool your distribution ships: ufw on Ubuntu and Debian, firewalld on RHEL, Rocky, Alma and Fedora. Both are well supported and write nftables rules for you. Write raw nftables when you need features the front ends hide (sets, maps, complex routing setups) or when you build appliances, and then disable the front end so that only one tool owns the ruleset.
Is iptables dead?
The iptables command is still installed on most distributions, but it is the iptables-nft compatibility layer that translates your commands into nftables rules. Old scripts keep working, which is useful, but new configuration should use ufw, firewalld or nft. Avoid mixing iptables-legacy with nftables on the same machine, because the two sets of rules are evaluated separately and confuse everyone.
Do I need a host firewall if my cloud has security groups?
Yes, keep both. Security groups are managed by a different team or Terraform module and can be loosened by mistake; the host firewall is defence in depth that travels with the server image. It also protects you from neighbours inside the same VPC, which security groups often allow by default. Keep the two rule sets consistent so that debugging does not turn into guesswork.
How do I see which ports are open on my Linux server?
Run sudo ss -tlnp for listening TCP sockets and sudo ss -ulnp for UDP; the address column shows whether a service binds to 0.0.0.0, a private IP or 127.0.0.1. Then check the firewall with sudo ufw status verbose or sudo firewall-cmd --list-all, and confirm from another machine with nc -zv <ip> <port>, because only an outside test shows the combined effect of every layer.
Why do ufw rules not apply to my Docker containers?
Docker publishes ports with NAT rules that redirect the traffic to the container before ufw’s INPUT chain is consulted, and its forwarding rules accept the traffic. Publish ports on 127.0.0.1 when only a local reverse proxy needs them, put custom rules in the DOCKER-USER chain, or filter at the cloud security group.