Interview Prep/Networking/Sockets, ports, TIME_WAIT and conntrack

A service on port 40001 fails to start after boot about once a week with `Address already in use`, though nothing listens there when you check.

IntermediateTroubleshootingSockets, ports, TIME_WAIT and conntrack
Answer

Likely causes → Port 40001 lies inside the ephemeral range (ip_local_port_range, default 32768–60999). Occasionally an outbound connection opened before the service starts grabs it as its source port.

Diagnose →

sysctl net.ipv4.ip_local_port_range
ss -tanp | grep ':40001 '

Fix → Reserve the port so the kernel never uses it as an ephemeral source port:

echo 'net.ipv4.ip_local_reserved_ports = 40001' | sudo tee /etc/sysctl.d/91-reserved.conf
sudo sysctl --system

Or move the service out of the ephemeral range.

Prevent → Keep listening ports below the ephemeral range; note that Kubernetes NodePorts (30000–32767) overlap with some ranges, so reserve them on nodes.

All Networking questions Roadmap: Networking for DevOps

More on Sockets, ports, TIME_WAIT and conntrack