Skip to content

Network Troubleshooting Playbook: Connection Refused vs Timeout, DNS Failures, MTU/Fragmentation, conntrack & Ephemeral Port Exhaustion, Packet Capture ​

"Systems have inertia: we’ve found that a working computer system tends to remain in motion until acted upon by an external force, such as a configuration change or a shift in the type of load served." — Google, Site Reliability Engineering, chapter 12 "Effective Troubleshooting"

Summary: Every network failure a developer meets shows up as one of about fifteen error strings, and each string tells you which layer broke and what to run next; this chapter maps every string to its causes and gives you a method, the commands and the code to prove which one it is. Focus: Refused vs timed out vs unreachable vs reset, DNS and TLS failures, resource errors (EMFILE, EADDRINUSE, EADDRNOTAVAIL), slow-first-request and intermittent failures, MTU black holes, conntrack and ephemeral-port exhaustion, packet capture and Wireshark, latency tools, Docker/Kubernetes/cloud specifics, and the observability that makes the next incident short. Learning goal: Given an error message and five minutes, name the layer, list the two or three likely causes, run the one command that separates them, and write it down as a timeline someone else can follow.

This is the capstone of the networking group: it is organised by symptom → hypotheses → commands → fix and links back to the chapter that owns each mechanism instead of re-teaching it. Read it after (or alongside) network models (the layers we walk), IP addressing and routing (routes, ARP), NAT (translation tables and idle timeouts), DNS resolution (resolvers, ndots, caching), ports, sockets and connections (socket states, ss, TIME_WAIT), firewalls (DROP vs REJECT, security groups), Docker networking, Kubernetes networking, VPNs and tunnels (where MTU shrinks) and TLS in practice (handshake errors). Design topics stay in their own chapters: TCP and UDP, HTTP evolution and keep-alive, load balancing and health checks, timeouts, retries and jitter, observability, connection pooling and service discovery.

Page map ​

If you are looking forGo to
The symptom table to memoriseEverything in one minute
Why a method beats guessingWhy a playbook
Sources: SRE book, USE method, RFCsWhere it comes from
Reproduce, localise, bisect, compare, change one thingThe method
connection refusedConnection refused
connection timed out, i/o timeoutConnection timed out
no route to host, network is unreachableUnreachable
connection reset by peer, broken pipe, EOFReset, broken pipe, EOF
no such host, NXDOMAIN, SERVFAIL, DNS timeoutsDNS failures
TLS handshake timeout / certificate errorsTLS failures
too many open files, address already in use, cannot assign requested addressResource errors
The first request is slowSlow first request
It fails 1 % of the timeIntermittent failures
Small requests work, big ones hangMTU and fragmentation
conntrack full, ephemeral ports, NAT gateway portsconntrack and ephemeral ports
tcpdump, Wireshark, RST, retransmissionsPacket capture
mtr, traceroute, iperf3, curl -w, ss -tiLatency and loss tools
Every error string per client (Go, PHP, curl, psql, redis-cli)Error strings
Link → IP → route → ARP → firewall → NAT → DNS → TCP → TLS → HTTPLayer checklist
Docker, Kubernetes, cloudContainers and Kubernetes, Cloud
Go netdiag, PMTU probe, port-exhaustion reproducerSolving the classic problems
Laravel net:diag, HTTP client errors, health endpointsLaravel
Which tool answers which questionChoosing
Monolith to distributedIn architecture
Metrics and probes to keepObservability to keep
Postmortem-ready timelineWriting the timeline
Six broken Compose scenariosLab

Everything in one minute ​

The symptom table. The error string is the most precise evidence you have. Read it before you touch anything.

You seeErrnoWhat happened on the wireUsual causesFirst command
connection refusedECONNREFUSED (111)SYN answered by RST, within one RTTNothing listening on that ip:port; wrong port; app bound to 127.0.0.1; container crashed; REJECT --reject-with tcp-resetss -ltnp on the server
connection timed out / i/o timeoutETIMEDOUT (110) or your own deadlineSYN sent, nothing came backSecurity group/NACL/iptables DROP; wrong route; NAT missing; host down; conntrack fulltcpdump 'tcp[tcpflags] & tcp-syn != 0' on both ends
no route to hostEHOSTUNREACH (113)No ARP reply on the local subnet, or ICMP host-unreachable / host-prohibitedDead IP on the same subnet; firewall REJECT --reject-with icmp-host-prohibitedip neigh; ip route get IP
network is unreachableENETUNREACH (101)Nothing sent: no route in the local tableNo default route; Docker internal: true network; IPv6 address with no IPv6 routeip route; ip -6 route
connection reset by peerECONNRESET (104)RST on an established connectionIdle timeout at LB/NAT then reuse; server crash/abort; proxy limit; RST injectiontcpdump 'tcp[tcpflags] & tcp-rst != 0'
broken pipeEPIPE (32)You wrote after the peer closed or resetSame as reset, noticed on writeas above
EOF / unexpected EOF(none: read returned 0)FIN arrived before a complete answerServer closed idle keep-alive connection; crash mid-response; body shorter than Content-Lengthcurl -v; server logs
no such host / Could not resolve host(resolver) NXDOMAIN, SERVFAIL, timeoutDNS answer negative or missingTypo; wrong search domain; split DNS; resolver down; UDP 53 filtereddig name; cat /etc/resolv.conf
TLS handshake timeout / x509 / wrong version number(TLS)TCP fine, handshake failedPlain HTTP on the TLS port; SNI; chain; clock; MTU on the certificate flightopenssl s_client -connect host:443 -servername host
too many open filesEMFILE (24)No syscall to the network at allLow ulimit -n; leaked socketsls /proc/PID/fd | wc -l
address already in useEADDRINUSE (98)bind() on a taken ip:portSecond instance; old process still alive; port taken by another appss -ltnp 'sport = :8080'
cannot assign requested addressEADDRNOTAVAIL (99)No free ephemeral port for that destinationEphemeral port exhaustion (TIME_WAIT churn, no keep-alive)ss -tan state time-wait | wc -l
Large requests hang, small fine(none, a hang)Big packets dropped, ICMP "fragmentation needed" lostMTU black hole on VPN/overlay/PPPoEping -M do -s 1472 host; tracepath host
Fails 1 in NvariesOne path, one IP or one table is badconntrack full; dead IP in DNS round-robin; LB draining; half-open after NAT timeoutsplit by destination IP and by host

The ladder. Every connection climbs the same rungs. The first rung that fails names the layer.

RungQuestionToolOwner chapter
1. ResolveDoes the name give the IP I expect, from this host/container?dig, getent hosts, nslookupDNS
2. RouteWhich interface and gateway would this packet use?ip route get, ip neighIP addressing
3. ConnectDoes the SYN get a SYN-ACK?nc -vz, curl -v, tcpdumpPorts and sockets
4. TLSDoes the handshake complete with the right certificate?openssl s_clientTLS
5. ApplicationDoes a full, correct response arrive in time?curl -w, app logsthis chapter

The three rules.

RuleWhy
Test from where the failing code runs (same container, pod, subnet)Your laptop has different DNS, routes, firewall and NAT
Fast failure and slow failure are different layersRefused (milliseconds) means a host answered; timeout (seconds) means something dropped
Change one thing at a time and write it downTwo changes at once hide which one fixed it, and the timeline is the postmortem
Walk down the ladder; the first "no" names the layer1. Did the name resolve?dig name; getent hosts name2. Did TCP connect?nc -vz ip port; curl -v3. Did TLS complete?openssl s_client -connect4. Full response arrived?curl -w timings; tcpdump5. Fails only sometimes?rate, counters, per-IP splityesyesyesyesDNS: NXDOMAIN / SERVFAIL / i/o timeout on :53typo, search/ndots, split DNS, resolver down, UDP 53 filteredFast "connection refused" (RST)nothing listening, wrong port/IP, bound to 127.0.0.1, crashed, REJECT"no route to host" / "network is unreachable"ARP fails on subnet, ICMP prohibited, no default route, internal networkSlow "connection timed out" (SYN unanswered)SG/NACL/iptables DROP, wrong route, NAT, host down; conntrack fullTLS: handshake timeout / unknown CA / wrong host / not TLSSNI, chain, clock, port speaks plain HTTP: see the TLS chapterReset by peer / EOF / broken pipe / large payload hangsidle timeout at LB or NAT on a pooled connection, server crash, proxy limit;small requests fine but big ones hang: MTU black hole (ICMP filtered)Intermittent: resources and stateconntrack table full, ephemeral ports (EADDRNOTAVAIL), NAT GW ports,DNS round-robin to a dead IP, LB draining, too many open files,slow first request: ndots search walk, TLS, cold poolnonononoyes

Why a playbook ​

Network failures feel random because the network is invisible: a function call returns an error string, and the cause could be the code, the host, a container bridge, a firewall three hops away or a load balancer in another account. Guessing ("restart it", "raise the timeout") sometimes works, which is exactly why it survives. A method is slower for the first minute and much faster for the next sixty.

GuessingMethod
"It's the network""The SYN leaves the pod and never reaches the node; a NetworkPolicy drops it"
Raise the timeoutFind out what the timeout is waiting for
Restart and hopeReproduce, capture, then fix and verify with the same reproduction
Test from your laptopTest from the failing pod, then bisect towards the server
One big changeOne change, one observation, one timeline line
Fixed but nobody knows whyA postmortem with evidence (capture, counters, error strings)

The everyday picture. A plumber with no water at the kitchen tap. She does not replace the tap first. She opens the tap next to the meter (is water reaching the house?), then the one halfway (is it reaching the floor?), then the kitchen. Each test halves the pipe that could be broken. "Refused" is the tap answering "no" immediately; "timeout" is no sound at all; "reset" is water that starts and then stops. We will reuse this picture: bisect the pipe, compare with a working tap, change one valve at a time.

Three misunderstandings, up front.

MisunderstandingReality
"Timeout and refused are the same: it's down"Refused proves a host answered with RST; timeout proves packets vanished. They point to different layers and different teams
"ping works, so the network is fine"ICMP echo uses no port, may take another path or priority, and is small. TCP to the real port with the real packet size is what matters
"It works from my machine"Your machine has its own DNS, routes, VPN and NAT. Reproduce from inside the failing container or pod

Where it comes from ​

SourceWhat it gives this chapter
Google SRE book, ch. 12 "Effective Troubleshooting" (2016)The hypothetico-deductive loop: triage, examine, diagnose, test, treat; "what touched it last"; bisection; "correlation is not causation"
Brendan Gregg, the USE method and Linux performance tools"For every resource, check utilization, saturation, and errors": applied here to fds, ports, conntrack, NAT ports, backlog
RFC 1191 (1990), Path MTU DiscoveryDF bit and ICMP "fragmentation needed": the mechanism whose failure is the black hole
RFC 2923 (2000), TCP problems with PMTUDNames "the long-standing black hole problem"
RFC 4821 (2007), Packetization Layer PMTUDProbing with real packets instead of trusting ICMP; Linux tcp_mtu_probing
RFC 8899 (2020), DPLPMTUDThe same idea for datagram transports (QUIC, UDP)
RFC 9293 (2022), TCPSYN, RST, retransmission and the connection states every capture shows
Linux man pages: connect(2), tcp(7), ss(8), ip(8), tcpdump(1), pcap-filter(7), ping(8), tracepath(8), mtr(8), traceroute(1), dig(1), conntrack(8), nft(8), iptables(8), nstat(8), strace(1), nsenter(1)Exact flags and the errno meanings
Kernel docs ip-sysctl and nf_conntrack-sysctlDefaults: port range 32768-60999, tcp_mtu_probing, nf_conntrack_max
Wireshark User's GuideDisplay filters, TCP analysis flags, Follow TCP Stream, TLS decryption with a key log
Cloudflare engineering blogconntrack overfill, ephemeral port exhaustion, PMTUD with ECMP, IP fragmentation
Kubernetes, Docker, AWS and Azure docskubectl debug, DNS debugging, NetworkPolicy, VPC Flow Logs, NAT gateway limits, SNAT ports

The SRE book's own words on the strategy we use most: "an alternative, bisection, splits the system in half and examines the communication paths between components on one side and the other." And on recent changes: "Recent changes to a system can be a productive place to start identifying what’s going wrong." Gregg's USE method is one line: "For every resource, check utilization, saturation, and errors."

The concept catalogue ​

The method: reproduce, localise, bisect, compare, change one thing Must-know ​

In plain words: Make the failure happen on demand, find the first layer where it breaks by walking from the client to the server, compare with something that works, and change exactly one thing at a time.

Common misunderstanding: "Troubleshooting is knowing the answer." It is a loop. The SRE book frames it as forming hypotheses from observations and then testing them: "Using the experimental method, we can try to rule in or rule out our hypotheses." Experience makes the hypothesis list shorter, not the loop unnecessary.

Definition: a five-step loop.

StepWhat you doNetwork example
1. ReproduceOne command that fails the same way the app fails, from the same placekubectl exec pod -- curl -sv --max-time 5 http://orders:8080/health
2. Localise by layerWalk the ladder: DNS, route, connect, TLS, HTTPDNS ok, connect times out: stop above TCP
3. Bisect the pathTest from points between client and serverFrom the pod: timeout. From the node: ok. So the pod-to-node hop (policy, CNI)
4. Compare working vs brokenSame request from a working pod/host/region; diff configs, routes, rulesPod in namespace A works, B fails: B has a default-deny NetworkPolicy
5. Change one thingOne change, then re-run the reproduction from step 1Add an egress rule; re-run; it passes; write the timeline line

Timeline: bisecting a timeout.

1  10:02  app log: dial tcp 10.0.3.7:5432: i/o timeout            (symptom)
2  10:04  pod:  nc -vz -w3 10.0.3.7 5432   -> timed out            (reproduced)
3  10:05  pod:  getent hosts db.internal   -> 10.0.3.7             (DNS ok: rung 1 passes)
4  10:06  node: nc -vz -w3 10.0.3.7 5432   -> succeeded            (bisect: node ok, pod fails)
5  10:08  node: tcpdump -ni any 'host 10.0.3.7 and port 5432'       -> SYN from pod IP leaves node, no SYN-ACK
6  10:10  db:   tcpdump shows no SYN arriving                       (dropped between)
7  10:12  cloud: DB security group allows node SG, not pod CIDR    (hypothesis)
8  10:15  add pod CIDR to SG ingress 5432; re-run step 2 -> succeeded (one change, verified)

Real scenarios: a staging deploy where only one replica fails (compare that pod's node with the others); a monthly batch job that fails at 02:00 (reproduce at 02:00 load or with the same concurrency); a partner API that fails only from production (bisect: prod NAT IP is not on their allow-list).

What each tool tells you on each side.

Point on the pathCommandProves
Inside the client containercurl -sv, getent hosts, ip route getWhat the app sees
Client host/nodetcpdump -ni any host IPWhether packets leave
Every middle box you ownflow logs, conntrack -L, LB access logsWhether packets pass
Server hosttcpdump, ss -ltn, nstatWhether packets arrive and who answers
Server processlogs, strace -f -e trace=%networkWhether the app saw it

Fix / how to use it: the Go netdiag and the Laravel net:diag command automate steps 1 and 2; the timeline section is step 5 written down.

Connection refused Must-know ​

In plain words: You knocked and someone shouted "nobody lives here" immediately. A host is reachable; the port is not served.

Common misunderstanding: "Refused means a firewall blocked me." Most firewalls DROP silently (you get a timeout). Refused means the target kernel (or a REJECT --reject-with tcp-reset rule) answered your SYN with RST. connect(2) says it exactly: ECONNREFUSED "A connect() on a stream socket found no one listening on the remote address."

Definition: the SYN reached a TCP stack that had no listening socket for that destination ip:port, so it replied RST+ACK. Arrives in about one round trip.

   client 10.231.0.2                          server 10.231.0.10
1  SYN  sport 47494 -> dport 81      ----->
2                                    <-----   RST,ACK   (no listener on :81)
3  connect() returns ECONNREFUSED after ~0 ms

Real scenarios (and the hypothesis each one gives):

CauseHow you see itFix
Nothing listens: process crashed, not started, still bootingss -ltnp shows no :PORTStart/fix it; add a readiness probe so traffic waits
Wrong port or IP in configss shows :5433, config says 5432Fix config; one source of truth
App bound to 127.0.0.1 inside a containerss -ltn shows 127.0.0.1:8000, not 0.0.0.0:8000Bind 0.0.0.0 (or ::) in containers
Container restarted / Service has no endpointsdocker ps restarts; kubectl get endpointslices emptyFix crash loop; selector labels
REJECT --reject-with tcp-resetServer has listener but rule rejects; iptables -L -v counter risesAllow the source
Docker published port with no backendThrough docker-proxy it often becomes reset/empty reply insteadSee Lab scenario 1

What each client prints. Real output, Linux containers, Go 1.27, curl 8, PostgreSQL 16 psql, Redis 8 redis-cli, PHP 8.5:

Go         dial tcp 10.231.0.10:81: connect: connection refused
curl       curl: (7) Failed to connect to ntp-web:81 after 0 ms: Could not connect to server
psql       psql: error: connection to server at "ntp-web" (10.231.0.10), port 5432 failed: Connection refused
                   Is the server running on that host and accepting TCP/IP connections?
redis-cli  Could not connect to Redis at ntp-web:6379: Connection refused
PHP        stream_socket_client(): errno=111 errstr="Connection refused"

Laravel's ConnectionException carries the same libcurl text (cURL error 7: Failed to connect to ...), because the HTTP client is built on Guzzle and libcurl.

Fix / how to use it: on the server, ss -ltnp (who listens where), then curl -v http://127.0.0.1:PORT from inside the server's own namespace. If that works but the remote test is refused, the bind address or a REJECT rule is the answer. In Go, errors.Is(err, syscall.ECONNREFUSED); in PHP, errno === 111. Refused is cheap and fast, so it is safe to retry with backoff during a deploy (the listener is coming), but a refusal that lasts more than a deploy is a config bug, not a transient.

Connection timed out Must-know ​

In plain words: You knocked and heard nothing. Something between you and the host threw your packet away, or the host is not there.

Common misunderstanding: "Timeout means the server is slow." For a connect timeout the server never saw you; slow servers accept the connection and then are slow to answer (that is a read/response timeout). Separate the two in your client config and your logs.

Definition: the SYN (or its SYN-ACK) was dropped; the kernel retransmits the SYN until the tcp_syn_retries budget is spent and then fails with ETIMEDOUT, unless your own deadline fires first. The budget changed with kernels: tcp(7) still says default 6 "corresponds to retrying for up to approximately 127 seconds" (pure exponential backoff), while the current kernel ip-sysctl docs say 6 "corresponds to 67seconds (with tcp_syn_linear_timeouts = 4)", because current kernels retransmit the first SYNs every second ("1, 1, 1, 1, 1, 2, 4, ...") before backing off. Go reports its own deadline as i/o timeout; the kernel's give-up as connection timed out.

Real capture (kernel 7.0, tcp_syn_retries=2 in the client's namespace, iptables -j DROP on the server, no Go deadline):

18:23:49.096819 IP 10.240.1.6.49622 > 10.240.1.20.80: Flags [S], seq 2957620591, win 64240, options [mss 1460,...], length 0
18:23:50.110827 IP 10.240.1.6.49622 > 10.240.1.20.80: Flags [S], seq 2957620591, ...     (same seq: a retransmission)
18:23:51.133836 IP 10.240.1.6.49622 > 10.240.1.20.80: Flags [S], seq 2957620591, ...
18:23:52.157367 IP 10.240.1.6.49622 > 10.240.1.20.80: Flags [S], seq 2957620591, ...
18:23:53.181953 IP 10.240.1.6.49622 > 10.240.1.20.80: Flags [S], seq 2957620591, ...
18:23:54.206174 IP 10.240.1.6.49622 > 10.240.1.20.80: Flags [S], seq 2957620591, ...
FAIL  rung 2 (tcp): dial tcp 10.240.1.20:80: connect: connection timed out      (after 7.16 s)

Six SYNs with the same sequence number, one second apart, no answer at all: that is what a DROP looks like from the client. The firewall's counter (iptables -L INPUT -v -n) showed 6 360 DROP ... tcp dpt:80 for exactly those six packets.

Real scenarios:

CauseWhere to lookTelltale
Security group / NACL / iptables / nftables DROPCloud console, iptables -L -v -n, nft list ruleset, VPC Flow Logs REJECTCounter on a DROP rule rises with each SYN
Wrong route (asymmetric, missing return route)ip route get, route tablesSYN arrives at the server, SYN-ACK leaves by another path and dies
Missing NAT / no internet gateway routeSubnet route table, NAT gatewayPrivate subnet: no 0.0.0.0/0 route to a NAT
Host down or IP not assignedARP: ip neigh shows FAILED/INCOMPLETE on a same-subnet hostSame subnet usually turns into no route to host after ~3 s
Kubernetes NetworkPolicy default denykubectl get networkpolicy -AOnly pods in one namespace fail
conntrack table full on a nodedmesg "nf_conntrack: table full, dropping packet"Random new connections time out under load
Server listen backlog overflownstat -az TcpExtListenOverflows rises on the serverUnder bursts only

What each client prints (real output):

Go (own deadline)    dial tcp 10.231.0.99:80: i/o timeout
Go (kernel gave up)  dial tcp 10.240.1.20:80: connect: connection timed out
curl                 curl: (28) Connection timed out after 2005 milliseconds
psql                 psql: error: connection to server at "10.231.0.99", port 5432 failed: timeout expired
PHP (musl)           errno=110 errstr="Operation timed out"

In Laravel the same two cases arrive as ConnectionException with cURL error 28 in the message.

Fix / how to use it: always set a connect timeout of a few seconds (Go net.Dialer{Timeout}, Laravel connectTimeout(), libpq connect_timeout, curl --connect-timeout), separate from the read/total timeout. Then capture on both ends: tcpdump -ni any 'tcp[tcpflags] & (tcp-syn|tcp-rst) != 0 and host IP'. SYN leaves the client but never arrives: a middle box. SYN arrives, SYN-ACK leaves, never reaches the client: return path. Nothing arrives and nothing leaves: local policy. See firewalls for DROP vs REJECT.

No route to host and network is unreachable Important ​

In plain words: "Network is unreachable" means your own machine has no road to that address at all. "No route to host" means the road exists but the last step (finding the host on the local network) failed, or a router/firewall explicitly said the host is unreachable or prohibited.

Common misunderstanding: "No route to host means a routing table problem." On Linux it most often means ARP got no answer for a same-subnet IP (a dead container, a stale IP in config), or a firewall used REJECT --reject-with icmp-host-prohibited (a common choice in host firewalls; see Lab step 5).

Definition:

ErrorErrnoGenerated byWire
network is unreachableENETUNREACHLocal kernel, before sendingNothing leaves; immediate
no route to hostEHOSTUNREACHLocal kernel after ~3 s of failed ARP, or an ICMP type 3 code 1/10/13 from a router/firewallARP who-has repeated; or ICMP back
   client 10.231.0.2 (same /24 as 10.231.0.99, which does not exist)
1  ARP who-has 10.231.0.99 tell 10.231.0.2
2  ARP who-has 10.231.0.99 tell 10.231.0.2
3  ARP who-has 10.231.0.99 tell 10.231.0.2
4  connect() -> EHOSTUNREACH after 3.1 s  ("dial tcp 10.231.0.99:80: connect: no route to host")

Real scenarios: a Docker container whose old IP is hard-coded in another service's config (the new container got a new IP); a host whose firewall rejects with host-prohibited; a container on a Compose network with internal: true that tries to reach the internet (no default route: unreachable); an IPv6 AAAA answer on a host with no IPv6 route (Happy Eyeballs clients fall back, simple clients fail).

ClientENETUNREACHEHOSTUNREACH
Goconnect: network is unreachableconnect: no route to host
curl(7) Failed to connect ... Could not connect to serversame exit 7
redis-cli (musl)—Could not connect to Redis at 10.231.0.99:6379: Host is unreachable
PHP (musl)errno 101errno 113 Host is unreachable

Fix / how to use it: ip route get DEST prints the route and source the kernel would use (or RTNETLINK answers: Network is unreachable); ip neigh shows FAILED/INCOMPLETE for an ARP failure. Replace IPs in config with names; give containers a default route or an egress path; for IPv6-only failures prefer clients with Happy Eyeballs (Go's dialer does it, RFC 8305).

Connection reset by peer, broken pipe and EOF Must-know ​

In plain words: The call started fine and then the other side (or something in the middle) hung up. A reset is a slammed phone; EOF is a polite goodbye that came too early; broken pipe is you talking into a phone that is already dead.

Common misunderstanding: "Reset by peer means the server crashed." The "peer" is whoever sent the RST, and it is very often a middle box: a load balancer or NAT gateway that forgot your idle connection. The AWS NAT gateway documentation is explicit: after 350 seconds idle, "a NAT gateway returns an RST packet to any resources behind the NAT gateway that attempt to continue the connection (it does not send a FIN packet)."

Definition:

ErrorMeaningErrno
connection reset by peerAn RST arrived on an established connection; pending data is discardedECONNRESET
broken pipeYou wrote to a socket whose peer already reset it (Linux sends SIGPIPE; Go ignores it and returns EPIPE)EPIPE
EOFRead returned 0: the peer sent FINnone
unexpected EOFFIN before the promised length (Content-Length, protocol frame)none (library)

Real Go output, a server that aborts (SetLinger(0)) versus one that closes normally:

read after RST:          read tcp 127.0.0.1:40062->127.0.0.1:9101: read: connection reset by peer
write after RST:         write tcp 127.0.0.1:40062->127.0.0.1:9101: write: broken pipe
read after FIN:          EOF
first write after FIN:   <nil>          (accepted locally; the peer answers it with RST)
second write after FIN:  write tcp 127.0.0.1:46392->127.0.0.1:9102: write: broken pipe
net/http, no response:   Post "http://127.0.0.1:9202/": EOF
net/http, short body:    unexpected EOF

The "first write succeeds, second write fails" line is why broken pipes appear one request late: the first write only proves the bytes reached your kernel.

The keep-alive race (timeline). The single most common source of sporadic resets and EOFs:

   client pool                        load balancer (idle timeout 60 s)        server
1  request A on conn #7     ----->    ----->                                     200
2  conn #7 returned to pool, idle
3  ... 60 s pass ...                  LB drops state for conn #7 (or sends FIN)
4  request B on conn #7     ----->    no state: RST                <-----
5  client: "connection reset by peer" / "EOF" on a request that never reached the server

Real scenarios:

CauseTelltaleFix
Pool keeps idle connections longer than LB/NAT idle timeoutErrors after quiet periods; first request after idleClient idle timeout below the shortest middlebox timeout; TCP keepalive; retry idempotent requests once
Server keep-alive timeout shorter than the client'sServer closes (FIN) while client sendsServer keep-alive timeout > LB/client idle timeout (nginx keepalive_timeout, Node keepAliveTimeout)
Server process crashed / OOM-killed mid-requestKernel resets the orphaned sockets; logs show restartFix crash; graceful shutdown that drains
Proxy limits (body size, header size, proxy_read_timeout)Reset or 502 at the proxy onlyRaise or fix the limit; read proxy logs
Listen queue full with tcp_abort_on_overflow=1Resets under burstsBigger backlog, more workers
RST injection by middleboxes/DPIRST with odd TTL/IP ID in capturesDifferent path, TLS everywhere
Database killed the session (idle_session_timeout, wait_timeout in MySQL)"server closed the connection unexpectedly" on the next queryPool max_idle_time below server timeout; ping/validate before use

Fix / how to use it: capture RSTs with tcpdump -ni any 'tcp[tcpflags] & tcp-rst != 0' and look at who sends them (source IP and TTL). In Go, set http.Transport.IdleConnTimeout below the smallest idle timeout on the path (see the timing snippet); net/http already retries a request on a reused connection that failed before any response if the request is idempotent. Laravel: Http::retry() for ConnectionException on idempotent calls only.

DNS failures Must-know ​

In plain words: The name did not turn into an IP. Either the answer was "no such name" (NXDOMAIN), "I failed" (SERVFAIL), or no answer at all (timeout).

Common misunderstanding: "no such host means the record does not exist." It means the resolver your process used, after applying /etc/hosts, search domains and ndots, got a negative answer. The same name may resolve fine from another host, another container or another resolver. Always test from the failing place with the failing resolver. Mechanism and caching live in DNS resolution; this block is the symptom view.

Definition and the strings (all real, from the containers described under Error strings; a dash means not reproduced):

Answerdig statusGocurlpsql (musl)redis-cli (musl)PHP (musl)
Name does not existNXDOMAINlookup x on 127.0.0.11:53: no such host(6) Could not resolve host: xcould not translate host name "x" to address: Try againName has no usable addressgetaddrinfo for x failed: Name does not resolve
Resolver failed (internal Docker network, external name)SERVFAIL—(6) Could not resolve host: example.com (DNS server returned general failure)———
No answer in time (cold upstream, first run)no replylookup ntp-wbe: i/o timeout————
   app (ndots:5 in a Kubernetes pod) asks for "api.partner.com"
1  api.partner.com.default.svc.cluster.local   A?  -> NXDOMAIN
2  api.partner.com.svc.cluster.local           A?  -> NXDOMAIN
3  api.partner.com.cluster.local               A?  -> NXDOMAIN
4  api.partner.com.                            A?  -> 203.0.113.10    (4 queries x A and AAAA)

Real scenarios: a typo in DB_HOST (instant NXDOMAIN from Docker's embedded resolver 127.0.0.11); a cold upstream making the first lookup time out (we saw lookup ntp-wbe: i/o timeout on the first run and an instant no such host on the second); CoreDNS overloaded by ndots:5 search expansion; split DNS that resolves a name to a private IP on the VPN and a public one off it; a resolver reachable over UDP but not TCP, so large answers (DNSSEC, many records) fail.

Fix / how to use it: dig +search name, dig @RESOLVER name, getent hosts name (uses the system resolver path, including /etc/hosts and nsswitch.conf), cat /etc/resolv.conf. In Kubernetes, the official DNS debugging page starts with kubectl exec -i -t dnsutils -- nslookup kubernetes.default. Use fully qualified names with a trailing dot for external hosts in pods, or lower ndots, and cache in the app.

TLS failures Important ​

In plain words: TCP connected, but the two sides could not agree to speak encrypted, or the client did not trust what the server showed.

Common misunderstanding: "TLS handshake timeout is a certificate problem." A timeout in the handshake is usually a network problem: the server's certificate flight is the first large packet of the connection, so an MTU black hole shows up exactly there. Certificate problems fail fast with a specific message.

Definition and the strings (real output where marked):

SituationGocurl
Plain HTTP on the TLS port (real)tls: first record does not look like a TLS handshake(35) TLS connect error: error:0A00010B:SSL routines::wrong version number
Handshake stalls (MTU, overloaded server)net/http: TLS handshake timeout(28)
Unknown CA / self-signedx509: certificate signed by unknown authority(60) "Peer certificate cannot be authenticated with known CA certificates"
Name mismatch / wrong SNIx509: certificate is valid for a, not b(60)
1  TCP SYN / SYN-ACK / ACK            fine (small packets)
2  ClientHello (~300-600 bytes)       fine
3  ServerHello + Certificate (3-5 KB, full-size segments)  -> dropped at a 1400-byte hop
4  client waits ... "TLS handshake timeout"

Fix / how to use it: openssl s_client -connect host:443 -servername host -showcerts, then the TLS chapter for chains, SNI and clocks. If s_client hangs after CONNECTED(00000003), test the MTU with ping -M do -s 1372 host.

Resource errors: too many open files, address already in use, cannot assign requested address Must-know ​

In plain words: These are not the network saying no. Your own machine ran out of something: file descriptors, a free listening port, or free source ports.

Common misunderstanding: "cannot assign requested address is a DNS or IP problem." In a client, EADDRNOTAVAIL from connect() means, in the connect(2) page's words, "all port numbers in the ephemeral port range are currently in use". It is port exhaustion towards one destination.

Definition:

ErrorErrnoSyscallMeans
too many open filesEMFILE / ENFILEsocket, accept, openProcess (ulimit -n) or system (fs.file-max) fd limit
address already in useEADDRINUSEbind/listenSomeone else holds ip:port (or a TIME_WAIT without SO_REUSEADDR, rare for servers in Go/Linux)
cannot assign requested addressEADDRNOTAVAILconnect (or bind to a non-local IP)No ephemeral port left for this destination 4-tuple, or binding to an address the host does not have

Real Go output in a container with ulimit -n 30:

listen tcp 127.0.0.1:9101: bind: address already in use
dial tcp 127.0.0.1:9102: socket: too many open files          (connection #21)
dial tcp 10.231.0.20:8080: connect: cannot assign requested address   (port range 40000-40009, see Lab)

Real scenarios: a PHP-FPM or Go service that creates a new HTTP client per request (every request a new connection, every close a TIME_WAIT: ports run out at a few hundred requests per second to one upstream); a load test from one machine; a service that leaks response bodies (Go: forgetting resp.Body.Close() leaks fds and keeps connections out of the pool); a second php artisan serve on port 8000; binding a container to the host's public IP that only exists on the host.

ErrorCheckFix
EMFILEls /proc/PID/fd | wc -l vs cat /proc/PID/limitsFix leaks; raise LimitNOFILE (systemd), ulimits (Docker/Compose)
EADDRINUSEss -ltnp 'sport = :PORT', lsof -i :PORTStop the other process; choose a port; SO_REUSEPORT only on purpose
EADDRNOTAVAILss -tan state time-wait | wc -l, ss -tan 'dst IP:PORT' | wc -lKeep-alive and pooling; widen net.ipv4.ip_local_port_range; more source IPs; spread destinations

Fix / how to use it: the port-exhaustion reproducer shows the exact error; the fix is almost always connection reuse, covered under conntrack and ephemeral ports.

Slow first request Important ​

In plain words: The first call after a deploy or a quiet period takes seconds; the next ones take milliseconds. Something is being set up once and then reused.

Common misunderstanding: "The server is slow to warm up." Measure before blaming: split the time into DNS, connect, TLS, server time. Very often it is DNS search expansion or a TLS handshake that only the first request pays.

Definition: curl -w exposes the phases (from the curl manual: time_namelookup, time_connect "until the TCP connect to the remote host (or proxy) was completed", time_appconnect "until the SSL/SSH/etc connect/handshake to the remote host was completed", time_starttransfer "until the first byte was received").

curl -s -o /dev/null -w 'dns=%{time_namelookup} connect=%{time_connect} tls=%{time_appconnect} ttfb=%{time_starttransfer} total=%{time_total}\n' URL

1  dns=5.012   connect=5.013   tls=5.040   ttfb=5.080   -> 5 s in DNS: a resolver timeout then retry (first nameserver dead)
2  dns=0.001   connect=0.090   tls=0.300   ttfb=0.310   -> connect 90 ms RTT, TLS 2 RTT: far region, new connection
3  dns=0.001   connect=0.001   tls=0.002   ttfb=1.900   -> network fine; server cold (JIT, cache, pool)

Real scenarios and causes:

CausePhaseFix
ndots:5 search walk in Kubernetes (4 extra NXDOMAIN round trips, A and AAAA)dnsFQDN with trailing dot, dnsConfig.options ndots: 2, NodeLocal DNSCache
First nameserver in resolv.conf dead: 5 s timeout default then nextdnsFix resolver list; options timeout:1 attempts:2
AAAA answer but no IPv6 route; client tries IPv6 firstconnectHappy Eyeballs; fix IPv6 or do not publish AAAA
New TLS connection per request (no keep-alive, no session resumption)tlsReuse connections; TLS 1.3 resumption
Cold connection pool (database, Redis, HTTP)connect + tlsWarm the pool at start; min idle connections
Lazy app boot (Laravel config/route cache missing, opcache cold, Octane worker start)ttfbphp artisan optimize; warm-up request in readiness
Conntrack/ARP entry missing on first packet in some CNIsconnectUsually small; measure

Fix / how to use it: Go timing snippet prints the same phases and reused=true/false for each request.

Intermittent failures Must-know ​

In plain words: It works most of the time. That means most paths are fine and one path, one IP or one table is not. The job is to find the variable that separates good from bad attempts.

Common misunderstanding: "Intermittent means random." Nothing in a network is random; it is a hidden variable you have not split by yet: destination IP, source pod, node, time of day, payload size, connection age.

Definition: a failure rate between 0 and 100 % on otherwise identical requests. Split the failures by every dimension you log until one value has 100 % failures.

Hidden variableCauseHow to splitFix
Destination IPDNS round-robin includes a dead or draining IPLog resolved IP per request; dig +short name shows severalHealth-checked LB instead of plain RR; remove the record; client tries next IP
Connection ageHalf-open connection after NAT/LB idle timeout (reset/EOF on first use after idle)Error vs idle time before requestIdle timeout below middlebox timeout; keepalive
Payload sizeMTU black hole: only large bodies hangError vs request/response sizeMSS clamp, fix ICMP, lower MTU (MTU)
Load / timeconntrack full, ephemeral ports, NAT gateway ports, listen backlogError vs connection rateconntrack and ports
Node / podOne node with broken iptables/CNI state or a full conntrackError vs node nameCordon and compare; fix node
DeploysLB connection draining too short; pods killed with open connectionsError vs deploy timestampspreStop sleep; deregistration delay > longest request; graceful shutdown
UDP vs TCP DNSTruncated answers retried over TCP that is blockedError vs answer sizeAllow TCP 53
   requests to api.internal (A records 10.0.1.10, 10.0.1.11, 10.0.1.12; .12 terminated)
1  req 1 -> 10.0.1.10  200
2  req 2 -> 10.0.1.11  200
3  req 3 -> 10.0.1.12  connect timeout   <- 1 in 3 fails; all failures share one IP

Fix / how to use it: log the resolved peer IP, local port, connection reuse flag and phase timings with every outbound error (the netdiag output has all of them). Then group by each field.

MTU and fragmentation Must-know ​

In plain words: Every link has a maximum packet size. When a path contains a smaller link than the endpoints know about, big packets must be shrunk. The safety net is an ICMP message that says "too big, use this size". If someone blocks that message, big packets vanish silently while small ones pass: connections open, small requests work, big ones hang.

Common misunderstanding: "If ping works, MTU is fine." Default ping is 64 bytes. You must ping with the DF bit and a full-size payload (ping -M do -s 1472) to test the path MTU. Also: "lowering the MTU on my container fixes it." Lowering the MTU on both endpoints only lowers the TCP MSS they announce; the black hole is caused by a smaller link in the middle that the endpoints do not know about.

Definition. RFC 1191: when a router cannot forward a datagram "because it exceeds the MTU of the next-hop network and its Don't Fragment bit is set, the router is required to return an ICMP Destination Unreachable message to the source of the datagram, with the Code indicating 'fragmentation needed and DF set'"; the sender then "reduces its assumed PMTU for the path." (That is ICMP type 3 code 4 for IPv4; ICMPv6 "Packet Too Big" for IPv6, where routers never fragment.) RFC 2923 calls the failure mode "the long-standing black hole problem". RFC 4821 answers it with a method "that relies on TCP or some other Packetization Layer to probe an Internet path with progressively larger packets"; RFC 8899 does the same for datagram protocols (QUIC, UDP) and defines a black hole as when "a sender is unaware that packets are not being delivered to the destination endpoint."

Path MTU Discovery and the black holeSenderlink MTU 1500MSS 1460, DF=1Firewall"block all ICMP"Routernext hop MTU 1400(VPN, overlay, PPPoE)Receiverlink MTU 15001. 1500-byte packet, DF=12. too big for 1400 and DF=1: drop3. ICMP type 3 code 4, next-hop MTU 14004. ICMP dropped here: sender never learns5. retransmit 1500 bytes ... again ... againsmall packets (SYN, GET, small JSON) pass: handshake OK, request OKSymptom: connect and TLS fine, small responses fine, large response or upload hangs, then times out or resets.Fix: allow ICMP frag-needed / ICMPv6 Packet Too Big, clamp MSS on the tunnel, lower MTU, or tcp_mtu_probing=1 (RFC 4821).
TermValue / meaning
MTU (Ethernet)1500 bytes of IP packet
MSS (TCP over IPv4)MTU − 20 (IP) − 20 (TCP) = 1460; with timestamps 1448 bytes of payload per segment
ping -sICMP payload; 1472 + 8 (ICMP) + 20 (IP) = 1500
DF bit"Don't Fragment"; Linux sets it on TCP by default (PMTUD on)
WireGuardBelow 1500: 60 (IPv4) or 80 (IPv6) bytes of overhead (outer IP 20/40 + UDP 8 + WireGuard 32); see VPNs and tunnels
VXLAN (Flannel, Calico VXLAN, Docker overlay)50 bytes by header arithmetic (outer Ethernet 14 + IP 20 + UDP 8 + VXLAN 8): 1450 inside a 1500 underlay
GRE, PPPoE, IPsec24 (IP 20 + GRE 4), 8 (PPPoE header), IPsec varies with mode and cipher: measure it
AWS9001 inside a VPC (jumbo), 1500 over an internet gateway / VPN / inter-region peering

Timeline (real, from Lab step 6):

1  client -> GET /small.txt    small: 200 6 bytes 0.000290s
2  client -> GET /big.bin      (response 200,000 bytes)
3  server sends 1448-byte segments, DF=1  -> router: next hop MTU 1400, drop, ICMP frag-needed suppressed
4  server retransmits seq 0:1448 at +0.2 s, +0.4 s, +0.8 s, +1.6 s (RTO backoff); nothing arrives
5  curl: (28) Operation timed out after 5012 milliseconds with 0 out of 200000 bytes received

Real scenarios: a site-to-site VPN where SSH logins work but scp hangs; Kubernetes on VXLAN where pod MTU was left at 1500; a Docker host on a cloud VM whose own MTU is below 1500 while docker0 defaults to 1500; TLS handshakes that time out only through the corporate VPN; Cloudflare's write-up of PMTUD in practice, where ECMP load balancing sent the ICMP to the wrong server (their post shows the filter tcpdump -s0 -p -ni eth0 'icmp and icmp[0] == 3 and icmp[1] == 4').

FixWhereHowCost
Allow ICMP type 3 code 4 / ICMPv6 type 2Every firewall/SG on the pathNever "block all ICMP"None; the proper fix
MSS clampingThe tunnel/routeriptables -t mangle -A FORWARD -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu; nftables tcp option maxseg size set rt mtuTCP only; UDP/QUIC still affected
Lower MTU on the overlayCNI / Docker daemon / WireGuardDocker com.docker.network.driver.mtu, "mtu" in daemon.json; Calico/Flannel MTU settingsSlightly more packets
Packetization-layer PMTUDSender hostsnet.ipv4.tcp_mtu_probing=1 ("enabled when an ICMP black hole detected")Detection takes a few RTOs

Commands: ping -M do -s 1472 host (the ping man page: do means "prohibit fragmentation, even local one"); bisect the size down until it passes; tracepath host ("traces path to a network host discovering MTU along this path"); ip route get IP shows a cached mtu after an ICMP was received; ss -ti prints pmtu: per connection. Fragmentation itself (when DF is off) is a different problem: fragments are dropped by many firewalls and need reassembly state; Cloudflare's post "Broken packets: IP fragmentation is flawed" explains why modern protocols avoid it.

conntrack and ephemeral ports Must-know ​

In plain words: Each outbound connection uses up an entry in several tables: a file descriptor in your process, a source port on your host, a row in the Linux connection-tracking table on every NATing node, and a port on the NAT gateway. Any one of them can fill up, and each fills up with a different error.

Common misunderstanding: "We have 65,535 ports, so 65,535 connections." Linux uses 32768-60999 for outgoing connections by default (28,232 ports), the limit applies per destination ip:port (the same source port can talk to many destinations), TIME_WAIT keeps a closed port busy for 60 seconds, and behind SNAT the limit is per public IP for everyone sharing it.

Definition. Kernel docs: ip_local_port_range "Defines the local port range that is used by TCP and UDP to choose the local port... The default values are 32768 and 60999 respectively." nf_conntrack_max: "Maximum number of allowed connection tracking entries"; nf_conntrack_count: "Number of currently allocated flow entries"; nf_conntrack_tcp_timeout_established default 432000 seconds (5 days). Cloudflare's "Conntrack tales" shows what happens at the limit: packets “were hard dropped. Conntrack on overfill does exactly that. It even complains in the "dmesg"”; the message in the kernel source (net/netfilter/nf_conntrack_core.c) is nf_conntrack: table full, dropping packet. Their ephemeral-ports post: "When the range is exhausted (against a single destination), we'll see EADDRNOTAVAIL error."

Every new connection spends a slot in five tablesApp process1 socket = 1 fdlimit: ulimit -nno keep-alive = churnClient kernelephemeral port per(dst ip, dst port)32768-60999 = 28,232TIME_WAIT holds 60 sNode conntrack1 entry per flownf_conntrack_maxDocker/K8s SNATport collisionsNAT gatewayports per public IPper destinationAWS: 55,000 / IPidle 350 s then RSTServerlisten backlogsomaxconnmax_connectionsworker poolWhen it is full, the error you see:EMFILE"too many openfiles"EADDRNOTAVAIL"cannot assignrequested address"SYN silently droppedclient: timeoutdmesg: table fulltimeouts to onedestination only;ErrorPortAllocationslow connect,"too many clients",listen overflowsCounter to watch:ls /proc/PID/fd | wc -lss -tan state time-waitnf_conntrack_count, conntrack -SCloudWatch port alloc errorsnstat ListenOverflowsOne fix helps all five: reuse connections (keep-alive, pools). Then widen the specific limit: ulimit, port range,nf_conntrack_max, more NAT IPs, backlog. Spreading across destinations helps ports; nothing helps a leak.
   one pod, 1,000 req/s to partner:443 with a new connection per request (no keep-alive)
1  t=0 s    each request: connect (new port) ... close (this side: TIME_WAIT 60 s)
2  t=28 s   28,000 ports in TIME_WAIT towards 203.0.113.10:443 on this host
3  t=29 s   connect() -> EADDRNOTAVAIL "cannot assign requested address"
   behind the node's SNAT: the same story with the node IP as the shared source
   behind a NAT gateway: ~55,000 concurrent per public IP per destination (AWS), then ErrorPortAllocation

Real scenarios:

TableLimitError/telltaleCounterFix
fdsulimit -n (often 1024)too many open files/proc/PID/fdraise limit; fix leaks
Ephemeral ports28,232 per destination ip:port per source IPEADDRNOTAVAILss -tan state time-waitkeep-alive/pool; wider range; more source IPs
conntracknf_conntrack_maxSYNs silently dropped: timeouts; dmesg table full, dropping packetnf_conntrack_count, conntrack -S (drop, early_drop, insert_failed)raise max and buckets; shorter timeouts; NOTRACK for known heavy flows
Docker/K8s node SNATsource ports of the node IP shared by all podstimeouts; insert_failed racesconntrack -Smasquerade with --random-fully (iptables-extensions: "Fully randomize source port mapping"); fewer, longer connections
AWS NAT gateway"Each IPv4 address can support up to 55,000 simultaneous connections to each unique destination" (destination IP + port + protocol)timeouts to one destinationCloudWatch ErrorPortAllocation ("could not allocate a source port")more IPs on the NAT GW; connection reuse; VPC endpoints
AWS NAT gateway idle350 s idleRST on next useIdleTimeoutCountkeepalive < 350 s
Azure LB outbound"64,000 ports are eligible for SNAT" per frontend IP, allocated per backendSNAT port exhaustionportal metricsAzure NAT Gateway; more frontend IPs

Fix / how to use it: connection reuse fixes every row at once (HTTP keep-alive, connection pools, gRPC/HTTP2 multiplexing). Then widen the specific limit. Tuning tcp_tw_reuse is mostly unnecessary on modern kernels (default 2: "enable for loopback traffic only"), and the kernel docs warn it "should not be changed without advice/request of technical experts". tcp_tw_recycle no longer appears in the kernel's ip-sysctl documentation and must not appear in a modern tuning guide. Cloudflare's post shows the IP_BIND_ADDRESS_NO_PORT socket option for clients that bind a source IP before connecting, so port selection still happens per destination.

Packet capture Must-know ​

In plain words: When logs disagree, the packets decide. tcpdump records what actually crossed an interface; Wireshark helps you read it.

Common misunderstanding: "Capture on the client and you have seen everything." You have seen what the client's interface saw. Capture on both ends (and on the node/host for containers) to prove where a packet disappears. Also: with TLS you see the handshake and sizes, not the HTTP, unless you decrypt with a key log from your own client.

Definition: the filters you need. pcap-filter(7) lists the flag constants "tcp-fin, tcp-syn, tcp-rst, tcp-push, tcp-ack, tcp-urg, tcp-ece, tcp-cwr".

Goaltcpdump (capture) filterWireshark display filter
One conversationhost 10.0.3.7 and port 5432ip.addr==10.0.3.7 && tcp.port==5432
Connection attempts'tcp[tcpflags] & tcp-syn != 0'tcp.flags.syn==1 && tcp.flags.ack==0
Resets'tcp[tcpflags] & tcp-rst != 0'tcp.flags.reset==1
Retransmissions(not expressible)tcp.analysis.retransmission
Duplicate ACKs / zero window—tcp.analysis.duplicate_ack, tcp.analysis.zero_window
All TCP problems—tcp.analysis.flags
ICMP frag-needed'icmp[0] == 3 and icmp[1] == 4'icmp.type==3 && icmp.code==4
DNSport 53dns, dns.flags.rcode != 0
TLS ClientHello'tcp[((tcp[12]&0xf0)>>2)] = 0x16'tls.handshake.type==1

Practice.

bash
# write a file, full packets, no name resolution, all interfaces
tcpdump -ni any -s 0 -w /tmp/cap.pcap 'host 10.0.3.7 and port 5432'
# rotating capture for an intermittent problem: 10 files of 100 MB, oldest overwritten
tcpdump -ni eth0 -s 0 -C 100 -W 10 -w /var/tmp/ring.pcap 'port 443'
# read it back with relative timestamps and hex
tcpdump -nr /tmp/cap.pcap -ttt -X
# inside a container: share its network namespace
docker run --rm -it --net container:app nicolaka/netshoot tcpdump -ni eth0 port 8080
# inside a pod: ephemeral debug container
kubectl debug -it pod/app --image=nicolaka/netshoot --target=app -- tcpdump -ni eth0 port 8080
# from the node into a container's namespace
nsenter -t "$(docker inspect -f '{{.State.Pid}}' app)" -n tcpdump -ni eth0 port 8080

Reading a capture. Wireshark's TCP analysis flags (from its user guide): "TCP Retransmission" when "the next expected sequence number is greater than the current sequence number"; "TCP Dup ACK" when "the segment size is zero" and the ACK repeats; "TCP ZeroWindow" when "the receive window size is zero" (the receiver's application is not reading: an application problem, not a network one). Follow TCP Stream (Analyze → Follow → TCP Stream) shows one conversation's payload. For TLS from your own client: set SSLKEYLOGFILE=/tmp/keys.log before running curl, Firefox or Chrome; the Wireshark wiki explains that their TLS library "writes the required per-session secrets to a file", which you load in Preferences → Protocols → TLS → "(Pre)-Master-Secret log filename". Go has the same: tls.Config{KeyLogWriter: f} (only in debug builds).

A real RST, annotated (from the Lab, tcpdump -X, client 10.240.1.5 to fw port 81 with REJECT --reject-with tcp-reset): see the hex dump in Lab step 7.

Latency and loss tools Important ​

In plain words: Some failures are not errors but slowness or loss. These tools tell you where along the path time goes and packets disappear.

Common misunderstanding: "mtr shows 30 % loss at hop 5, so hop 5 is the problem." Routers rate-limit the ICMP they generate for TTL-expired probes. Loss at a middle hop that does not continue to the final hop is just a busy router control plane. Only loss that persists to the destination is real.

Definition:

ToolWhat it sendsAnswersWatch out
pingICMP echoRTT, loss to one hostICMP may be blocked or deprioritised; not your port
tracerouteUDP to high ports by default; -I ICMP; -T TCP SYN (to port 80 or -p)Hops by TTL expiryFirewalls treat each protocol differently: use -T -p 443 to see the path your HTTPS takes
tracepathUDP, no rootHops and PMTU
mtrContinuous traceroute (--tcp, --udp, -P port)Per-hop loss and latency over time"mtr combines the functionality of the traceroute and ping programs"; read loss at the last hop
iperf3TCP/UDP bulkThroughput, retransmits, jitterNeeds a server end (iperf3 -s)
curl -wYour real requestDNS/connect/TLS/TTFB splitThe best first tool for HTTP
ss -ti—Per-connection rtt:, retrans:, cwnd:, pmtu:Live sockets only
nstat / netstat -s—Kernel counters: retransmits, resets, listen overflowsUse deltas: nstat prints changes since the last run
   illustrative (not from this lab): mtr --tcp -P 443 -r -c 50 api.example.com
1  gw            0.0% loss   0.4 ms
2  isp-edge      0.0%        3.1 ms
3  core-a       40.0%        9.0 ms   <- ICMP rate limit; next hops are fine
4  peer          0.0%       11.2 ms
5  api           0.0%       11.5 ms   <- destination: 0 % loss, so the path is fine

Real scenarios: an API that is slow only from one region (mtr from that region; RTT jump at the peering hop); upload throughput far below the link (iperf3 shows retransmits; ss -ti shows retrans:); a service whose p99 rises while CPU is idle (nstat TcpRetransSegs rising).

Fix / how to use it: ss -tino dst IP on a live connection prints lines like this real one from the Lab: rtt:10.303/18.066 ato:40 mss:1348 pmtu:1400 ... retrans:0/1 ... rwnd_limited:1982ms(98.0%); the ss man page defines rtt:<rtt>/<rttvar> as "the average round trip time" and its mean deviation. nstat -az | grep -E 'Retrans|ListenOverflows|ListenDrops|TCPTimeouts|AttemptFails|EstabResets' gives the counters to alert on.

Mechanics ​

Error strings per client ​

Every cell below was produced in Linux containers on this machine (Docker 29 on a 7.0 kernel, Go 1.27 static binary on Alpine 3.24, curl 8 in curlimages/curl and Alpine, psql from postgres:16-alpine, redis-cli from redis:8-alpine, PHP 8.5 from php:8.5-cli-alpine). A dash means we did not reproduce that client for that case; do not guess its text, reproduce it. Laravel wraps libcurl, so its ConnectionException message carries the same cURL error N text as the curl CLI.

SymptomGocurlpsqlredis-cliPHP stream_socket_client
Refuseddial tcp 10.231.0.10:81: connect: connection refused(7) Failed to connect to ntp-web:81 after 0 ms: Could not connect to serverconnection to server at "ntp-web" (10.231.0.10), port 5432 failed: Connection refusedCould not connect to Redis at ntp-web:6379: Connection refusederrno=111 "Connection refused"
Timeout (client deadline)dial tcp 10.231.0.99:80: i/o timeout(28) Connection timed out after 2005 milliseconds... port 5432 failed: timeout expired—errno=110 "Operation timed out"
Timeout (kernel gave up)dial tcp 10.240.1.20:80: connect: connection timed out————
No route (ARP failed)connect: no route to host (after 3.1 s)(7) Failed to connect to 10.231.0.99:80 after 3093 ms: Could not connect to server—Could not connect to Redis at 10.231.0.99:6379: Host is unreachableerrno=113 "Host is unreachable"
ICMP admin prohibiteddial tcp 10.240.1.20:82: connect: no route to host(7) Failed to connect to 10.240.1.20:82 after 0 ms———
No default routeconnect: network is unreachable(7) Failed to connect to 1.1.1.1:80 after 0 ms———
NXDOMAINlookup ntp-wbe on 127.0.0.11:53: no such host(6) Could not resolve host: ntp-wbecould not translate host name "postgress" to address: Try againCould not connect to Redis at postgress:6379: Name has no usable addressgetaddrinfo for ntp-wbe failed: Name does not resolve
SERVFAIL (internal network, external name)—(6) Could not resolve host: example.com (DNS server returned general failure)———
Not TLS on TLS porttls: first record does not look like a TLS handshake(35) TLS connect error: error:0A00010B:SSL routines::wrong version number———
Resetread: connection reset by peer————
Broken pipewrite: broken pipe————
Empty reply / closed without responsePost "http://127.0.0.1:9202/": EOF(52) Empty reply from server———
Body shorter than Content-Lengthunexpected EOF————
fdsdial tcp 127.0.0.1:9102: socket: too many open files————
Portsconnect: cannot assign requested address————
Client timeout waiting for headerscontext deadline exceeded (Client.Timeout exceeded while awaiting headers)————
Body stalls after headers (MTU black hole)—(28) Operation timed out after 5012 milliseconds with 0 out of 200000 bytes received———

For the rest, the curl manual documents the exit codes: 6 "Could not resolve host", 7 "Failed to connect to host", 28 "Operation timeout", 52 "The server did not reply anything", 55 "Failed sending network data", 56 "Failure in receiving network data" (the last two are what a reset or broken pipe produce mid-transfer). Note also that the curl on macOS prints Couldn't connect to server where curl 8 on Linux prints Could not connect to server: one more reason to grep for the exit code, not the sentence.

Why the same errno prints differently ​

The kernel returns a number; the text comes from whoever formats it. Go has its own table (syscall.Errno.Error()), glibc and musl each have one, and drivers add their own prefix. Grep logs for the errno name or the stable fragment, not the whole sentence.

ErrnoGoglibc (strerror, Ubuntu)musl (Alpine)PHP/Laravel (via libcurl)
ECONNREFUSED 111connection refusedConnection refusedConnection refusedcURL error 7
ETIMEDOUT 110connection timed outConnection timed outOperation timed outcURL error 28
EHOSTUNREACH 113no route to hostNo route to hostHost is unreachablecURL error 7
ENETUNREACH 101network is unreachableNetwork is unreachableNetwork unreachablecURL error 7
ECONNRESET 104connection reset by peerConnection reset by peerConnection reset by peercURL error 56
EADDRNOTAVAIL 99cannot assign requested addressCannot assign requested addressAddress not availablecURL error 7
EAI_NONAME (resolver: name not found)no such host (Go's own resolver)Name or service not knownName does not resolve (or Try again, EAI_AGAIN, seen from psql and nc for the same typo)cURL error 6

Every cell was printed on this machine: Go by the netdiag runs, glibc by perl -MPOSIX in an Ubuntu-based image (mongo:8.0), musl by posix_strerror() in php:8.5-cli-alpine. The errno numbers are Linux's; macOS uses other numbers (ECONNREFUSED is 61 there), which is one more reason to reproduce in the same OS as production. In Go, never match strings: use errors.Is(err, syscall.ECONNREFUSED), errors.As(err, &dnsErr) (*net.DNSError has IsNotFound, IsTimeout, IsTemporary) and net.Error.Timeout().

The layer-by-layer checklist ​

Run it top to bottom from the failing place. Stop at the first "no".

#LayerQuestionCommandGood answer
1LinkIs the interface up, with the expected MTU?ip -br link, ip link show eth0UP, mtu 1500 (or the overlay's value)
2IPDo I have the address I think?ip -br addrExpected subnet
3RouteWhich route and source would be used?ip route get 10.0.3.7via GW dev eth0 src ...
4ARP/NDPIs the next hop resolvable?ip neighREACHABLE/STALE, not FAILED
5Firewall (local)Is anything dropping on this host?iptables -L -v -n, nft list rulesetNo growing DROP counter for this flow
6NATIs the flow translated as expected?conntrack -L -d IP, iptables -t nat -SReply tuple shows the backend
7DNSDoes the name resolve here, to the right IP?getent hosts name, dig nameExpected IP, fast
8TransportDoes the SYN get an answer?nc -vz -w3 IP PORTsucceeded
9TLSHandshake and certificate ok?openssl s_client -connect IP:443 -servername nameVerify return code: 0 (ok)
10HTTPFull response, in time?curl -sv -w '%{http_code} %{time_total}\n' URLExpected status and time

Kernel knobs and defaults ​

KnobDefaultAffectsSource
net.ipv4.tcp_syn_retries6 (67 s with linear timeouts; ~127 s on older kernels)How long a dropped SYN takes to failkernel ip-sysctl, tcp(7)
net.ipv4.tcp_syn_linear_timeouts4SYN retransmissions at a fixed 1 s before exponential backoffkernel ip-sysctl
net.ipv4.ip_local_port_range32768 60999Ephemeral portskernel ip-sysctl
net.ipv4.ip_local_reserved_portsemptyPorts excluded from automatic assignmentkernel ip-sysctl
net.ipv4.tcp_tw_reuse2 (loopback only)Reusing TIME_WAIT ports for new outbound connectionskernel ip-sysctl
net.ipv4.tcp_mtu_probing0Packetization-layer PMTUD (1 = after a black hole is detected)kernel ip-sysctl
net.ipv4.ip_no_pmtu_disc0Disables PMTUD (do not)kernel ip-sysctl
net.netfilter.nf_conntrack_maxnf_conntrack_buckets (memory-based)conntrack table sizekernel nf_conntrack-sysctl
net.netfilter.nf_conntrack_tcp_timeout_established432000 (5 days)How long idle established flows staykernel nf_conntrack-sysctl
net.core.somaxconn4096 (kernel 5.4+)Listen backlog caplisten(2)
ulimit -n1024 soft on many distrosfds per processshell/systemd

Counters worth knowing ​

CounterWhereMeans when it rises
TcpRetransSegsnstatLoss or congestion somewhere on the path
TcpExtListenOverflows, TcpExtListenDropsnstat (server)Accept queue full: app not accepting fast enough
TcpAttemptFailsnstatOutbound connects failing (refused, reset in SYN-SENT)
TcpEstabResetsnstatEstablished connections reset
TcpExtTCPTimeoutsnstatRTO fired: packets unacknowledged
nf_conntrack_count vs nf_conntrack_max/proc/sys/net/netfilter/Saturation of the conntrack table
drop, early_drop, insert_failedconntrack -Sconntrack full, or NAT port allocation races
retrans: / rtt: / pmtu:ss -tiPer-connection health
Flow log REJECT recordsAWS VPC Flow LogsSecurity group/NACL denied the flow
ErrorPortAllocation, IdleTimeoutCount, PacketsDropCountCloudWatch NAT gatewayNAT port exhaustion, idle resets, drops

Containers and Kubernetes ​

QuestionDockerKubernetes
Get a shell with tools in the app's network namespacedocker run --rm -it --net container:app nicolaka/netshootkubectl debug -it pod/app --image=nicolaka/netshoot --target=app
Same, from the hostnsenter -t PID -n (PID from docker inspect)nsenter on the node, or kubectl debug node/NODE -it --image=...
What listens inside?docker exec app ss -ltn or via netshootsame via ephemeral container
Is the port published?docker port app, docker ps PORTS columnService port/targetPort, kubectl get svc
Does the name resolve inside?Embedded DNS 127.0.0.11: nslookup svckubectl exec -i -t dnsutils -- nslookup kubernetes.default
Does the Service have backends?—kubectl get endpointslices -l kubernetes.io/service-name=svc (empty: selector or readiness)
Bypass Service/Ingress/policy to test the pod itselfdocker exec / curl the container IPkubectl port-forward pod/app 8080:8080 then curl localhost:8080
Who is dropping?iptables -L DOCKER-USER -v, docker network inspectkubectl get networkpolicy -A; kube-proxy rules iptables -t nat -L KUBE-SERVICES, ipvsadm -Ln
MTUdocker network inspect option com.docker.network.driver.mtu (bridge driver option: "Set the containers network Maximum Transmission Unit")CNI MTU (Calico/Flannel/Cilium setting), ip link inside pod

Ephemeral containers became stable in Kubernetes v1.25; the docs describe them as useful "when kubectl exec is insufficient because a container has crashed or a container image doesn't include debugging utilities, such as with distroless images." kubectl port-forward is the best bisection tool in Kubernetes: if the pod answers through port-forward but not through the Service, the problem is Service selector, endpoints, kube-proxy or NetworkPolicy, not the app. NetworkPolicy semantics in one line from the docs: "By default, a pod is non-isolated for ingress"; as soon as any policy with Ingress in policyTypes selects it, only allowed traffic passes.

Cloud: security group vs NACL vs route table vs NAT gateway ​

Layer (AWS names; Azure/GCP have equivalents)Stateful?Typical symptom when wrongEvidence
Security groupYes: "Return traffic: Automatically allowed (stateful)"Connect timeoutFlow Logs REJECT; Reachability Analyzer
Network ACLNo: return traffic "Must be explicitly allowed (stateless)", rules evaluated "in ascending order until a match"Timeout, often only for replies to ephemeral portsFlow Logs REJECT on the return direction
Route table—Timeout (no route to NAT/IGW/peering), or asymmetric pathRoute table of the subnet; traceroute -T
NAT gatewayYes (it is NAT)Timeouts under load (ErrorPortAllocation), RST after 350 s idleCloudWatch NAT metrics
Load balancer—502/503/504, resets after the idle timeout (ALB default 60 s), targets "unhealthy"LB access logs, target health reason codes
Target health check—Healthy app marked unhealthy: wrong path/port, SG not allowing the LB, HealthCheckTimeoutSeconds (default 5 s for instance/ip targets) too shortTarget group health description

AWS VPC Flow Logs "capture information about the IP traffic going to and from network interfaces", and the docs list "Diagnosing overly restrictive security group rules" as the first use. Each record carries the 5-tuple, bytes, packets and ACCEPT/REJECT. A NACL problem looks like this in flow logs: the inbound SYN is ACCEPT, the outbound reply to an ephemeral port is REJECT.

Solving the classic problems ​

ProblemSolutionHowAdvantageCost / limitation
"It fails" with no detailRun the ladder from the failing placeGo netdiag, Laravel net:diagNames the rung and errno in one runNeeds a shell or an Artisan command in the target environment
Connect hangs for minutesConnect timeout separate from read timeoutnet.Dialer{Timeout}, connectTimeout(), connect_timeoutFails in seconds, frees workersToo short a value fails on slow but healthy paths
Sporadic reset/EOF after idleClient idle timeout below middlebox idle timeout; keepaliveIdleConnTimeout: 50s behind a 60 s ALBRemoves the keep-alive raceSlightly more connections
Ephemeral port / NAT port exhaustionConnection reuseOne shared client, pool sizes, HTTP/2Fixes fds, ports, conntrack, NAT at onceMust bound pools; long-lived connections need rebalancing
MTU black holeAllow ICMP frag-needed; clamp MSS; set overlay MTUSee MTUFixes all sizesNeeds access to the middle box
Can't prove where packets dieCapture on both endstcpdump -w + WiresharkHard evidence for other teamsNeeds root/caps; privacy of payloads
Health checks restart healthy pods during a DB outageSplit liveness (/up) from readiness (/ready) with dependency checks and timeoutsLaravel controller belowOutage removes traffic, not processesReadiness must not flap: use timeouts and thresholds
Next incident takes as long as this oneKeep the counters and probesObservability to keepDetection before users noticeStorage and alert hygiene

Go: netdiag, the ladder in one binary ​

It resolves, connects to every returned IP with a timeout, does the TLS handshake with SNI, sends one HTTP request, and stops at the first failing rung with the errno and its meaning. errors.Is/errors.As see through *net.OpError and *os.SyscallError, so the classification never parses strings.

go
// Command netdiag walks the connection ladder for one URL:
// resolve -> TCP connect -> TLS handshake -> HTTP request,
// and stops at the first rung that fails, naming the errno and what it implies.
//
//	netdiag -timeout 3s https://api.example.com/health
//	netdiag tcp://db:5432          (stops after the TCP rung)
package main

import (
	"bufio"
	"context"
	"crypto/tls"
	"crypto/x509"
	"errors"
	"flag"
	"fmt"
	"io"
	"net"
	"net/http"
	"net/url"
	"os"
	"syscall"
	"time"
)

func main() {
	timeout := flag.Duration("timeout", 3*time.Second, "timeout per rung")
	flag.Parse()
	if flag.NArg() != 1 {
		fmt.Fprintln(os.Stderr, "usage: netdiag [-timeout 3s] https://host[:port]/path | tcp://host:port")
		os.Exit(64)
	}
	u, err := url.Parse(flag.Arg(0))
	if err != nil || u.Hostname() == "" {
		fmt.Fprintln(os.Stderr, "bad URL:", flag.Arg(0))
		os.Exit(64)
	}
	port := u.Port()
	if port == "" {
		port = map[string]string{"http": "80", "https": "443"}[u.Scheme]
	}

	// Rung 1: DNS. The resolver Go uses honours /etc/hosts, resolv.conf and ndots.
	ctx, cancel := context.WithTimeout(context.Background(), *timeout)
	start := time.Now()
	addrs, err := net.DefaultResolver.LookupIPAddr(ctx, u.Hostname())
	cancel()
	if err != nil {
		fail(1, "dns", err)
	}
	fmt.Printf("[1/4] dns   %s -> %v (%s)\n", u.Hostname(), addrs, since(start))

	// Rung 2: TCP. Try every address, like a real client; report each failure.
	var conn net.Conn
	for _, a := range addrs {
		target := net.JoinHostPort(a.IP.String(), port)
		d := net.Dialer{Timeout: *timeout}
		start = time.Now()
		conn, err = d.Dial("tcp", target)
		if err == nil {
			fmt.Printf("[2/4] tcp   %s connected from %s (%s)\n", target, conn.LocalAddr(), since(start))
			break
		}
		fmt.Printf("      tcp   %s failed after %s: %s\n", target, since(start), classify(err))
	}
	if conn == nil {
		fail(2, "tcp", err)
	}
	defer conn.Close()
	if u.Scheme == "tcp" {
		return
	}

	// Rung 3: TLS (https only). SNI and verification use the hostname, not the IP.
	if u.Scheme == "https" {
		tc := tls.Client(conn, &tls.Config{ServerName: u.Hostname(), NextProtos: []string{"http/1.1"}})
		ctx, cancel := context.WithTimeout(context.Background(), *timeout)
		start = time.Now()
		err = tc.HandshakeContext(ctx)
		cancel()
		if err != nil {
			fail(3, "tls", err)
		}
		st := tc.ConnectionState()
		fmt.Printf("[3/4] tls   %s, cert CN=%q (%s)\n", tls.VersionName(st.Version), st.PeerCertificates[0].Subject.CommonName, since(start))
		conn = tc
	} else {
		fmt.Println("[3/4] tls   skipped (plain http)")
	}

	// Rung 4: HTTP. One request on the connection we already proved.
	req, _ := http.NewRequest(http.MethodGet, u.String(), nil)
	req.Header.Set("User-Agent", "netdiag/1")
	req.Close = true
	_ = conn.SetDeadline(time.Now().Add(*timeout))
	start = time.Now()
	if err = req.Write(conn); err != nil {
		fail(4, "http", err)
	}
	resp, err := http.ReadResponse(bufio.NewReader(conn), req)
	if err != nil {
		fail(4, "http", err)
	}
	n, _ := io.Copy(io.Discard, resp.Body)
	resp.Body.Close()
	fmt.Printf("[4/4] http  %s, %d body bytes (%s)\n", resp.Status, n, since(start))
	if resp.StatusCode >= 500 {
		os.Exit(5) // the network is fine; the server is not
	}
}

// classify turns an error into "ERRNO: meaning" using errors.Is/As,
// which see through *net.OpError, *os.SyscallError and *url.Error wrappers.
func classify(err error) string {
	var dnsErr *net.DNSError
	var certErr *tls.CertificateVerificationError
	var hostErr x509.HostnameError
	var recErr tls.RecordHeaderError
	switch {
	case errors.As(err, &dnsErr) && dnsErr.IsNotFound:
		return fmt.Sprintf("NXDOMAIN/no such host (server %s): name typo, wrong search domain, record missing", dnsErr.Server)
	case errors.As(err, &dnsErr) && dnsErr.IsTimeout:
		return fmt.Sprintf("DNS timeout (server %s): resolver unreachable or UDP/53 filtered", dnsErr.Server)
	case errors.As(err, &dnsErr):
		return fmt.Sprintf("DNS failure %q (server %s): SERVFAIL or a broken upstream", dnsErr.Err, dnsErr.Server)
	case errors.Is(err, syscall.ECONNREFUSED):
		return "ECONNREFUSED: the host answered with RST; nothing listens on that ip:port (wrong port, bound to 127.0.0.1, process down) or a REJECT rule"
	case errors.Is(err, syscall.EHOSTUNREACH):
		return "EHOSTUNREACH: no ARP answer on the local subnet, or an ICMP host-unreachable/host-prohibited from a router or firewall"
	case errors.Is(err, syscall.ENETUNREACH):
		return "ENETUNREACH: no route to that network in the local routing table (missing default route, IPv6 without connectivity)"
	case errors.Is(err, syscall.EADDRNOTAVAIL):
		return "EADDRNOTAVAIL: no free local ephemeral port for this destination (port exhaustion) or binding a non-local address"
	case errors.Is(err, syscall.EMFILE), errors.Is(err, syscall.ENFILE):
		return "EMFILE/ENFILE: out of file descriptors (ulimit -n); leaked connections or too low a limit"
	case errors.Is(err, syscall.ECONNRESET):
		return "ECONNRESET: the peer (or a middlebox: LB, NAT, firewall) sent RST on an established connection"
	case errors.Is(err, syscall.EPIPE):
		return "EPIPE: wrote to a connection the peer already closed/reset"
	case errors.Is(err, syscall.ETIMEDOUT):
		return "ETIMEDOUT: the kernel gave up retransmitting (SYN or data never acknowledged)"
	case errors.As(err, &certErr), errors.As(err, &hostErr):
		return "certificate rejected: " + err.Error() + " (see the TLS chapter)"
	case errors.As(err, &recErr):
		return "not TLS: the server answered with plain bytes (wrong port or plain HTTP on 443)"
	case errors.Is(err, io.EOF), errors.Is(err, io.ErrUnexpectedEOF):
		return "EOF: the peer closed the connection without a full answer (crash, idle-timeout close, proxy limit)"
	}
	var ne net.Error
	if errors.As(err, &ne) && ne.Timeout() {
		return "timeout: no answer within our deadline; packets are being dropped (firewall/SG/NACL DROP, wrong route, host down) or the peer is stalled"
	}
	return "unclassified: " + err.Error()
}

func fail(rung int, name string, err error) {
	fmt.Printf("FAIL  rung %d (%s): %v\n      %s\n", rung, name, err, classify(err))
	os.Exit(rung)
}

func since(t time.Time) time.Duration { return time.Since(t).Round(time.Millisecond) }

Real runs (Linux container, Docker network ntplab, nginx at 10.231.0.10):

$ netdiag http://ntp-web/
[1/4] dns   ntp-web -> [{10.231.0.10 }] (1ms)
[2/4] tcp   10.231.0.10:80 connected from 10.231.0.2:47494 (0s)
[3/4] tls   skipped (plain http)
[4/4] http  200 OK, 896 body bytes (0s)

$ netdiag tcp://ntp-web:81
[1/4] dns   ntp-web -> [{10.231.0.10 }] (1ms)
FAIL  rung 2 (tcp): dial tcp 10.231.0.10:81: connect: connection refused
      ECONNREFUSED: the host answered with RST; nothing listens on that ip:port (wrong port, bound to 127.0.0.1, process down) or a REJECT rule

$ netdiag -timeout 15s tcp://10.231.0.99:80
      tcp   10.231.0.99:80 failed after 3.101s: EHOSTUNREACH: no ARP answer on the local subnet, ...
FAIL  rung 2 (tcp): dial tcp 10.231.0.99:80: connect: no route to host

$ netdiag http://ntp-wbe/
FAIL  rung 1 (dns): lookup ntp-wbe on 127.0.0.11:53: no such host
      NXDOMAIN/no such host (server 127.0.0.11:53): name typo, wrong search domain, record missing

$ netdiag -timeout 2s https://ntp-web:80/
[2/4] tcp   10.231.0.10:80 connected from 10.231.0.2:42402 (0s)
FAIL  rung 3 (tls): tls: first record does not look like a TLS handshake
      not TLS: the server answered with plain bytes (wrong port or plain HTTP on 443)

$ ip route del default; netdiag -timeout 2s tcp://1.1.1.1:443
FAIL  rung 2 (tcp): dial tcp 1.1.1.1:443: connect: network is unreachable

The exit code is the rung number, so a CI smoke test or a Kubernetes init container can tell "DNS broken" (1) from "port closed" (2) from "server error" (5).

Go: timing and a client that survives middleboxes ​

go
// Command timing prints a curl -w style breakdown for one HTTP request with
// net/http/httptrace, and shows the client settings that prevent the classic
// "connection reset by peer" on reused idle connections.
package main

import (
	"crypto/tls"
	"fmt"
	"io"
	"net"
	"net/http"
	"net/http/httptrace"
	"os"
	"time"
)

// newClient: every timeout set, idle connections retired BEFORE the shortest
// idle timeout on the path (AWS ALB default 60 s, AWS NAT gateway 350 s).
func newClient() *http.Client {
	dialer := &net.Dialer{
		Timeout:   3 * time.Second,  // connect timeout: a dropped SYN fails fast
		KeepAlive: 30 * time.Second, // TCP keepalive probes on idle sockets
	}
	tr := &http.Transport{
		Proxy:                 http.ProxyFromEnvironment,
		DialContext:           dialer.DialContext,
		TLSHandshakeTimeout:   3 * time.Second,
		ResponseHeaderTimeout: 10 * time.Second,
		IdleConnTimeout:       50 * time.Second, // < 60 s ALB idle timeout
		MaxIdleConns:          100,
		MaxIdleConnsPerHost:   32, // default is 2: bursts open (and TIME_WAIT) many ports
		ForceAttemptHTTP2:     true,
	}
	return &http.Client{Transport: tr, Timeout: 15 * time.Second}
}

func main() {
	if len(os.Args) != 2 {
		fmt.Fprintln(os.Stderr, "usage: timing URL")
		os.Exit(64)
	}
	client := newClient()
	for i := 1; i <= 2; i++ { // the second request shows connection reuse
		var t0, dnsStart, dnsDone, connStart, connDone, tlsStart, tlsDone, firstByte time.Time
		var reused bool
		trace := &httptrace.ClientTrace{
			DNSStart:             func(httptrace.DNSStartInfo) { dnsStart = time.Now() },
			DNSDone:              func(httptrace.DNSDoneInfo) { dnsDone = time.Now() },
			ConnectStart:         func(_, _ string) { connStart = time.Now() },
			ConnectDone:          func(_, _ string, _ error) { connDone = time.Now() },
			TLSHandshakeStart:    func() { tlsStart = time.Now() },
			TLSHandshakeDone:     func(tls.ConnectionState, error) { tlsDone = time.Now() },
			GotConn:              func(i httptrace.GotConnInfo) { reused = i.Reused },
			GotFirstResponseByte: func() { firstByte = time.Now() },
		}
		req, _ := http.NewRequest(http.MethodGet, os.Args[1], nil)
		req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))
		t0 = time.Now()
		resp, err := client.Do(req)
		if err != nil {
			fmt.Println("error:", err)
			os.Exit(1)
		}
		_, _ = io.Copy(io.Discard, resp.Body)
		resp.Body.Close()
		fmt.Printf("request %d: %s reused=%v dns=%s connect=%s tls=%s ttfb=%s total=%s\n",
			i, resp.Status, reused, d(dnsStart, dnsDone), d(connStart, connDone),
			d(tlsStart, tlsDone), firstByte.Sub(t0).Round(time.Millisecond), time.Since(t0).Round(time.Millisecond))
	}
}

func d(a, b time.Time) time.Duration {
	if a.IsZero() {
		return 0 // phase skipped: cached DNS or a reused connection
	}
	return b.Sub(a).Round(time.Millisecond)
}
$ timing http://ntp-web/
request 1: 200 OK reused=false dns=1ms connect=0s tls=0s ttfb=3ms total=3ms
request 2: 200 OK reused=true dns=0s connect=0s tls=0s ttfb=0s total=0s

The second request skips DNS, connect and TLS because the connection was reused. If you see reused=false on every request in production, you are paying the handshake each time and burning ephemeral ports (usual causes: not draining/closing resp.Body, a new http.Client per request, or MaxIdleConnsPerHost left at its default of 2 under concurrency).

Go: a PMTU probe that does not trust ICMP ​

go
//go:build linux

// Command pmtuprobe finds the largest datagram that really crosses a path,
// in the spirit of RFC 8899 (DPLPMTUD): it does not trust ICMP; it sends
// probes with the DF bit set and counts only sizes that the far end echoes.
//
//	pmtuprobe -listen :9999                  (on the far end: a UDP echo)
//	pmtuprobe -target 10.0.2.20:9999         (on the near end)
package main

import (
	"errors"
	"flag"
	"fmt"
	"net"
	"os"
	"syscall"
	"time"
)

const ipUDPHeaders = 28 // 20-byte IPv4 header + 8-byte UDP header

func main() {
	listen := flag.String("listen", "", "run the UDP echo responder on this address")
	target := flag.String("target", "", "probe the path to this echo responder")
	flag.Parse()
	switch {
	case *listen != "":
		echo(*listen)
	case *target != "":
		probe(*target)
	default:
		flag.Usage()
		os.Exit(64)
	}
}

func echo(addr string) {
	pc, err := net.ListenPacket("udp4", addr)
	if err != nil {
		panic(err)
	}
	buf := make([]byte, 65535)
	for {
		n, from, err := pc.ReadFrom(buf)
		if err != nil {
			continue
		}
		// Echo only the length (4 bytes), so the reply itself never hits the limit.
		_, _ = pc.WriteTo([]byte(fmt.Sprintf("%04d", n%10000)), from)
	}
}

func probe(target string) {
	conn, err := net.Dial("udp4", target)
	if err != nil {
		panic(err)
	}
	defer conn.Close()
	raw, _ := conn.(*net.UDPConn).SyscallConn()
	// IP_PMTUDISC_DO: set DF on every packet and never fragment locally.
	_ = raw.Control(func(fd uintptr) {
		err = syscall.SetsockoptInt(int(fd), syscall.IPPROTO_IP, syscall.IP_MTU_DISCOVER, syscall.IP_PMTUDISC_DO)
	})
	if err != nil {
		panic(err)
	}

	lo, hi := 576, 9000 // RFC 791 minimum datagram every host must accept .. jumbo frames
	for lo < hi {
		mid := (lo + hi + 1) / 2
		switch ok, why := try(conn, mid); {
		case ok:
			fmt.Printf("probe %5d bytes: echoed\n", mid)
			lo = mid
		default:
			fmt.Printf("probe %5d bytes: %s\n", mid, why)
			hi = mid - 1
		}
	}
	fmt.Printf("path MTU (confirmed by echo): %d bytes\n", lo)
	fmt.Printf("kernel's cached PMTU (from ICMP, IP_MTU): %d bytes\n", kernelMTU(raw))
	fmt.Printf("largest TCP MSS that fits: %d bytes\n", lo-40)
}

func try(conn net.Conn, size int) (bool, string) {
	payload := make([]byte, size-ipUDPHeaders)
	for attempt := 0; attempt < 3; attempt++ {
		if _, err := conn.Write(payload); err != nil {
			if errors.Is(err, syscall.EMSGSIZE) {
				return false, "EMSGSIZE (bigger than the local/cached PMTU, refused before sending)"
			}
			if errors.Is(err, syscall.ECONNREFUSED) {
				return false, "ECONNREFUSED (ICMP port unreachable: no echo responder)"
			}
			return false, err.Error()
		}
		_ = conn.SetReadDeadline(time.Now().Add(400 * time.Millisecond))
		buf := make([]byte, 16)
		if _, err := conn.Read(buf); err == nil {
			return true, ""
		}
	}
	return false, "no echo after 3 tries (dropped: black hole or ICMP frag-needed filtered)"
}

func kernelMTU(raw syscall.RawConn) int {
	mtu := -1
	_ = raw.Control(func(fd uintptr) {
		mtu, _ = syscall.GetsockoptInt(int(fd), syscall.IPPROTO_IP, syscall.IP_MTU)
	})
	return mtu
}
go
//go:build !linux

package main

import (
	"fmt"
	"os"
)

// The DF bit and IP_MTU are Linux socket options; run the probe in a Linux
// container (docker run --rm -v "$PWD":/w -w /w golang go run ./pmtuprobe ...).
func main() {
	fmt.Fprintln(os.Stderr, "pmtuprobe needs Linux (IP_MTU_DISCOVER / IP_MTU)")
	os.Exit(1)
}

The probe sets IP_PMTUDISC_DO (DF on, never fragment locally), binary-searches the datagram size and counts a size as good only when the far end echoes it: the RFC 8899 idea of confirming with acknowledgements instead of waiting for ICMP. It also prints the kernel's cached PMTU (IP_MTU), which only changes if an ICMP "fragmentation needed" arrived. Through a black hole the two numbers disagree; that disagreement is the diagnosis. Real output is in Lab step 6.

Go: reproducing ephemeral port exhaustion ​

go
// Command portexhaust reproduces ephemeral-port exhaustion against ONE
// destination ip:port. Run it in a container with a tiny port range:
//
//	docker run --rm --sysctl net.ipv4.ip_local_port_range="40000 40009" ...
//	portexhaust -serve :8080              (accept and hold)
//	portexhaust -target srv:8080 -n 50    (open and keep 50 connections)
//	portexhaust -target srv:8080 -churn   (open+close: TIME_WAIT version)
package main

import (
	"errors"
	"flag"
	"fmt"
	"net"
	"os"
	"syscall"
	"time"
)

func main() {
	serve := flag.String("serve", "", "accept connections on this address and hold them")
	target := flag.String("target", "", "destination ip:port")
	n := flag.Int("n", 100, "connections to attempt")
	churn := flag.Bool("churn", false, "close each connection right away (client side ends in TIME_WAIT)")
	flag.Parse()

	if *serve != "" {
		ln, err := net.Listen("tcp", *serve)
		if err != nil {
			panic(err)
		}
		var held []net.Conn
		for {
			c, err := ln.Accept()
			if err == nil {
				held = append(held, c) // hold: never close
			}
		}
	}
	if *target == "" {
		flag.Usage()
		os.Exit(64)
	}

	var open []net.Conn
	for i := 1; i <= *n; i++ {
		c, err := net.DialTimeout("tcp", *target, 2*time.Second)
		if err != nil {
			fmt.Printf("connection %d failed: %v\n", i, err)
			if errors.Is(err, syscall.EADDRNOTAVAIL) {
				fmt.Println("=> EADDRNOTAVAIL: every local port for this 4-tuple is taken.")
				fmt.Println("   Fix: reuse connections (keep-alive/pool), widen ip_local_port_range, add source IPs, or spread destinations.")
			}
			os.Exit(1)
		}
		if *churn {
			c.Close() // active close: this side keeps the port in TIME_WAIT for 60 s
		} else {
			open = append(open, c)
		}
		if i%5 == 0 {
			fmt.Printf("%d connections ok (last local port %s)\n", i, c.LocalAddr())
		}
	}
	fmt.Printf("all %d ok\n", *n)
}

Real run, a client container with only ten ephemeral ports:

$ docker run --rm --network ntplab --sysctl net.ipv4.ip_local_port_range="40000 40009" ... portexhaust -target 10.231.0.20:8080 -n 50
5 connections ok (last local port 10.231.0.2:40002)
connection 10 failed: dial tcp 10.231.0.20:8080: connect: cannot assign requested address
=> EADDRNOTAVAIL: every local port for this 4-tuple is taken.

$ ... portexhaust -target 10.231.0.10:80 -churn -n 50        (open + close each time)
connection 10 failed: dial tcp 10.231.0.10:80: connect: cannot assign requested address
$ awk 'NR>1 && $4=="06"' /proc/net/tcp | wc -l              (state 06 = TIME_WAIT)
9

The -churn run is the surprising one: every connection was closed, yet the ports are gone, because the side that closes first keeps each port in TIME_WAIT. Holding connections open and closing them quickly exhaust the same range; only reuse avoids both.

Laravel and PHP ​

Diagnose from Artisan. The command runs the same ladder against the database and Redis hosts from the app's own config, from the same container, then lets the real driver do its handshake (authentication, TLS, protocol), so "TCP works but PDO fails" is visible as its own rung. It uses stream_socket_client(), whose $errno/$errstr are the kernel's errno and the C library's text (real: errno=111 "Connection refused", errno=110 "Operation timed out", errno=113 "Host is unreachable" on Alpine/musl).

php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Throwable;

/**
 * php artisan net:diag
 * php artisan net:diag --url=https://partner.example.com/health
 *
 * Runs the ladder (DNS -> TCP -> driver handshake) for every dependency the
 * app is configured with, FROM the same container/pod/env the app runs in.
 */
class NetDiagCommand extends Command
{
    protected $signature = 'net:diag {--url=* : Extra HTTP(S) URLs to test} {--timeout=3 : Seconds per rung}';

    protected $description = 'Diagnose connectivity to the database, Redis and HTTP dependencies rung by rung';

    public function handle(): int
    {
        $timeout = (float) $this->option('timeout');
        $failed = 0;

        $db = config('database.connections.'.config('database.default'));
        $redis = config('database.redis.default');

        $targets = [
            ['db', $db['host'] ?? '127.0.0.1', (int) ($db['port'] ?? 5432)],
            ['redis', $redis['host'] ?? '127.0.0.1', (int) ($redis['port'] ?? 6379)],
        ];
        foreach ($this->option('url') as $url) {
            $p = parse_url($url);
            $targets[] = [$url, $p['host'], (int) ($p['port'] ?? (($p['scheme'] ?? 'http') === 'https' ? 443 : 80))];
        }

        foreach ($targets as [$name, $host, $port]) {
            $this->line("<info>{$name}</info> {$host}:{$port}");
            $failed += $this->ladder($name, $host, $port, $timeout) ? 0 : 1;
        }

        return $failed === 0 ? self::SUCCESS : self::FAILURE;
    }

    private function ladder(string $name, string $host, int $port, float $timeout): bool
    {
        // Rung 1: DNS. gethostbynamel() uses the system resolver (hosts file, resolv.conf).
        $t = microtime(true);
        $ips = filter_var($host, FILTER_VALIDATE_IP) ? [$host] : gethostbynamel($host);
        if ($ips === false) {
            $this->error('  [dns]  cannot resolve '.$host.' (NXDOMAIN, SERVFAIL or resolver timeout): check the name, search domains, /etc/resolv.conf');

            return false;
        }
        $this->line(sprintf('  [dns]  %s (%.0f ms)', implode(', ', $ips), (microtime(true) - $t) * 1000));

        // Rung 2: TCP. errno/errstr are the kernel's: 111 refused, 113 no route, 110 timed out.
        $t = microtime(true);
        $sock = @stream_socket_client("tcp://{$ips[0]}:{$port}", $errno, $errstr, $timeout);
        if ($sock === false) {
            $this->error(sprintf('  [tcp]  errno %d "%s" after %.1f s: %s', $errno, $errstr, microtime(true) - $t, $this->hint($errno, $errstr)));

            return false;
        }
        fclose($sock);
        $this->line(sprintf('  [tcp]  connected (%.0f ms)', (microtime(true) - $t) * 1000));

        // Rung 3: the real driver (auth, TLS, protocol) with the app's own config.
        try {
            match ($name) {
                'db' => DB::connection()->select('select 1'),
                'redis' => Redis::connection()->ping(),
                default => null,
            };
            $this->line('  [app]  driver handshake ok');
        } catch (Throwable $e) {
            $this->error('  [app]  '.class_basename($e).': '.$e->getMessage());

            return false;
        }

        return true;
    }

    private function hint(int $errno, string $errstr): string
    {
        return match (true) {
            $errno === 111 => 'RST: nothing listens there (wrong port, bound to 127.0.0.1, container down) or a REJECT rule',
            $errno === 113 => 'no route to host: ARP failed on the subnet, or an ICMP host-prohibited from a firewall',
            $errno === 101 => 'network unreachable: no route (missing default route, internal-only network)',
            $errno === 110, str_contains($errstr, 'timed out') => 'SYN dropped: security group/NACL/iptables DROP, wrong route, host down',
            default => 'see the troubleshooting table',
        };
    }
}

The shape of its output (the DNS and TCP rungs use exactly the PHP calls whose real results are quoted above; the Artisan command itself was reviewed, not run here):

$ php artisan net:diag --url=https://partner.example.com/health
db postgres:5432
  [dns]  10.240.2.3 (1 ms)
  [tcp]  connected (0 ms)
  [app]  driver handshake ok
redis redis:6379
  [dns]  cannot resolve redis (NXDOMAIN, SERVFAIL or resolver timeout): check the name, search domains, /etc/resolv.conf

For one-off checks php artisan tinker works too: DB::connection()->getPdo() and Redis::connection()->ping() raise the driver's exception with the libpq or Redis message inside (SQLSTATE[08006] [7] connection to server at ... failed: Connection refused is the shape PDO gives a libpq connection failure).

Map HTTP client errors to layers. The Laravel 13 docs: when a timeout is exceeded "an instance of Illuminate\Http\Client\ConnectionException will be thrown"; connectTimeout defaults to 10 seconds and timeout to 30. RequestException means the network worked and a 4xx/5xx came back (after throw()). Retry the first kind (idempotent calls only), not the second.

php
<?php

namespace App\Services;

use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use RuntimeException;
use Throwable;

/**
 * Map transport failures (no HTTP response at all) and HTTP failures
 * (a response with 4xx/5xx) to different handling. They need different fixes.
 */
class PartnerClient
{
    public function quote(array $payload): array
    {
        try {
            return Http::baseUrl(config('services.partner.url'))
                ->connectTimeout(2)   // a dropped SYN fails in 2 s, not 10
                ->timeout(5)          // whole request, including TLS and body
                ->retry(3, 200, function (Throwable $e, PendingRequest $request) {
                    // Retry transport errors and 502/503/504; never retry 4xx.
                    return $e instanceof ConnectionException
                        || ($e instanceof RequestException && in_array($e->response->status(), [502, 503, 504], true));
                })
                ->post('/quotes', $payload)
                ->throw()
                ->json();
        } catch (ConnectionException $e) {
            // The message carries libcurl's text, e.g.
            // "cURL error 7: Failed to connect to partner port 443 ... Couldn't connect to server"
            // "cURL error 28: Connection timed out after 2002 milliseconds"
            // "cURL error 6: Could not resolve host: partner"
            Log::warning('partner transport failure', [
                'curl_errno' => preg_match('/cURL error (\d+)/', $e->getMessage(), $m) ? (int) $m[1] : null,
                'message' => $e->getMessage(),
            ]);
            throw new RuntimeException('Partner unreachable (network layer)', 0, $e);
        } catch (RequestException $e) {
            // The network worked: we have a status code and a body to log.
            Log::warning('partner http failure', ['status' => $e->response->status()]);
            throw $e;
        }
    }
}

Health endpoints with timeouts. Laravel ships GET /up: "will return a 200 HTTP response if the application has booted without exceptions". Keep that for liveness. Add a readiness endpoint that checks dependencies, each bounded by a short connect timeout, so a database outage takes the pod out of the load balancer rather than into a restart loop.

php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Throwable;

/**
 * GET /ready: readiness, dependencies included, each with its own short timeout.
 * Keep Laravel's built-in GET /up as liveness (process booted, no dependencies),
 * so a database outage removes pods from the load balancer instead of restarting them.
 */
class HealthController extends Controller
{
    public function __invoke(): JsonResponse
    {
        $checks = [
            'database' => fn () => DB::connection()->select('select 1'),
            'redis' => fn () => Redis::connection()->ping(),
            'partner_dns' => fn () => gethostbynamel(parse_url(config('services.partner.url'), PHP_URL_HOST))
                ?: throw new \RuntimeException('cannot resolve'),
        ];

        $result = [];
        $ok = true;
        foreach ($checks as $name => $check) {
            $t = microtime(true);
            try {
                $check();
                $result[$name] = ['ok' => true, 'ms' => (int) ((microtime(true) - $t) * 1000)];
            } catch (Throwable $e) {
                $ok = false;
                $result[$name] = ['ok' => false, 'ms' => (int) ((microtime(true) - $t) * 1000), 'error' => class_basename($e).': '.$e->getMessage()];
            }
        }

        return response()->json(['ok' => $ok, 'checks' => $result], $ok ? 200 : 503);
    }
}
php
<?php

// config/database.php (excerpt): fail fast and survive idle-timeout middleboxes.
// pgsql: PDO passes these DSN keys to libpq (connect_timeout, keepalives_idle).
// redis (phpredis): 'timeout' is the connect timeout, 'read_timeout' the socket read timeout.

return [
    'connections' => [
        'pgsql' => [
            'driver' => 'pgsql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '5432'),
            'database' => env('DB_DATABASE', 'app'),
            'username' => env('DB_USERNAME', 'app'),
            'password' => env('DB_PASSWORD', ''),
            'options' => [
                PDO::ATTR_TIMEOUT => 3, // seconds; for pgsql it maps to connect_timeout
            ],
        ],
    ],
    'redis' => [
        'client' => env('REDIS_CLIENT', 'phpredis'),
        'default' => [
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'port' => env('REDIS_PORT', '6379'),
            'timeout' => 2,
            'read_timeout' => 5,
            'persistent' => false,
        ],
    ],
];

libpq documents connect_timeout and keepalives_idle ("the number of seconds of inactivity after which TCP should send a keepalive message to the server"); pdo_pgsql turns PDO::ATTR_TIMEOUT into connect_timeout. Set keepalives below any NAT/LB idle timeout on the path to the database.

Writing the timeline (SQL) ​

A postmortem-ready timeline is a table of timestamped observations and actions, each with evidence. Keep it while you debug, not after. If your team logs probes or incidents in PostgreSQL, the schema is small and makes "what changed when" queryable:

sql
CREATE TABLE incident_event (
  id          bigserial PRIMARY KEY,
  incident_id text        NOT NULL,
  at          timestamptz NOT NULL DEFAULT now(),
  kind        text        NOT NULL CHECK (kind IN ('symptom','test','hypothesis','change','verify','note')),
  layer       text        CHECK (layer IN ('link','ip','route','arp','firewall','nat','dns','tcp','tls','http','app')),
  source      text,        -- pod/host/region the observation came from
  detail      text        NOT NULL,
  evidence    text         -- command + output excerpt, pcap path, dashboard link
);

-- every change and the first verification after it: did the change fix it?
SELECT c.at AS changed_at, c.detail AS change, v.at AS verified_at, v.detail AS result
FROM incident_event c
LEFT JOIN LATERAL (
  SELECT at, detail FROM incident_event v
  WHERE v.incident_id = c.incident_id AND v.kind = 'verify' AND v.at > c.at
  ORDER BY at LIMIT 1) v ON true
WHERE c.incident_id = 'INC-2026-11-25-db' AND c.kind = 'change'
ORDER BY c.at;
Column of a good timelineExample
Time (UTC, to the minute or second)10:06Z
Who/where"from pod orders-7d9 on node ip-10-0-2-4"
Observation or action"nc -vz 10.0.3.7 5432 timed out"
Evidencecommand, output, pcap file name, graph link
Layer conclusion"TCP: SYN unanswered; DNS ok"
Change (one at a time)"added pod CIDR to sg-db inbound 5432"
Verification"same nc succeeded at 10:15Z; error rate 0 at 10:20Z"

Choosing ​

QuestionFirst toolSecond toolWhy
Is it DNS?getent hosts name (system path)dig @resolver name +searchgetent sees /etc/hosts and nsswitch like the app; dig shows rcode and server
Does anything listen?ss -ltnp on the servercurl -v 127.0.0.1:PORT inside the server namespaceSeparates bind address from network
Is the port reachable from here?nc -vz -w3 IP PORTcurl -v --connect-timeout 3Fast vs refused vs timeout in one line
Where do packets die?tcpdump on both endsFlow logs, conntrack -L, firewall countersEvidence, not inference
Which hop is slow/lossy?mtr --tcp -P 443 hosttraceroute -T -p 443Same protocol/port as the app
Path MTU?ping -M do -s 1472 hosttracepath host, pmtuprobeDF set, full size
Throughput?iperf3 -c hostss -ti during the transferRetransmits and cwnd
HTTP phase timing?curl -wGo httptraceDNS/connect/TLS/TTFB split
What is the app doing?strace -f -e trace=%network -p PIDapp logs with peer IP and phaseSees connect() errno directly
Kernel-wide symptoms?nstat -azconntrack -S, dmesgRetransmits, overflows, drops
Kubernetes Service broken?kubectl port-forward pod/...kubectl get endpointslices, netshoot via kubectl debugBisect Service vs pod
Cloud path?VPC Flow LogsReachability Analyzer / connectivity tests, LB target healthSG/NACL/route evidence
SituationRecommended approachExtra techniqueReason
Hard failure, every requestLadder from the failing placenetdiag / net:diagDeterministic: the first rung names the layer
Intermittent, low rateLog peer IP, local port, reuse flag, phase timings; group by eachRing-buffer capture -C -WFind the hidden variable
Only under loadUSE method on fds, ports, conntrack, NAT ports, backlognstat, conntrack -S, NAT metricsSaturation, not errors in code
Only large payloadsMTU testsMSS clampBlack hole
Only after idleIdle timeouts on the pathKeepalive, pool idle timeoutKeep-alive race
Only after deployLB draining, readinesspreStop, deregistration delayConnections cut mid-flight
Only from one environmentCompare configs: DNS, routes, SG, egress IPdiff of resolv.conf, ip route, rulesEnvironment, not code

In architecture: from a single process to a distributed system ​

The more hops a request crosses, the more places can produce each error string, and the more the "where" question dominates. The method does not change; the number of points you bisect between does.

Everyday example. A developer's Laravel app in Docker Compose cannot reach Postgres: SQLSTATE[08006] ... could not translate host name "postgress". Rung 1 fails; the fix is a one-letter typo in .env. Five minutes with the ladder, an afternoon without it.

Production example (a worked scenario assembled from the documented behaviour above, not a specific published incident). An order service in Kubernetes on AWS calls a payment provider. Under the evening peak, 0.5 % of calls fail with i/o timeout on connect. Split by node: all nodes. Split by destination IP: all. Split by time: only at peak. USE method on the NAT gateway: CloudWatch ErrorPortAllocation > 0. Each pod opened a new TLS connection per payment (a client constructed per request), so thousands of short connections per second went to one destination ip:port through one NAT IP. Fix: one shared client with keep-alive (ports in use fell by two orders of magnitude) and a second Elastic IP on the NAT gateway as headroom. Timeline, graphs and the CloudWatch metric went into the postmortem.

Monolith (one process, one database) ​

Example. One VM: nginx → PHP-FPM → PostgreSQL on localhost, Redis on localhost. The error strings are few and local: connection refused to 127.0.0.1:5432 (Postgres down or listening on another port), too many open files (FPM workers × connections > ulimit -n), address already in use when a second nginx starts. The external edges are DNS and the provider firewall. The ladder runs on one host; ss -ltnp, journalctl and curl -w cover almost everything. The one network trap even here: the cloud firewall or provider security group that silently drops (timeout) while the local ufw rejects (refused): two layers, two behaviours.

Modular monolith ​

Example. The same codebase now runs as web, worker and scheduler containers sharing Postgres and Redis on a Compose or ECS network, and calls three external APIs. New failure surfaces: container DNS (service names, the embedded resolver 127.0.0.11), bind addresses (a module's admin server listening on 127.0.0.1 inside its container), and outbound egress through one NAT. Give every module the same net:diag command and health endpoint; log the module name with every outbound error so "only the worker fails" is visible at once. Keep one HTTP client per external API per process, configured with timeouts and idle limits, instead of ad-hoc clients in each module.

Microservices ​

Example. Twenty services in Kubernetes, a service mesh or plain Services, Ingress at the edge, NAT gateway for egress. A request crosses: client → CDN → LB → Ingress controller → Service (kube-proxy rules) → pod (sidecar) → another Service → pod → database through a NetworkPolicy and a security group. Every arrow is a place where refused, timeout, reset or 503 can be generated (a sidecar can answer 503 for an upstream connect failure; an Ingress returns 502 for an upstream reset). Rules that keep this debuggable:

RuleWhy
Propagate trace IDs and log the peer IP and phase on every outbound errorBisecting needs to know which hop produced the error
Distinguish "error generated by a proxy" from "error from the app" (response headers, proxy access logs)A 503 from Envoy and a 503 from the app are different incidents
Test with kubectl port-forward to the pod, then the Service, then the IngressBisect the in-cluster path in three steps
Default-deny NetworkPolicies come with a test per allowed edgeThe first symptom of a missing rule is a connect timeout
Idle timeouts ordered: client < sidecar < LB < server keep-alivePrevents the keep-alive race on every hop

The design side of retries and timeouts belongs to timeouts, retries and jitter and load balancing; this chapter gives you the evidence that tells you which timeout fired.

Distributed data: replicas, caches, multi-region ​

Example. A primary database in one region, a read replica and a Redis cache in another, connected by peering or a VPN. Failures here are dominated by long-lived connections and middleboxes: a replication or pooled connection idles past a NAT/firewall timeout and dies with a reset on the next query; the VPN's smaller MTU turns large result sets into hangs while SELECT 1 health checks pass (health checks are small: they never test the MTU); a DNS failover record with a long TTL keeps clients on the old primary. Defences: TCP keepalives below every idle timeout (keepalives_idle in libpq), MSS clamping on the tunnel, health checks that move a realistic payload size, and low TTLs on failover names. Connection pooling owns pool sizing; replication and failover owns the failover itself.

Scaling path ​

LoadWhat breaks firstWhat to change
1× (tens of requests per second)Config: names, ports, bind addresses, firewall rulesThe ladder; health endpoints; timeouts on every client
10× (hundreds per second)fds and pools; keep-alive races; first TIME_WAIT pile-upsShared clients, pool limits, idle timeouts below LB/NAT; alert on ListenOverflows, retransmits
100× (thousands per second per host)Ephemeral ports per destination, node conntrack, NAT gateway ports, DNS QPS (ndots)Connection reuse everywhere, HTTP/2, more NAT IPs or VPC endpoints, NodeLocal DNSCache, conntrack sizing
GlobalPer-region paths, MTU across tunnels, asymmetric routing, anycastSynthetic probes per region and per path, flow logs, MTU standards per overlay, runbooks per error string

Observability to keep ​

Most of an incident is spent collecting evidence that could have been collected already. Keep these (design of the stack is in observability):

SignalSourceAlert / use
Outbound errors by class (refused, timeout, reset, DNS, TLS) and by peerApp logs/metrics using the classify mappingSpike in one class names the layer before anyone logs in
Connect, TLS and TTFB latency per dependencyhttptrace, Guzzle on_stats, curl -w in probesp99 connect time rising = network or SYN backlog
Pool stats: open, idle, waiting, created/ssql.DB.Stats(), Laravel/Horizon metrics, PgBouncerCreated/s high = no reuse
DNS: query rate, NXDOMAIN, SERVFAIL, latencyCoreDNS metrics, resolver logsndots storms, upstream failures
TCP counters: retransmits, resets, listen overflowsnstat, node exporterPath loss, accept queue saturation
conntrack count / max, insert_failed, dropnode exporter (nf_conntrack_entries), conntrack -SSaturation before drops
fds per process vs limit/proc/PID/fd, process exporterLeaks
TIME_WAIT count per destinationss -tan state time-waitChurn
NAT gateway and LB metricsCloudWatch / cloud equivalentPort allocation errors, idle timeouts, unhealthy targets
Synthetic probes from each region/network to each dependencyBlackbox exporter, netdiag in a cron jobDetects path problems with no user traffic
Flow logsVPC Flow LogsProof of SG/NACL rejects

Lab ​

Six broken scenarios (bind address, publish, internal network, DNS typo, firewall, MTU) in one Compose file, plus capture practice. Everything below ran on Docker Desktop (Linux VM, kernel 7.0); the output is real and trimmed only where marked with .... Every step uses the ladder: name, route, connect, TLS/HTTP. The fixes for steps 1-5 are the one-line changes named in each step and were not re-run here; the three MTU fixes in step 6 were run and their output is shown.

yaml
# Six broken scenarios plus an MTU black hole. Run:
#   docker compose -p ntplab up -d --build
#   docker compose -p ntplab exec client sh     (then follow the lab steps)
#   docker compose -p ntplab down
name: ntplab

x-tools: &tools
  build:
    context: .
    dockerfile_inline: |
      FROM alpine:3
      RUN apk add --no-cache iptables iproute2 tcpdump curl bind-tools conntrack-tools \
          iputils iputils-tracepath mtr strace netcat-openbsd busybox-extras
  image: ntplab-tools

services:
  # A client with every tool, on the "front" network and the internal "back" network.
  client:
    <<: *tools
    command: sh -c "ip route add 10.240.3.0/24 via 10.240.1.254 && sleep infinity"
    cap_add: [NET_ADMIN, NET_RAW]
    networks:
      front: { ipv4_address: 10.240.1.5 }
      back: {}
    environment:
      DB_HOST: postgress            # scenario 4: a typo, the service is "postgres"

  # 1. Wrong bind address: listens on 127.0.0.1 inside the container, port published.
  bind-wrong:
    <<: *tools
    command: busybox-extras httpd -f -p 127.0.0.1:8000 -h /etc
    ports: ["127.0.0.1:8001:8000"]
    networks: [front]

  # 2. Missing port publish: the service works, but no host port maps to it.
  no-publish:
    image: nginx:alpine
    networks: [front]

  # 3. Internal network: postgres is reachable from client, the internet is not from postgres.
  postgres:
    image: postgres:16-alpine
    environment: { POSTGRES_PASSWORD: secret }
    networks: [back]

  # 5. A firewall: DROP on 80, RST on 81, ICMP host-prohibited on 82.
  fw:
    <<: *tools
    cap_add: [NET_ADMIN]
    networks:
      front: { ipv4_address: 10.240.1.20 }
    command: >
      sh -c "iptables -A INPUT -p tcp --dport 80 -j DROP &&
             iptables -A INPUT -p tcp --dport 81 -j REJECT --reject-with tcp-reset &&
             iptables -A INPUT -p tcp --dport 82 -j REJECT --reject-with icmp-host-prohibited &&
             for p in 80 81 82 8080; do busybox-extras httpd -p $$p -h /etc; done &&
             sleep infinity"

  # 6. MTU black hole: client (front) -> router -> bigserver (mtu network).
  #    The router lowers its front-side link to 1400 and drops the ICMP
  #    "fragmentation needed" it would send back to bigserver.
  router:
    <<: *tools
    cap_add: [NET_ADMIN]
    sysctls: { net.ipv4.ip_forward: 1 }
    networks:
      front: { ipv4_address: 10.240.1.254 }
      mtu: { ipv4_address: 10.240.3.254 }
    command: >
      sh -c "ip -o -4 addr show | awk '/10.240.1.254/ {print $$2}' > /tmp/if &&
             ip link set dev $$(cat /tmp/if) mtu 1400 &&
             iptables -A OUTPUT -p icmp --icmp-type fragmentation-needed -j DROP &&
             sleep infinity"

  bigserver:
    <<: *tools
    cap_add: [NET_ADMIN]
    networks:
      mtu: { ipv4_address: 10.240.3.10 }
    command: >
      sh -c "ip route add 10.240.1.0/24 via 10.240.3.254 &&
             mkdir -p /srv && head -c 200000 /dev/urandom > /srv/big.bin && echo small > /srv/small.txt &&
             busybox-extras httpd -f -p 8080 -h /srv"

networks:
  front:
    ipam: { config: [{ subnet: 10.240.1.0/24 }] }
  back:
    internal: true                    # scenario 3
    ipam: { config: [{ subnet: 10.240.2.0/24 }] }
  mtu:
    ipam: { config: [{ subnet: 10.240.3.0/24 }] }
bash
docker compose -p ntplab up -d --build
docker compose -p ntplab exec client sh      # the client has every tool and NET_ADMIN

# the Go tools from this chapter, cross-compiled for the Linux containers and copied in
cd docs/snippets/foundations/network-troubleshooting-playbook/go
for p in netdiag pmtuprobe portexhaust timing; do
  GOOS=linux GOARCH=$(docker info -f '{{.Architecture}}' | sed 's/x86_64/amd64/;s/aarch64/arm64/') CGO_ENABLED=0 go build -o /tmp/ntp-bin/$p ./$p
done
for c in ntplab-client-1 ntplab-bigserver-1; do for p in netdiag pmtuprobe portexhaust; do docker cp /tmp/ntp-bin/$p $c:/usr/local/bin/$p; done; done

1. Wrong bind address ​

bind-wrong serves on 127.0.0.1:8000 inside its container and publishes 127.0.0.1:8001:8000.

bash
curl -sS http://127.0.0.1:8001/passwd          # from the host
# curl: (52) Empty reply from server          <- docker-proxy accepted, the backend refused, the proxy closed
docker compose -p ntplab exec client curl -sS http://bind-wrong:8000/passwd
# curl: (7) Failed to connect to bind-wrong:8000 after 0 ms: Could not connect to server
docker compose -p ntplab exec bind-wrong ss -ltn
# LISTEN 0  9  127.0.0.1:8000  0.0.0.0:*      <- the diagnosis: loopback only

Two different symptoms for one cause: from the host the published port answers (the proxy listens) and then closes, so you see an empty reply, not a refusal; from another container it is a plain refusal. Fix: bind 0.0.0.0 (httpd -p 8000, php artisan serve --host=0.0.0.0, --bind 0.0.0.0).

2. Missing port publish ​

no-publish is a working nginx with no ports:.

bash
docker compose -p ntplab port no-publish 80     # invalid IP:0   <- nothing published
curl -sS http://127.0.0.1:8002/                # curl: (7) Failed to connect to 127.0.0.1 port 8002 after 0 ms: Couldn't connect to server
docker compose -p ntplab exec client curl -s -o /dev/null -w '%{http_code}\n' http://no-publish/   # 200

Works inside the network, refused from the host: the service is fine, the publish is missing. Fix: ports: ["8002:80"].

3. Internal network, no egress ​

back is internal: true; postgres is only on it.

bash
docker compose -p ntplab exec postgres sh -c 'ip route; wget -q -T 3 -O /dev/null http://1.1.1.1/'
# 10.240.2.0/24 dev eth0 scope link  src 10.240.2.3        <- no default route at all
# wget: can't connect to remote host (1.1.1.1): Network unreachable
docker run --rm --network ntplab_back ntplab-tools curl -sS -m 3 https://example.com/
# curl: (6) Could not resolve host: example.com (DNS server returned general failure)
docker compose -p ntplab exec client nc -vz -w3 postgres 5432
# Connection to postgres (10.240.2.3) 5432 port [tcp/postgresql] succeeded!

Two rungs fail at once on an internal network: DNS for external names returns SERVFAIL and routing returns unreachable. Internal traffic is fine. Fix (if egress is intended): attach a second, non-internal network or route through an egress proxy.

4. DNS typo ​

The client's DB_HOST is postgress.

bash
docker compose -p ntplab exec client sh -c 'nc -vz -w3 $DB_HOST 5432; getent hosts postgress; echo "getent exit=$?"; dig postgress @127.0.0.11 | grep status'
# nc: getaddrinfo for host "postgress" port 5432: Try again
# getent exit=2
# ;; ->>HEADER<<- opcode: QUERY, status: NXDOMAIN, id: 29853

Rung 1 fails; nothing below it matters. Note the musl text "Try again" for an NXDOMAIN, which misleads people into retrying. Fix the name.

5. Firewall: DROP vs REJECT ​

fw listens on 80, 81, 82 and 8080 with DROP on 80, REJECT --reject-with tcp-reset on 81 and REJECT --reject-with icmp-host-prohibited on 82.

bash
for p in 80 81 82 8080; do netdiag -timeout 3s tcp://10.240.1.20:$p; done
# FAIL  rung 2 (tcp): dial tcp 10.240.1.20:80: i/o timeout                 (after 3.002 s)
# FAIL  rung 2 (tcp): dial tcp 10.240.1.20:81: connect: connection refused (0 s)
# FAIL  rung 2 (tcp): dial tcp 10.240.1.20:82: connect: no route to host   (0 s)
# [2/4] tcp   10.240.1.20:8080 connected from 10.240.1.4:56980 (0s)
docker compose -p ntplab exec fw iptables -L INPUT -v -n
#     6   360 DROP    tcp  --  *  *  0.0.0.0/0  0.0.0.0/0  tcp dpt:80
#     2   120 REJECT  tcp  --  *  *  0.0.0.0/0  0.0.0.0/0  tcp dpt:81 reject-with tcp-reset
#     2   120 REJECT  tcp  --  *  *  0.0.0.0/0  0.0.0.0/0  tcp dpt:82 reject-with icmp-host-prohibited

The same listening service gives three different errors depending only on the rule in front of it. The counters prove which rule matched. Fix: allow the source (and prefer REJECT internally so clients fail fast).

6. MTU black hole ​

The router's link towards the client is 1400 and it drops the ICMP "fragmentation needed" it should send to bigserver.

bash
docker compose -p ntplab exec client sh -c '
  curl -sS -m 5 -o /dev/null -w "small: %{http_code} %{size_download} bytes %{time_total}s\n" http://10.240.3.10:8080/small.txt
  curl -sS -m 5 -o /dev/null -w "big: %{http_code} %{size_download} bytes %{time_total}s\n" http://10.240.3.10:8080/big.bin'
# small: 200 6 bytes 0.000290s
# curl: (28) Operation timed out after 5012 milliseconds with 0 out of 200000 bytes received

docker compose -p ntplab exec bigserver sh -c 'ping -c2 -W1 -M do -s 1472 10.240.1.5; ping -c2 -W1 -M do -s 1372 10.240.1.5; tracepath -n 10.240.1.5'
# 2 packets transmitted, 0 received, 100% packet loss      <- 1500-byte DF packets vanish
# 2 packets transmitted, 2 received, 0% packet loss        <- 1400 fits
#  1?: [LOCALHOST]   pmtu 1500
#  1:  10.240.3.254  0.048ms
#  2:  no reply ...  Resume: pmtu 1500                      <- tracepath never learns: the ICMP is eaten

pmtuprobe -listen :9999                       # on client
pmtuprobe -target 10.240.1.5:9999             # on bigserver
# probe  1629 bytes: EMSGSIZE (bigger than the local/cached PMTU, refused before sending)
# probe  1398 bytes: echoed
# probe  1401 bytes: no echo after 3 tries (dropped: black hole or ICMP frag-needed filtered)
# path MTU (confirmed by echo): 1400 bytes
# kernel's cached PMTU (from ICMP, IP_MTU): 1500 bytes   <- the kernel still believes 1500: the black hole
# largest TCP MSS that fits: 1360 bytes

The stuck connection on the server tells the same story in ss -tino: retransmissions with exponential backoff, a congestion window of 1, and a PMTU that never dropped.

CLOSE-WAIT 1  47288  [::ffff:10.240.3.10]:8080 [::ffff:10.240.1.5]:50864 timer:(on,,9)
   ts sack cubic wscale:10,10 rto:102912 backoff:9 ... mss:1448 pmtu:1500 ... cwnd:1 ssthresh:7 bytes_retrans:14480 ... unacked:11 retrans:1/10 lost:10

The server-side capture shows the retransmissions (the 7240-byte "segments" are GSO super-packets, split by the kernel below tcpdump):

18:26:59.136047 IP 10.240.3.10.8080 > 10.240.1.5.51370: Flags [P.], seq 513740315:513747555, ack 4171154710, ... length 7240: HTTP
18:26:59.140223 IP 10.240.3.10.8080 > 10.240.1.5.51370: Flags [.], seq 0:1448, ack 1, ... length 1448: HTTP
18:26:59.350835 IP 10.240.3.10.8080 > 10.240.1.5.51370: Flags [.], seq 0:1448, ack 1, ... length 1448: HTTP    (+0.21 s)
18:26:59.761298 IP 10.240.3.10.8080 > 10.240.1.5.51370: Flags [.], seq 0:1448, ack 1, ... length 1448: HTTP    (+0.41 s)
18:27:00.575930 IP 10.240.3.10.8080 > 10.240.1.5.51370: Flags [.], seq 0:1448, ack 1, ... length 1448: HTTP    (+0.81 s)
$ nstat -az TcpRetransSegs TcpExtTCPTimeouts
TcpRetransSegs                  15                 0.0
TcpExtTCPTimeouts               13                 0.0

Three fixes, each verified with the same curl:

bash
# fix A: MSS clamping on the router
docker compose -p ntplab exec router iptables -t mangle -A FORWARD -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu
# big: 200 200000 bytes 0.000454s          (counter: 2 SYNs rewritten)
docker compose -p ntplab exec router iptables -t mangle -F FORWARD     # undo before the next fix

# fix B: packetization-layer PMTUD on the sender: a second server with tcp_mtu_probing=1
docker run -d --name ntp-probe-srv --network ntplab_mtu --ip 10.240.3.11 --cap-add NET_ADMIN \
  --sysctl net.ipv4.tcp_mtu_probing=1 ntplab-tools sh -c 'ip route add 10.240.1.0/24 via 10.240.3.254 &&
  mkdir -p /srv && head -c 200000 /dev/urandom > /srv/big.bin && httpd -f -p 8080 -h /srv'
docker compose -p ntplab exec client curl -sS -m 30 -o /dev/null -w "big (tcp_mtu_probing=1) run 1: %{http_code} %{size_download} bytes %{time_total}s\n" http://10.240.3.11:8080/big.bin
# big (tcp_mtu_probing=1) run 1: 200 200000 bytes 3.098087s      <- works, but pays a few RTOs to detect the hole
docker exec ntp-probe-srv nstat -az TcpExtTCPMTUPFail TcpExtTCPMTUPSuccess
# TcpExtTCPMTUPFail 6   TcpExtTCPMTUPSuccess 6

# fix C (the real one): stop dropping ICMP frag-needed on the router
docker compose -p ntplab exec router iptables -D OUTPUT -p icmp --icmp-type fragmentation-needed -j DROP
# big (ICMP allowed): 200 200000 bytes 0.000587s
ip route get 10.240.1.5      # on bigserver
# 10.240.1.5 via 10.240.3.254 dev eth0 src 10.240.3.10 uid 0
#     cache expires 599sec mtu 1400                  <- the kernel learned the PMTU from ICMP
# kernel's cached PMTU (from ICMP, IP_MTU): 1400 bytes   (pmtuprobe again: the two numbers now agree)

Inside a container sysctl -w net.ipv4.tcp_mtu_probing=1 fails with "Read-only file system"; set it at start with --sysctl / Compose sysctls: or on the host.

7. Capture and annotate a RST, a retransmission and an ICMP rejection ​

bash
tcpdump -ni eth0 -X -c 2 'host 10.240.1.20 and port 81' & nc -vz -w2 10.240.1.20 81
# nc: connect to 10.240.1.20 port 81 (tcp) failed: Connection refused
18:23:58.270410 IP 10.240.1.6.37238 > 10.240.1.20.81: Flags [S], seq 4263478037, win 64240, options [mss 1460,sackOK,TS val 3980363860 ecr 0,nop,wscale 10], length 0
	0x0000:  4500 003c f8c6 4000 4006 29fc 0af0 0106  E..<..@.@.).....
	0x0010:  0af0 0114 9176 0051 fe1f 8315 0000 0000  .....v.Q........
	0x0020:  a002 faf0 1828 0000 0204 05b4 0402 080a  .....(..........
	0x0030:  ed3f 8854 0000 0000 0103 030a            .?.T........
18:23:58.270448 IP 10.240.1.20.81 > 10.240.1.6.37238: Flags [R.], seq 0, ack 4263478038, win 0, length 0
	0x0000:  4500 0028 0000 4000 4006 22d7 0af0 0114  E..(..@.@.".....
	0x0010:  0af0 0106 0051 9176 0000 0000 fe1f 8316  .....Q.v........
	0x0020:  5014 0000 1814 0000                      P.......
Bytes (RST packet)FieldValueMeaning
45IP version + header length4, 5 wordsIPv4, 20-byte header
0028Total length4020 IP + 20 TCP, no payload
4000Flags + fragment offsetDF setLinux sets DF
40TTL64Sent by a Linux host one hop away (a middle box would show a different TTL)
06Protocol6TCP
0af0 0114 → 0af0 0106Source → destination10.240.1.20 → 10.240.1.6The server's IP answered (not a proxy)
0051 → 9176Ports81 → 37238Reply to our SYN's port pair
0000 0000Sequence0A RST answering a SYN carries seq 0
fe1f 8316AcknowledgmentSYN seq + 1Acknowledges exactly our SYN (fe1f8315 + 1): it is a direct reply, not injected noise
50Data offset5 words20-byte TCP header, no options
14Flags0x14 = RST + ACKThe [R.] in the summary line
0000Window0Nothing to receive

In the SYN above, a002 is data offset 10 words (40 bytes with options) and flags 0x002 (SYN); 0204 05b4 is the MSS option, 0x05b4 = 1460. The ICMP variant (port 82) shows the rejection type in clear text:

18:24:39.997104 IP (tos 0xc0, ttl 64, id 38260, offset 0, flags [none], proto ICMP (1), length 88)
    10.240.1.20 > 10.240.1.6: ICMP host 10.240.1.20 unreachable - admin prohibited, length 68
	IP (tos 0x0, ttl 64, id 55472, offset 0, flags [DF], proto TCP (6), length 60)
    10.240.1.6.57478 > 10.240.1.20.82: Flags [S], ... length 0          <- the ICMP quotes our SYN

The retransmissions, annotated. Two real captures on this page show them; read them with the same eye:

CaptureWhat repeatsSpacingWhat it proves
Timeout block, DROP on port 80Flags [S], seq 2957620591 six times, same source port 496221.01, 1.02, 1.02, 1.02, 1.02 sSYN retransmissions (linear 1 s timeouts): nothing answered, not even a RST; a filter drops
Step 6, MTU black holeseq 0:1448 (relative) from port 8080+0.21, +0.41, +0.81 s ...Data retransmissions with exponential RTO backoff: the connection exists, the full-size segment never gets ACKed
Step 6, nstatTcpRetransSegs 15, TcpExtTCPTimeouts 13—Kernel-wide confirmation of the same retransmissions

Wireshark's rule is the one quoted in Packet capture: a segment is a "TCP Retransmission" when "the next expected sequence number is greater than the current sequence number". Write the capture with tcpdump -w, open it and apply tcp.analysis.retransmission or tcp.analysis.flags to see these packets marked.

8. Ephemeral ports and TIME_WAIT ​

Run the reproducer with --sysctl net.ipv4.ip_local_port_range="40000 40009": connection 10 fails with cannot assign requested address. Then look at a server that closes first:

bash
docker compose -p ntplab exec fw ss -tano state time-wait
# [::ffff:10.240.1.20]:8080 [::ffff:10.240.1.5]:38162 timer:(timewait,59sec,0)
# [::ffff:10.240.1.20]:8080 [::ffff:10.240.1.5]:34004 timer:(timewait,23sec,0)

The active closer holds each 4-tuple for 60 seconds (timewait,59sec one second after closing).

Clean up ​

bash
docker rm -f ntp-probe-srv
docker compose -p ntplab down

Common misconceptions ​

BeliefReality
"Refused and timeout both mean the service is down"Refused: a host answered RST (no listener, wrong port/bind, REJECT). Timeout: packets were dropped. Different layers, different owners
"ping works, so TCP will work"ICMP has no port, is small, and is filtered and prioritised differently. Test the real port with the real size
"Connection reset by peer means the server crashed"Any middle box (LB, NAT gateway, firewall, sidecar) can send the RST; look at who sent it
"Raising the timeout fixes timeouts"A connect timeout means a drop; waiting longer just holds workers longer
"65,535 ports means 65,535 connections"28,232 ephemeral ports by default, per destination ip:port, per source IP; TIME_WAIT holds them 60 s
"Closing connections quickly saves ports"The side that closes first keeps the port in TIME_WAIT; reuse saves ports
"Lowering MTU on my containers fixes the black hole"A black hole is a smaller link in the middle with ICMP blocked; fix ICMP, clamp MSS or set the overlay MTU
"Blocking all ICMP is safer"It breaks PMTUD (black holes) and makes every failure a slow timeout
"mtr shows loss at hop 3, hop 3 is broken"Only loss that continues to the last hop is real; middle hops rate-limit ICMP
"It works from my laptop, so the network is fine"Your laptop has different DNS, routes, VPN and NAT. Test from the failing pod/container
"no such host means the record does not exist"It means this resolver, with these search domains, said so; another resolver may disagree
"Health checks passing means the path is healthy"Health checks are small and on one port; they do not test MTU, egress or the dependency under load
"tcp_tw_recycle fixes TIME_WAIT"It broke clients behind NAT and no longer exists in current kernels (absent from the ip-sysctl docs); use connection reuse

Cheat sheet ​

TopicRemember
MethodReproduce → localise by layer → bisect client to server → compare working vs broken → change one thing
RefusedRST in ~1 RTT; ss -ltnp; bind 0.0.0.0 in containers
TimeoutSYN dropped; capture both ends; SG/NACL/iptables/route/NAT/conntrack
No route / unreachableARP failed or ICMP prohibited / no route at all; ip route get, ip neigh
Reset / EOF / broken pipeIdle timeouts on the path; client idle < LB/NAT idle; see who sent the RST
DNSgetent hosts, dig +search, resolv.conf, ndots; NXDOMAIN vs SERVFAIL vs timeout
TLSFast failure = certificate/SNI; slow failure = network/MTU; openssl s_client
EMFILE / EADDRINUSE / EADDRNOTAVAILfds / listener port taken / ephemeral ports gone
MTUping -M do -s 1472, tracepath; allow ICMP type 3 code 4; clamp MSS; overlay MTU
conntracknf_conntrack_count vs max; conntrack -S; dmesg "table full"
NAT gatewayAWS: 55,000 concurrent per IP per destination; 350 s idle then RST
Capturetcpdump -ni any -w f.pcap 'host X and port Y'; tcp[tcpflags] & tcp-rst != 0; ring -C -W
Wiresharktcp.analysis.flags, tcp.flags.reset==1, Follow TCP Stream, SSLKEYLOGFILE
Latencycurl -w, mtr --tcp, ss -ti, nstat, iperf3
Containers--net container:X nicolaka/netshoot, kubectl debug --target, nsenter -n, kubectl port-forward
Write it downUTC time, where, observation, evidence, one change, verification

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — A client gets connection refused in 1 ms and another gets i/o timeout after 3 s to the same IP and port. What does each prove? Must-know ​

Answer

Answer: Refused proves the SYN reached a TCP stack (or a REJECT rule) that answered RST: the host is reachable and nothing listens, or a rule rejects. Timeout proves the SYN or the SYN-ACK was dropped: a firewall DROP, route, NAT or a down host. If both happen to the same target from different clients, compare the clients' paths (one passes a DROP rule the other does not).

2 — A container publishes -p 8080:8080 but curl localhost:8080 from the host fails, while docker exec app curl localhost:8080 works. Most likely cause? Must-know ​

Answer

Answer: The app binds 127.0.0.1 inside the container, so it only accepts connections from inside its own network namespace. Traffic arriving via the bridge targets the container's eth0 address. Bind 0.0.0.0. docker exec app ss -ltn shows 127.0.0.1:8080.

3 — Why does connection reset by peer appear mostly on the first request after a quiet period? Important ​

Answer

Answer: The pooled connection outlived an idle timeout on the path (ALB default 60 s, AWS NAT gateway 350 s, or the server's keep-alive timeout). The middle box dropped its state and answers the next packet with RST (or the server closed with FIN, giving EOF). Set the client idle timeout below the shortest one on the path and use keepalives.

4 — Small API responses work through the VPN; a 2 MB export hangs. What do you test and what are the fixes? Important ​

Answer

Answer: An MTU black hole. Test with ping -M do -s 1472 then lower sizes, and tracepath. Fixes: allow ICMP type 3 code 4 (and ICMPv6 Packet Too Big), clamp TCP MSS to the PMTU on the tunnel, set the tunnel/overlay MTU correctly, or enable tcp_mtu_probing=1 on senders.

5 — What does EADDRNOTAVAIL from connect() mean, and why can closing connections quickly make it worse? Important ​

Answer

Answer: No free ephemeral port for that destination ip:port (default range 32768-60999). The side that closes first keeps each port in TIME_WAIT for 60 s, so open-close churn consumes ports as fast as holding connections. Reuse connections (keep-alive, pools), widen the range, add source IPs.

6 — What happens when the conntrack table is full, and how would you see it? Important ​

Answer

Answer: New flows are dropped before they get an entry: clients see connect timeouts, not errors. The kernel logs "nf_conntrack: table full, dropping packet"; nf_conntrack_count equals nf_conntrack_max; conntrack -S shows drop/early_drop. Raise the limit and buckets, shorten timeouts, reuse connections, exempt known heavy flows with NOTRACK.

7 — mtr shows 40 % loss at hop 3 and 0 % at the destination. Is there packet loss? Must-know ​

Answer

Answer: No. Hop 3 rate-limits the ICMP TTL-exceeded replies it generates. Forwarded traffic is fine, which is why the destination shows 0 %. Only loss that persists to the final hop matters.

8 — Which tcpdump filter shows only resets, and which Wireshark filter shows every TCP problem? Good to know ​

Answer

Answer: tcpdump -ni any 'tcp[tcpflags] & tcp-rst != 0'. In Wireshark, tcp.analysis.flags (retransmissions, dup ACKs, zero window, out-of-order and more); tcp.flags.reset==1 for resets.

9 — A Kubernetes pod cannot reach orders:8080. kubectl port-forward pod/orders-x 8080 works. What next? Must-know ​

Answer

Answer: The pod answers, so the app and its bind address are fine. Check the Service: kubectl get endpointslices -l kubernetes.io/service-name=orders (empty means selector mismatch or pods not ready), the Service targetPort, NetworkPolicies selecting either pod, and DNS from the caller pod (kubectl debug with netshoot, then nslookup orders).

10 — Why separate the connect timeout from the request timeout in Laravel's HTTP client? Important ​

Answer

Answer: A connect timeout fires when the SYN is dropped (network problem) and should be short (2-3 s); a request timeout covers TLS, server processing and body transfer (server or payload problem). One long timeout makes a dropped SYN hold a worker for as long as a slow report. Both raise ConnectionException, but the message (cURL error 28: Connection timed out vs Operation timed out ... with N bytes received) tells them apart.

11 — What makes a timeline "postmortem-ready"? Important ​

Answer

Answer: UTC timestamps, where each observation was made, the exact command and output (or capture file) as evidence, one change per line, and the verification that followed each change. It lets someone else replay the reasoning and see which change fixed it.

Glossary ​

TermMeaning
BisectionTesting at the middle of the path to halve the search space each step
USE methodUtilization, saturation, errors for every resource (Brendan Gregg)
RSTTCP reset segment: abort a connection or refuse a SYN
ECONNREFUSEDErrno 111: RST in reply to SYN; nothing listening
ETIMEDOUTErrno 110: the kernel gave up retransmitting
i/o timeoutGo's message when your own deadline fired
EHOSTUNREACHErrno 113: no ARP reply or ICMP host unreachable/prohibited
ENETUNREACHErrno 101: no route to the network
ECONNRESETErrno 104: RST on an established connection
EPIPEErrno 32: write after the peer closed/reset (broken pipe)
EOFRead returned zero bytes: the peer sent FIN
EMFILEErrno 24: too many open files in the process
EADDRINUSEErrno 98: address already in use on bind
EADDRNOTAVAILErrno 99: cannot assign requested address (no ephemeral port)
NXDOMAINDNS rcode 3: the name does not exist
SERVFAILDNS rcode 2: the resolver failed to answer
ndotsresolv.conf option: names with fewer dots go through the search list first
MTUMaximum transmission unit: largest IP packet on a link
MSSMaximum segment size: largest TCP payload, announced in the SYN
PMTUDPath MTU Discovery with DF bit and ICMP "fragmentation needed" (RFC 1191)
PLPMTUD / DPLPMTUDProbing the path with real packets instead of trusting ICMP (RFC 4821, RFC 8899)
DF bitIPv4 "Don't Fragment" flag
Black holePackets silently dropped while the sender is unaware (RFC 8899 definition)
MSS clampingRewriting the MSS option in SYNs on a router to fit the path (TCPMSS --clamp-mss-to-pmtu)
FragmentationSplitting an IP packet into fragments; fragile through firewalls and NAT
conntrackLinux netfilter's connection-tracking table, needed for NAT and stateful rules
nf_conntrack_max / nf_conntrack_countconntrack table limit and current use
Ephemeral portSource port picked by the kernel for outbound connections (ip_local_port_range)
TIME_WAITState the active closer keeps for 60 s on Linux to absorb late segments
SNAT port collisionTwo flows mapped to the same NAT source port; insert_failed, mitigated by --random-fully
NAT gateway port limitAWS: 55,000 concurrent connections per IP per destination (ErrorPortAllocation)
Half-open connectionOne side believes the connection is alive, the other (or a middle box) forgot it
Connection drainingLB keeps existing connections to a deregistering target for a delay
Keep-alive raceA client reuses an idle connection the server or a middle box is closing
tcpdump / pcapPacket capture tool and its file format
Display filterWireshark's post-capture filter language (tcp.analysis.flags)
RetransmissionA segment sent again because it was not acknowledged
Dup ACKRepeated ACK signalling a gap (loss or reordering)
Zero windowReceiver advertises no buffer space: the application is not reading
SSLKEYLOGFILEEnvironment variable that makes TLS libraries write session secrets for Wireshark
mtrContinuous traceroute with per-hop loss and latency
tracepathTraceroute that also discovers the path MTU
iperf3Throughput and loss tester (client and server)
ss -tiSocket statistics with per-connection TCP info (rtt, retrans, cwnd, pmtu)
nstatKernel SNMP counters as deltas
straceSystem-call tracer; -e trace=%network shows connect/accept errors
netshootContainer image with network debugging tools (nicolaka/netshoot)
nsenterRun a program in another process's namespaces (e.g. its network namespace)
Ephemeral containerTemporary debug container added to a running pod (kubectl debug)
kubectl port-forwardTunnel a local port to a pod, bypassing Service, Ingress and policies
Security groupStateful cloud firewall attached to interfaces
Network ACLStateless subnet firewall; return traffic must be allowed explicitly
VPC Flow LogsRecords of accepted/rejected flows per interface
Synthetic probeScheduled test request from a known place to a dependency
Postmortem timelineTimestamped observations, evidence, changes and verifications

References ​

Every URL was fetched and its text saved under scratchpad/sources/network-troubleshooting-playbook/; each returned HTTP 200 when fetched.

Built by Morteza Negahi