Direct Answer / TL;DR
Connection failures resolve to three causes: no listener (TCP RST → "Connection refused"), a firewall DROP (no reply → timeout), or a resource limit such as conntrack exhaustion. Run `ss -tulnpe` to confirm the listener and its bind address, then `nft monitor trace` to find the dropping rule; fix the bind config or add the missing accept rule.
ss -tulnpe
nf_conntrack: nf_conntrack table full, dropping packetCore Architecture & Mechanics
A port failure is resolved from one of three diagnostic planes, and a complete investigation walks through each in order. Socket plane: TCP and UDP endpoints are kernel objects with a 5-tuple, a state machine, and (usually) an owning process. ss(8) queries them over the NETLINK_SOCK_DIAG netlink family (the inet_diag kernel subsystem), which is authoritative, namespace-exact, and faster than scraping legacy /proc/net/tcp. Route plane: ip(8) speaks rtnetlink and answers questions a listening socket cannot — is the address assigned, which route and source IP the kernel will actually choose, and does the neighbor (ARP/NDP) entry resolve. Filter plane: netfilter hooks (prerouting, input, forward, output, postrouting) hold nftables rules, compiled to binary bytecode and shipped to the kernel over the nftables netlink subsystem.
An inbound SYN to a service transits: NIC driver → netfilter prerouting (conntrack registers at raw priority −300) → input hook (filter priority 0) → the listening socket’s SYN backlog → accept() queue (capped at net.core.somaxconn, 4096 since kernel 5.4). Each stop has a distinct observable: no listener → kernel emits TCP RST (client: “Connection refused”, curl exit 7); policy DROP → pure silence (client: connect timeout, curl exit 28); policy REJECT → ICMP port-unreachable or RST; SYN backlog overflow → SYNs silently dropped and retransmitted; conntrack exhaustion → new flows dropped and nf_conntrack: table full appears in the kernel log. bind() semantics sit at the entry point: a daemon bound to 127.0.0.1:8080 is unreachable from other hosts even with zero firewall rules; two sockets may share a port only with SO_REUSEPORT on all parties; SO_REUSEADDR merely permits rebinding through TIME_WAIT residue.
The state inventory every diagnosis depends on (via ss -a): ESTAB — healthy traffic; TIME-WAIT — client-side post-close state, fixed at 2×MSL ≈ 60 s, still holding an ephemeral port from net.ipv4.ip_local_port_range (default 32768–60999); CLOSE-WAIT — peer FIN arrived, local application never called close(); the kernel never ages it out — always an fd leak; SYN-SENT/SYN-RECV — outbound/inbound handshake pressure, spikes during floods or path blackholes; BOUND — unconnected UDP socket. Ephemeral-port exhaustion (errno 99, EADDRNOTAVAIL on connect()) and net.netfilter.nf_conntrack_max exhaustion are independent ceilings that both surface as intermittent outbound-connection failures.
Complete Reference Table / Diagnostic Matrix
Run top-down: socket plane, route plane, filter plane. Everything below is read-only except ss -K (irreversible socket destruction) and nft -f (ruleset application), both covered in the hardening section.
| Item / Code / Flag | Behavior | Common Cause / Use Case |
|---|---|---|
ss -tulnpe | All listening TCP/UDP sockets, numeric, with PID/UID | First command in any port dispute; exposes bind-address mistakes instantly |
ss -tlnpe 'sport = :8443' | Filter expression pinned to one port | Verifies exact tuple and owner; two rows = SO_REUSEPORT group |
ss -tan | awk '{print $1}' | sort | uniq -c | Socket-state histogram | TIME_WAIT/CLOSE_WAIT storms, SYN-RECV floods |
ss -lnti | LISTEN queues: Recv-Q (current SYN backlog), Send-Q (max backlog), rtt/cwnd | Backlog overflow → client SYN retransmits; also shows somaxconn cap |
ss -tno | Adds live timers | Watch TIME_WAIT burn off at fixed 2×MSL |
ss -e -p | uid, inode, sk pointer per socket | Map socket to fd via /proc/<pid>/fd |
sudo ss -K dst <ip> | Destroys matching live sockets (root + CONFIG_INET_DIAG_DESTROY) | Emergency shed of abusive/stale peers; irreversible |
ss -N <netns> | Socket view inside a named network namespace | Container diagnostics without exec |
ss -s | Totals per family/state plus socket allocation | One-line capacity check |
ip -br addr | Brief interface/address table with UP/DOWN state | Is the service IP even assigned? |
ip route get <dst> [from <src>] | Shows the kernel’s chosen route and source IP | Explains rp_filter / asymmetric-routing drops |
ip -s link show <iface> | rx/tx errors and dropped counters | NIC-level loss before netfilter ever sees the packet |
ip neigh show | ARP/NDP table | FAILED/INCOMPLETE = L2 problem, not firewall |
ip rule show | Policy-routing rule list | Unexpected table/interface selection (leftover cloud rules) |
nft list ruleset | The active ruleset of the current network namespace, all tables/hooks | Ground truth before any edit |
nft -a list chain inet filter input | Chain dump with rule handles | Prerequisite for surgical nft delete rule ... handle <handle> |
nft -c -f <file> | Parses/validates the file without applying it | Mandatory dry-run before nft -f on remote hosts |
nft monitor trace | Live per-packet rule walk for nftraced packets | Finds the exact chain and verdict that kills a flow |
conntrack -L / -E / -S | List flows, stream events, per-CPU stats | DNAT port mismatch, table pressure, drop counters |
sysctl net.netfilter.nf_conntrack_count net.netfilter.nf_conntrack_max | Current vs maximum tracked flows | Precheck before “table full, dropping packet” events |
Multi-Distro Implementation Differences
ss and ip behave identically everywhere (same iproute2). The fork point is ruleset ownership: who writes the active nftables ruleset, and therefore whose tool must persist your changes.
Ubuntu / Debian
sudo apt install -y iproute2 nftables conntrack
# Ground truth: everything currently in the kernel, all tables/chains
sudo nft list ruleset
# Ubuntu 24.04: ufw programs the kernel via the nftables backend (ufw-* chains);
# never hand-edit those chains — `ufw reload` erases foreign edits.
sudo ufw status verbose
# Debian 12: native nftables service, config in /etc/nftables.conf
sudo nft -c -f /etc/nftables.conf && sudo systemctl restart nftables
# Socket/route facts, identical on every distro
sudo ss -tulnpe
ip -br addr && ip route get 198.51.100.20RHEL / AlmaLinux / Rocky
sudo dnf install -y nftables conntrack-tools policycoreutils-python-utils
sudo nft list ruleset | sed -n '1,60p' # firewalld owns table `inet firewalld`
sudo firewall-cmd --state && sudo firewall-cmd --list-all
# SELinux can block bind() before sockets ever appear on the wire
getenforce
sudo semanage port -l | grep -E 'http_port_t|ssh_port_t'
# Allow a daemon to bind 8443 + open it through firewalld
sudo semanage port -a -t http_port_t -p tcp 8443
sudo firewall-cmd --permanent --add-port=8443/tcp && sudo firewall-cmd --reloadArch Linux
sudo pacman -S --needed iproute2 nftables conntrack
# Validate, then apply atomically; nftables.service is NOT enabled by default
sudo nft -c -f /etc/nftables.conf && sudo nft -f /etc/nftables.conf
sudo systemctl enable --now nftables.service
sudo nft list rulesetAlpine / Containers
doas apk add iproute2 nftables conntrack
ss -tulnpe # busybox-only images lack ss; busybox netstat -tunlp is the fallback
doas nft -c -f /etc/nftables.conf
doas rc-service nftables restart && doas rc-update add nftables defaultContainer note: netfilter tables are per network namespace, but bridge-mode containers keep their netns ruleset effectively empty — all their NAT executes in the host namespace via dockerd’s DOCKER chains. DNAT mysteries therefore always resolve from a host-side nft list ruleset. From the host you can interrogate any container’s socket table without exec: sudo nsenter -t <container_pid> -n ss -tulnpe.
Common Failure Modes & Troubleshooting Recipes
1. “Connection refused” vs “Connection timed out” — the decisive fork
curl -v --connect-timeout 5 telnet://198.51.100.20:8443
# exit 7 + 'Connection refused' → a RST came back: no listener, or a REJECT rule
# exit 28 + connect timeout → silence: policy DROP, no route, or SYN blackhole
sudo ss -tlnpe 'sport = :8443'- No output: the daemon is down or crash-looped —
systemctl status <unit>and fix the daemon, not the network. - Line shows only
127.0.0.1:8443or[::1]:8443: bind-address misconfiguration (missing0.0.0.0/private-IPListen/bind-addressdirective). Correct config, restart, re-verify with ss. 0.0.0.0:8443present but remote clients get refused: the packet transits to a local REJECT verdict — proceed to recipe 2.
2. Finding the exact nftables rule that kills a packet (nftrace)
Insert a temporary trace rule scoped to one flow, watch the live walk, then remove it by handle:
sudo nft list tables
# if the referenced table/chain from your ruleset is missing, create a stub:
sudo nft add table inet filter 2>/dev/null
sudo nft add chain inet filter input '{ type filter hook input priority 0; policy accept; }' 2>/dev/null
sudo nft add rule inet filter input ip saddr 203.0.113.50 tcp dport 8443 counter meta nftrace set 1
sudo nft monitor traceTrace output follows one packet through every chain it touches — trace id ... inet filter input packet: ... followed by verdict drop/verdict accept per chain, including base-chain jumps and policy verdicts. If the traced packet never reaches input, it died in prerouting, in the route plane (recipe 8), or in reverse-path filtering (net.ipv4.conf.all.rp_filter — rp_filter drops are invisible to nftrace because they finish before nftables sees the packet). Always remove the probe:
sudo nft -a list chain inet filter input
sudo nft delete rule inet filter input handle <handle>If firewalld or ufw owns the ruleset, translate the fix into firewall-cmd/ufw syntax — hand edits inside manager-owned tables are overwritten on the next reload.
3. CLOSE_WAIT avalanche — fd leak forensics
sudo ss -tnp state close-wait | head -15
sudo ss -tan state close-wait | awk '{print $NF}' | sort | uniq -c | sort -rn | head
sudo ls /proc/<pid>/fd | wc -lA socket in CLOSE-WAIT is waiting for the local process to call close(); the kernel will never clean it up. The culprit PID’s count grows without bound until ulimit -n (or fs.nr_open) blocks accept(). Restarting the service clears symptoms, not the cause. No sysctl fixes this — it is an application bug in connection teardown after the peer’s FIN.
4. TIME_WAIT pressure and ephemeral-port exhaustion
ss -s
sudo ss -tan state time-wait | wc -l
sysctl net.ipv4.ip_local_port_range
# on client-heavy machines (outbound connect() only):
sudo sysctl -w net.ipv4.tcp_tw_reuse=1
sudo sysctl -w net.ipv4.ip_local_port_range="10240 65535"Mitigations in order of correctness: reuse connections (keep-alive/pooling), then tcp_tw_reuse for outbound, then widen the port range. TIME_WAIT protects against stale duplicate segments — never try to disable it. net.ipv4.tcp_fin_timeout shrinks FIN-WAIT-2, not TIME-WAIT, and does nothing here.
5. nf_conntrack table full — silent flow drops
sudo dmesg -T | grep -i 'conntrack table full' | tail
sysctl net.netfilter.nf_conntrack_count net.netfilter.nf_conntrack_max
sudo conntrack -S # per-CPU insert/drop fail counters
sudo conntrack -E # live event stream; Ctrl-C to stop
echo 'net.netfilter.nf_conntrack_max = 262144' | sudo tee /etc/sysctl.d/90-conntrack.conf
sudo sysctl --system
# hash table only resizable via kernel cmdline (add to GRUB_CMDLINE_LINUX): nf_conntrack.hashsize=65536For high-pps NAT boxes, exempt junk flows at raw priority instead: a raw-priority prerouting chain with a notrack rule for broadcast/known-noise selectors cuts table growth without inflating the hash.
6. DNAT port mismatch — clients dial one port, the daemon listens on another
sudo conntrack -L -p tcp --dport 443 | head
sudo nft list table ip nat 2>/dev/null || sudo nft list table inet nat 2>/dev/nullA dnat to :8080 in prerouting means ss rightly shows the listener on :8080 while clients dial :443; conntrack’s reply tuple displays the translation. A DNAT’d flow exits via postrouting, never re-enters input — missing forward-hook accepts are the usual residual failure.
7. Two listeners on the same port — reuseport or stale process
sudo ss -tlnpe 'sport = :8443'
ls -l /proc/<pid>/exe /proc/<pid>/cwdTwo rows with different PIDs form a SO_REUSEPORT group: inbound connections are hash-balanced across every live member, so one stale binary serves a fraction of requests with old code. Kill the stale PID or fix the supervisor. A plain EADDRINUSE (errno 98) at startup, meanwhile, means an old process still holds the tuple — the same ss line finds it.
8. Route-plane sanity before blaming netfilter
ip route get 198.51.100.20
ip -br addr
ip -s link show eth0
ip neigh show | awk '$NF ~ /FAILED|INCOMPLETE/'If ip neigh shows FAILED/INCOMPLETE, or ip -s link counts rx_dropped, packets never reach netfilter and firewall edits are theater. Policy-routing surprises (ip rule show) reroute traffic silently; ip route get <dst> from <src> always reveals the kernel’s actual decision.
Production Hardening & Safety Checklist
Safety Check: Snapshot → validate → apply → pre-stage rollback, on every change, every host. Never apply nftables rules from a piecemeal shell loop over SSH, never flush ruleset on a remote box, and never rely on the next reboot to restore access. The management-IP accept rule must be the first rule in any policy-DROP chain.
# 1) Snapshot — the rollback anchor
sudo nft list ruleset | sudo tee /root/ruleset-$(date +%F-%H%M%S).nft
# 2) Dry-run: parse/evaluate the candidate file WITHOUT applying it
sudo nft -c -f /root/harden.nft
# 3) Apply atomically from the file (table declarations replace, never merge)
sudo nft -f /root/harden.nft
# 4) Pre-staged automatic rollback, cancelled by hand after external verification
( sleep 300 && sudo nft -f /root/ruleset-<snapshot>.nft ) &Candidate ruleset written as one atomic file:
cat > /root/harden.nft <<'EOF'
table inet harden {
chain input {
type filter hook input priority 0; policy drop;
iifname "lo" accept
ct state invalid counter drop
ct state established,related accept
ip protocol icmp accept
ip saddr <mgmt-ip> tcp dport 22 accept
ip saddr <app-subnet> tcp dport { 80, 443 } accept
limit rate 5/second log prefix "harden-input-drop: " counter drop
}
}
EOF- Ownership: on RHEL add access via
firewall-cmd, on Ubuntu viaufw; use raw nftables only on distros where you own/etc/nftables.conf, or in your own table (e.g.inet harden) no manager rewrites. ss -Kdiscipline: instant, irreversible socket destruction — scope every invocation tightly (dst/sport) and treat it as incident response, not hygiene.- Monitoring: export
ss -sandsysctl net.netfilter.nf_conntrack_count; alert at 80% ofnf_conntrack_maxand ~70% ofip_local_port_rangespan. - Post-change verification: diff
ss -tlnpelistener output, then probe from a second host — local-only tests cannot see DNAT or upstream filtering. - RHEL bonus: a port refusing to bind is often an AVC, not a firewall problem —
sudo ausearch -m avc -ts recent | grep -i tcpbefore touching nft.
Frequently Asked Edge Cases
Why does `ss -tlnp` show a socket but no PID?
Run it with `sudo`: unprivileged users cannot map other users' sockets to PIDs. If root still shows no PID, the socket is kernel-owned (e.g. NFS, WireGuard) or lives in another network namespace — inspect with `ss -N `.
How do I apply a new nftables ruleset remotely without locking myself out?
Write the whole table in one file with your management-IP accept rule first, validate with `nft -c -f`, snapshot with `nft list ruleset | sudo tee`, apply with `nft -f`, and pre-stage `( sleep 300 && nft -f snapshot.nft ) &` as an automatic rollback you cancel after verifying SSH.
Why do two processes appear on the same port in `ss -tlnpe`?
Both set SO_REUSEPORT, so the kernel hash-balances new inbound connections across every live member — one stale PID can silently serve a fraction of traffic. Identify each with `ls -l /proc//exe` and kill the outdated one.
