A server's network setup is a short stack an administrator owns: interfaces and addresses, routes, the DNS resolver, the services listening on ports, and a host firewall that decides which packets reach them. Linux's firewall is netfilter, driven by nftables directly or through ufw (Ubuntu) or firewalld (Red Hat family). This lesson configures one web server from the interface up to a tested default-deny policy, including the rule change that locks you out and the container that walks straight past the firewall.
Difficulty: Intermediate · Know this first: Lesson F19, Lesson 02
This bar adds up admin minutes from first login to a tested firewall. It is a worked example, not a measurement. The safe-apply and outside-test hops are where a firewall either works or only appears to.
Choose what listens, on which address, and what the firewall says. Remember that Docker-published ports have their own rules.
Exposed: Docker's rules accept the traffic before ufw sees it
Three questions. No score is saved anywhere — this is just you against the material.
Host networking grows in four levels: reading the setup, writing a basic firewall, nftables and containers, and network policy for a fleet.
At the basic level you can describe how this host talks to the network.
ip -br addr, ip route, resolvectl status.ss -tulpn: what listens on which address and port.ping, curl -v, nc -zv host port to test reachability.Where it breaks: testing a rule from the server itself, where loopback and local addresses bypass the rules you meant to test.
Try it: Basic
ss shows a service on 127.0.0.1:6379. Can another machine connect to it?
Now do it: Run sudo ss -tulpn and mark each listener as local-only or exposed.
At the intermediate level you set up a safe host firewall.
ufw default deny incoming, ufw allow from CIDR to any port 22 proto tcp, ufw allow 443/tcp, ufw enable.--add-service, --permanent then --reload; --timeout for a test rule.Try it: Intermediate
On firewalld, you add a rule with --permanent and it does not take effect. Why?
Now do it: Add a rule with --timeout=60 and watch it disappear.
At the advanced level you write the ruleset yourself and account for containers.
/etc/nftables.conf with an inet table, input chain policy drop, established and loopback accepted, then named sets of allowed sources.DOCKER-USER; Kubernetes nodes have kube-proxy and CNI rules of their own.Try it: Advanced
Why might a host firewall rule not apply to traffic for a Docker container?
Now do it: Run sudo nft list ruleset on a Docker host and find the DOCKER-USER chain.
At the master level the host firewall is one layer of several.
Trade-off: several layers mean one mistake does not expose a service, and mean a change must be made in several places. Generate them from one source of truth.
Try it: Master
What catches a port opened by mistake on one of 300 hosts?
Now do it: Scan one of your public hosts from outside with nmap -Pn and compare with what you expect.
A default-deny setup with ufw applied safely over SSH, the same policy in nftables, and the Docker fix.
sudo ufw default deny incoming sudo ufw default allow outgoing sudo ufw allow from 203.0.113.0/24 to any port 22 proto tcp # SSH first sudo ufw allow 443/tcp # safety net: disable automatically in 5 minutes unless cancelled sudo sh -c 'sleep 300 && ufw disable' & echo "rollback pid $!" sudo ufw --force enable # from a NEW terminal: ssh in again. If it works, cancel the rollback: sudo kill %1 2>/dev/null || sudo pkill -f "sleep 300" sudo ufw status verbose
# /etc/nftables.conf
table inet filter {
set admin { type ipv4_addr; flags interval; elements = { 203.0.113.0/24 } }
chain input {
type filter hook input priority 0; policy drop;
ct state established,related accept
iif lo accept
ip saddr @admin tcp dport 22 accept
tcp dport 443 accept
limit rate 5/minute log prefix "drop "
}
}
# check, then load: sudo nft -c -f /etc/nftables.conf && sudo nft -f /etc/nftables.conf
docker run -d --name pg -e POSTGRES_PASSWORD=change-me -p 127.0.0.1:5432:5432 postgres:16 sudo ss -tlnp | grep 5432 # 127.0.0.1:5432, not 0.0.0.0:5432
This is a composite of a failure pattern that keeps repeating; the details are illustrative. A database behind a "closed" firewall was found by a scanner.
Containers publish on 127.0.0.1 by policy, DOCKER-USER drops inbound traffic except from the load balancer, cloud security groups mirror the host rules, and a weekly external scan alerts on any unexpected open port.
Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.
Before you start: A Linux VM or a spare machine where you have sudo (a cloud VM, Multipass, or VirtualBox). Some commands change the system; do not run them on a shared server. ufw: sudo apt install -y ufw.
Type each one, read what it prints, and compare it with the note above it.
Interfaces, routes, and the resolver.
ip -br addr; ip route; ip route get 1.1.1.1; resolvectl status 2>/dev/null | head -8
What is listening, and on which address.
sudo ss -tulpn
A default-deny policy that allows SSH first, with an automatic rollback in 3 minutes.
sudo ufw default deny incoming; sudo ufw default allow outgoing sudo ufw allow 22/tcp; sudo ufw allow 443/tcp sudo sh -c "sleep 180 && ufw disable" & echo "rollback armed, pid $!" sudo ufw --force enable; sudo ufw status verbose
After a new SSH login works, cancel the rollback (or let it run to undo the lab).
sudo pkill -f "sleep 180" && echo "rollback cancelled"; sudo ufw status numbered
rule_eval.pyThis program evaluates packets against a first-match firewall ruleset with a default policy, the way netfilter chains do, including a container-published port that bypasses the host rules. Save it as rule_eval.py, then run it.
# rule_eval.py
import ipaddress
rules = [ # (action, source network, port), first match wins
("accept", "203.0.113.0/24", 22),
("accept", "0.0.0.0/0", 443),
]
DEFAULT = "drop"
docker_published = {5432} # Docker's own DNAT rules run before these
def decide(src, port):
if port in docker_published:
return "accept (DOCKER chain, before the host rules)"
for action, net, p in rules:
if p == port and ipaddress.ip_address(src) in ipaddress.ip_network(net):
return f"{action} (rule: {net} port {p})"
return f"{DEFAULT} (default policy)"
for src, port in [("203.0.113.7", 22), ("198.51.100.9", 22), ("198.51.100.9", 443),
("198.51.100.9", 8080), ("198.51.100.9", 5432)]:
print(f"{src:<15} -> port {port:<5} {decide(src, port)}")
Run it, and you should see this output:
$ python3 rule_eval.py 203.0.113.7 -> port 22 accept (rule: 203.0.113.0/24 port 22) 198.51.100.9 -> port 22 drop (default policy) 198.51.100.9 -> port 443 accept (rule: 0.0.0.0/0 port 443) 198.51.100.9 -> port 8080 drop (default policy) 198.51.100.9 -> port 5432 accept (DOCKER chain, before the host rules)
The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/host-firewall-and-network-configuration && cd ~/labs/host-firewall-and-network-configuration) and save this as lab.sh.
#!/usr/bin/env bash
# The Linux steps of "Host Networking and the Firewall", as one script (save it as lab.sh).
#
# ./lab.sh run every step, in order
# ./lab.sh 2 4 run only steps 2 and 4
# ./lab.sh --list list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.
STEPS=(
'Interfaces, routes, and the resolver.'
'What is listening, and on which address.'
'A default-deny policy that allows SSH first, with an automatic rollback in 3 minutes.'
'After a new SSH login works, cancel the rollback (or let it run to undo the lab).'
)
step_1() {
ip -br addr; ip route; ip route get 1.1.1.1; resolvectl status 2>/dev/null | head -8
}
step_2() {
sudo ss -tulpn
}
step_3() {
sudo ufw default deny incoming; sudo ufw default allow outgoing
sudo ufw allow 22/tcp; sudo ufw allow 443/tcp
sudo sh -c "sleep 180 && ufw disable" & echo "rollback armed, pid $!"
sudo ufw --force enable; sudo ufw status verbose
}
step_4() {
sudo pkill -f "sleep 180" && echo "rollback cancelled"; sudo ufw status numbered
}
# print a step that has to be run by hand, instead of running it
by_hand() {
echo " (run this one yourself: $1)"
sed 's/^/ /'
}
RESULTS=()
run_step() {
local n=$1 start=$SECONDS code
printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
"step_$n"
code=$?
RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}
summary() {
echo
echo "== summary"
local r
for r in "${RESULTS[@]}"; do echo " $r"; done
}
case "${1:-}" in
-h|--help) sed -n '2,6p' "$0"; exit 0 ;;
--list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac
[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
echo "there is no step '$n'; try --list" >&2
exit 2
fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done
Then make it executable and run it:
chmod +x lab.sh ./lab.sh --list # the steps ./lab.sh # every step, then a summary of exit codes and times ./lab.sh 2 3 # only steps 2 and 3
New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.
head, echo, Pipes, Redirection, If...Else.Write the network and firewall standard for three server roles: public web, internal API, and database.
What does each role listen on, and on which address? Who may reach each port? How are rules applied safely and kept identical across hosts? How will you know if a port is open that should not be?
Say 30 web hosts behind a load balancer, 20 API hosts, and 4 database hosts, with SSH only from a bastion or VPN.
Web: 443 from the load balancer subnet, 22 from the bastion. API: its port from the web subnet only. Database: 5432 from the API subnet only, bound to the private interface. Default deny everywhere, nftables rules generated from an inventory by configuration management, cloud security groups mirroring them, containers published on localhost, and a weekly external scan compared with the inventory.
Host firewalls plus security groups are redundant by design and need one generator to stay in sync. Source restrictions make admin access safer and add a dependency on the bastion or VPN, which needs its own break-glass path.