Learnings

Cloud and DevOps

Linux and Networking for Backend Engineers

What to know, and what to type, when a service misbehaves on a server: processes, files, memory, TCP, DNS, HTTP and TLS, mostly as diagrams and real terminal sessions. The sessions were captured in two Debian 12 containers (web-1 runs a small bank API, client-1 calls it), so a few things differ from a real server: there is no systemd, memory tools show the whole Docker VM, and traceroute sees only the Docker gateway.

Processes

Part 1 of 6 · what is running, and how it stops

A process and its states

Processes

A process is a running program with a PID, a parent (PPID), an owner and a state. The service used on this page is bank_app.py, a standard-library HTTP server started as python3 bank_app.py HOST PORT.

ps shows these as R (running or runnable), S (sleeping), T (stopped) and Z (zombie).
Keys or commandEffect
cmd &, jobsStart in the background, list this shell's jobs
Ctrl+C, Ctrl+ZSIGINT to the foreground job, or stop it (SIGTSTP)
fg %1, bg %1Resume job 1 in the foreground or background
nohup cmd &Survive the terminal closing. On a server, use a service manager instead.

Signals and exit codes

Processes

A signal is a small asynchronous message to a process. Deploys and orchestrators stop a service with SIGTERM, wait, then send SIGKILL.

SignalNumberSent byCan be handled?
SIGINT2Ctrl+CYes
SIGTERM15kill PID, systemd, Docker, KubernetesYes: finish work, then exit
SIGKILL9kill -9, the OOM killerNo: the kernel removes the process
SIGHUP1Terminal closed, kill -HUPYes: often "reload config"
SIGSTOP / SIGCONT19 / 18kill -STOP, kill -CONTSTOP cannot be handled
  • 0 is success. Killed by signal N shows as 128 + N: 143 is SIGTERM, 137 is SIGKILL.
  • 137 on a container usually means the OOM killer or a stop timeout, not a bug in your exit path.
  • SIGKILL skips every handler: no flush, no connection close. Reach for it last.

Zombies and orphans

Processes

Both are about which of parent and child exits first.

A zombie is only a table entry holding an exit code. An orphan is a live process with a new parent.
  • You cannot kill a zombie. Fix or restart the parent, which must call wait.
  • In a container your app is often PID 1 and reaps nothing. In an earlier run here, killed orphans stayed as zombies under sleep infinity: docker run --init adds a real init.

top, load average and nice

Processes

Read the header first, then the columns. htop shows the same fields with colours.

FieldMeaningWorry when
load averageTasks running, waiting for a CPU or stuck in disk I/O: 1, 5 and 15 minute averagesIt stays above the core count (nproc printed 10 here)
us / sy / wa / stCPU time in your code, in the kernel, waiting for disk, stolen by the hypervisorwa high: disk. st high: noisy neighbour.
%CPUPercent of one coreA threaded process can show 400
VIRTAddress space reserved (KiB)Rarely: it is not memory in use
RESPhysical memory held now (KiB)It grows without bound: a leak
NINice value, -20 (greedy) to 19 (polite). nice -n 10 cmd started a process that ps -o ni showed at 10.

Trap: high load with idle CPU means tasks are blocked on I/O, not short of CPU. Look at wa.

Files, permissions and disk

Part 2 of 6 · where things live, who may touch them, and what fills up

The directories that matter

Files, permissions and disk

Five places answer most "where is it?" questions on a server.

Config in /etc, logs in /var/log, and every running process as a folder in /proc/PID.
  • /proc/PID/status, fd, limits, environ and cwd show what the process really has, not what the config says.

Permissions, users and sudo

Files, permissions and disk

Every file has an owner, a group and nine bits: read, write and execute for user, group and other. Each triple is one octal digit.

r is 4, w is 2, x is 1. The kernel checks user, then group, then other, and stops at the first match.
ModeTypical use
644 / 755Ordinary file / directory or executable
640, 600Secrets: group-readable, or owner only (SSH keys must be 600)
1777 (drwxrwxrwt)/tmp: anyone writes, only the owner deletes
x on a directoryPermission to enter it. Without it, files inside are unreachable.

sudo runs one command as root if /etc/sudoers.d allows it. Here deploy may run two commands, and root is what reveals the process name:

Rule: run the service as its own user, never root, and fix "Permission denied" with ownership or a group, not chmod 777.

File descriptors, redirection and pipes

Files, permissions and disk

A file descriptor is a small integer naming something the process has open: a file, a pipe or a socket. 0, 1 and 2 are stdin, stdout and stderr.

A pipe connects one command's fd 1 to the next command's fd 0. Errors on fd 2 skip the pipe.
  • > file 2>&1 sends both streams to one file. Order matters: 2>&1 > file does not.
  • A pipeline's exit code is the last command's. Scripts want set -o pipefail.

Too many open files

Files, permissions and disk

Every socket and file costs one descriptor, and each process has a limit. A connection leak ends as EMFILE, and the service stops accepting.

  • 61, not 64: fds 0, 1 and 2 were already taken.
  • Check /proc/PID/limits, not ulimit -n in your shell: a service gets its limit from its unit file (LimitNOFILE). Many servers default to 1024, far below this container.
  • If the fd count climbs steadily, raising the limit only delays the outage. Find the leak.

Disk full: df, du, inodes, deleted files

Files, permissions and disk

df asks the filesystem how full it is. du adds up the files it can see. When they disagree, a deleted file is still open.

  • rm removes the name. The space returns when the last process closes the file, so restart it or truncate through /proc/PID/fd/N.
  • To empty a live log, truncate it (: > app.log) instead of deleting it.

The other surprise is inodes: one per file, with a fixed count on many filesystems. /spool here has 64.

Order: "No space left on device" means df -h, then df -i, then du -sh /var/log/*, then lsof +L1.

Memory and services

Part 3 of 6 · what the kernel does with RAM, and how a service is kept running

free, page cache and swap

Memory and services

Linux uses spare RAM to cache file contents and gives it back on demand. Read available, not free.

FieldMeaning
freeUsed by nothing at all. Low on a healthy server.
buff/cachePage cache: file data kept in RAM, reclaimable
availableWhat a new process could get without swapping: free plus reclaimable cache
si / so in vmstat 1Pages swapped in and out per second. Steadily non-zero means RAM is short and latency suffers.
r / b in vmstat 1Tasks runnable / blocked on I/O: the two halves of load average

Container caveat: free and top here report the whole Docker VM. A container's own limit and usage are in /sys/fs/cgroup/memory.max and memory.current.

The OOM killer

Memory and services

When memory runs out, on the host or inside a container's limit, the kernel picks a large process and sends SIGKILL. The container was given a 96 MB limit for this run.

  • No traceback and no log line from the app: the shell prints "Killed" and the exit code is 137. The evidence is in the kernel log (dmesg -T | grep -i oom, or journalctl -k), which this container may not read.
  • docker inspect reported OOMKilled=true for this container. Kubernetes shows the same as OOMKilled.
  • Fix the memory use or the limit. Swap only turns a fast death into a slow one.

systemd units and systemctl

Memory and services

On a real server systemd is PID 1: it starts the service, restarts it, applies limits and collects its output. The containers have no systemd, so this chapter was not run for this page.

CommandDoes
systemctl daemon-reloadRe-read unit files after editing one
systemctl enable --now bankStart now and at every boot
systemctl status bankState, main PID, last log lines, last exit code
systemctl restart bankSIGTERM, wait up to TimeoutStopSec, SIGKILL, start
journalctl -u bank -fFollow the service's stdout and stderr
journalctl -u bank --since "10 min ago" -p errRecent errors only
  • EnvironmentFile holds plain KEY=value lines, readable by root and the service group only (the 640 file above).
  • The service does not see your shell's environment or ulimit. "Works when I run it by hand" is usually that.

Logs and rotation

Memory and services

A service writes either to stdout (journald or the container runtime keeps it) or to a file under /var/log, which must be rotated or it fills the disk.

  • copytruncate copies then empties the file, so the app keeps its open descriptor. Without it the app must reopen its log, or it writes to a deleted file.
  • Useful readers: tail -f, less +F, grep -c ERROR, zgrep for the compressed ones.

Network model and TCP

Part 4 of 6 · addresses, ports, and what a connection goes through

The layers a request crosses

Network model and TCP

Each layer wraps the one above and solves one problem. Debugging is finding the lowest layer that is broken.

Down the stack on the client, across routers at the IP layer, up the stack on the server.
LayerQuestionTool
ApplicationDoes it answer correctly?curl -v, dig
TCPDoes the port accept a connection?nc -zv, ss
IPCan packets reach the host?ping, traceroute, ip route
LinkIs the interface up?ip -br addr

IP addresses, CIDR, ports and sockets

Network model and TCP

An IPv4 address is 32 bits. /N says how many leading bits name the network, and the rest name hosts inside it.

RangeAddressesUse
10.0.0.0/8about 16.7 millionPrivate: large networks, cloud VPCs
172.16.0.0/12about 1 millionPrivate: Docker's default range sits here
192.168.0.0/1665,536Private: home and office
127.0.0.0/8Loopback: this machine only
169.254.0.0/16Link-local: cloud metadata endpoints
/24, /32256, 1A typical subnet, a single host
  • Private addresses are not routed on the internet. They reach it through NAT, which is why the server sees one shared address.
  • A connection is the 4-tuple (source IP, source port, destination IP, destination port). The client's port is picked from the ephemeral range, 32768 to 60999 here.
  • Ports below 1024 need root or a capability, which is why apps listen on 8080 behind a proxy on 443.

localhost versus 0.0.0.0

Network model and TCP

A listener is bound to an address as well as a port. Bound to 127.0.0.1, it only exists on the loopback interface.

0.0.0.0 means every interface, loopback included.
  • First check for "works on the box, not from outside": the Local Address column of ss -ltn.
  • The same bug inside a container: the app binds 127.0.0.1, so the published port reaches nothing.
  • Binding 127.0.0.1 on purpose is right for a database or admin port that only local processes should reach.

TCP handshake and teardown

Network model and TCP

Three packets open a connection, so a new connection costs one round trip before any data. Each side closes its own direction.

Open: the kernel completes this before the application's accept ever runs.
Close: the side that closes first holds the port pair in TIME-WAIT for a minute on Linux.

The same exchange, captured with tcpdump on loopback for one curl localhost:8080/health:

  • Flags: S SYN, . ACK, P data pushed, F FIN, R reset.
  • The first three lines are the handshake, the last three the teardown. Here the server's FIN and ACK travel in one packet.

Connection states, backlog and keep-alive

Network model and TCP

ss -tan lists every TCP socket with its state. Three states cover most of what you will see.

StateMeaningTrouble sign
LISTENWaiting for connections. Send-Q is the backlog size, Recv-Q the connections waiting for accept.Recv-Q near Send-Q: the app accepts too slowly
ESTABOpen connectionThe count only grows: a leak
TIME-WAITClosed by this side, port pair parkedTens of thousands on a client: it opens a connection per request
CLOSE-WAITPeer closed, this app has notAny that linger: the app forgot to close
  • Backlog is the smaller of what the app passes to listen() (5 for Python's http.server) and net.core.somaxconn (4096 here). When it is full, new clients see timeouts.
  • TCP keep-alive is off unless the app sets SO_KEEPALIVE, and the default first probe is after two hours (tcp_keepalive_time = 7200). Load balancers and NAT drop idle connections far sooner, often within minutes.
  • So set every timeout yourself: connect, read, and a pool idle time shorter than the load balancer's.

Refused, timeout or reset

Network model and TCP

The three failures look alike in an error log and point at different culprits.

ErrorOn the wireUsual causeSpeed
Connection refusedSYN answered by RSTHost is up, nothing listens on that address and port: process down, wrong port, bound to localhostInstant
TimeoutSYN gets no answerPackets dropped: firewall, security group, wrong IP, host down, full backlogAs long as the client waits
Connection resetRST on an open connectionPeer crashed or closed abruptly, or a proxy forgot an idle connectionInstant, mid-request

Reproduced from client-1: nothing listens on 9999, an iptables DROP rule covers 8443, and a small server on 9100 closes every connection with RST.

  • This curl (7.88) words a refusal as "Couldn't connect" with exit code 7. nc names it.
  • Without --connect-timeout the kernel retries the SYN 6 times with doubling waits, about two minutes. Always set a connect timeout.
  • Refused proves the host is reachable. Timeout proves nothing about the app.

DNS, HTTP and TLS

Part 5 of 6 · from a name to an encrypted request

How a name is resolved

DNS, HTTP and TLS

The application asks a local stub, the stub asks one recursive resolver, and the resolver walks the hierarchy and caches every answer.

Only the first lookup walks the whole path. Until the TTL expires, the resolver answers from memory.

Records, TTL and the local files

DNS, HTTP and TLS

TypeMaps a name toSeen here
A / AAAAIPv4 / IPv6 address104.20.23.154
CNAMEAnother namewww.wikipedia.org to dyna.wikimedia.org.
NSThe zone's authoritative servershera.ns.cloudflare.com.
MXMail servers, with priority0 . (accepts no mail)
TXTFree text: SPF, domain verification"v=spf1 -all"
PTRAn address back to a name8.8.8.8 to dns.google.
SRVHost and port of a serviceNot queried here
  • files dns: /etc/hosts wins over DNS. dig ignores it, getent hosts and your app do not.
  • 127.0.0.11 is Docker's built-in resolver, which is how web-1 resolves at all. On a server it is the VPC or a local caching resolver.
  • A record change takes up to one TTL to reach everyone, so lower the TTL before a migration, not during it.
  • Long-lived processes often cache an address forever. After a failover, the name is right and the app is still wrong.

Reading dig

DNS, HTTP and TLS

FieldRead it as
status: NOERRORThe name exists. NXDOMAIN (returned here for nosuch.example.com): it does not. SERVFAIL: the resolver could not get an answer.
flags: qr rd raA response, recursion asked for and available. aa would mean it came straight from the authoritative server.
ANSWER: 2Two A records: clients pick one, a simple form of load spreading
377Seconds this answer may still be cached
SERVERWho answered. Add @8.8.8.8 to ask a different resolver and compare.
Query timeSlow here means slow for every new connection

Shortcuts: dig +short name for just the value, dig name MX for another type, dig -x 8.8.8.8 for reverse.

HTTP through curl -v

DNS, HTTP and TLS

An HTTP/1.1 exchange is text over the TCP connection: a request line, headers, a blank line, an optional body, and the same shape back. In curl -v, * is curl talking, > is sent, < is received.

FamilyMeaningWho fixes it
2xxWorked: 200, 201 created, 204 no body
3xxLook elsewhere: 301, 302, 304 not modifiedClient follows
4xxThe request is wrong: 400, 401, 403, 404, 409, 429The caller
5xxThe server failed: 500, then 502, 503, 504 from a proxy in frontThe service owner
  • HTTP/1.1 keeps the connection open by default (keep-alive), one request at a time per connection. Given two URLs, curl printed Re-using existing connection #0 for the second: no new handshake, which is why clients pool connections.
  • HTTP/2 multiplexes many requests as streams on one connection, with binary framing and compressed headers. It is negotiated inside the TLS handshake (ALPN).
  • 502: the proxy could not get a valid answer from the app. 504: the app did not answer in time. Both send you to the app's host, not the proxy.

The TLS handshake

DNS, HTTP and TLS

TLS gives the client proof of who the server is, and both sides a shared key. TLS 1.3 does it in one round trip after the TCP handshake.

SNI names the site the client wants, so one address can serve many certificates.
  • (OUT) and (IN) lines are the diagram's arrows, in order.
  • CAfile is the trust store the chain is checked against. A minimal container image without ca-certificates fails every HTTPS call.
  • The four lines to read when TLS fails: subject, expire date, subjectAltName, issuer.

Certificates, chains and errors

DNS, HTTP and TLS

A certificate binds a public key to names, signed by an issuer. The client follows issuers upward until it reaches a root it already trusts.

The server must send the leaf and every intermediate. openssl s_client -connect host:443 -servername host prints the chain a server really sends.

The errors below were reproduced against the bank API served over TLS on web-1 with self-signed certificates made by openssl. The last row was not reproduced here.

curl saysCauseFix
(60) SSL certificate problem: self-signed certificateNo trusted issuer signed itTrust that CA explicitly (--cacert), or use a real one
(60) SSL certificate problem: certificate has expiredToday is past notAfterRenew, automate renewal, alert on days left
(60) SSL: no alternative certificate subject name matches target host name '172.19.0.2'Called by IP or another name than the certificate listsCall the listed name, or reissue with that name
(35) ... SSL routines::wrong version numberhttps:// to a port that speaks plain HTTPRight scheme or port
unable to get local issuer certificate (not reproduced)Server omits an intermediate, or the client has no trust storeServe the full chain, install ca-certificates

Trap: curl -k and verify=False make the error go away by removing the protection. Use them to diagnose, never to ship.

Debugging toolkit

Part 6 of 6 · one small real example per tool, then the order to use them in

Who listens, who is connected: ss and lsof

Debugging toolkit

ss -ltnp answers "is anything listening on this port, on which address, and which process?". The flags: listening, TCP, numeric, process.

  • "Address already in use" on start: ss -ltnp names the process holding the port.
  • lsof -nP -p PID lists everything one process has open: files, logs and each socket with its peer.

Where the time goes: curl -w

Debugging toolkit

curl -w prints a timestamp at the end of each phase, measured from the start. The variables are the node names below, written as %{time_connect}.

A slow request is slow in one of five places, and each has a different owner.
  • Here: DNS 3 ms (cached), TCP 24 ms, TLS 34 ms, server 32 ms, body under 1 ms. Two thirds of the request was connection setup, which is the case for connection reuse.
  • Large connect: distance or packet loss. Large gap before first byte: the application or its database.

Can I reach it: nc, ping, traceroute

Debugging toolkit

nc -zv host port tests exactly what a client needs, a TCP connection to that port. ping and traceroute test the IP layer below it.

  • A failed ping proves little: many networks drop ICMP while TCP works. A successful nc is the test that counts.
  • traceroute and mtr list the routers on the path and where loss starts. Behind Docker's NAT only the gateway shows, and traceroute -n example.com printed * for every later hop.
  • nc also speaks: piping a hand-typed GET /health HTTP/1.1 into nc web-1 8080 returned the same 200 response as curl.
  • For anything stranger, tcpdump -i any -nn 'tcp port 8080' shows the packets themselves, as in the handshake chapter. It needs root.

The service is unreachable: what to check

Debugging toolkit

Work up the layers from the client, and let the kind of failure choose the branch.

Each answer rules out everything below it, so no step is repeated.

Interview point: say which layer each check rules out. "Refused, so the host is up and the firewall is open: I look at the process and its bind address" is the answer that shows the model.

Cheat sheet

Debugging toolkit

QuestionCommand
What is running, and under whom?ps -eo pid,ppid,user,stat,rss,etime,cmd
Why did it exit?echo $?: 137 SIGKILL (often OOM), 143 SIGTERM, 127 not found, 126 not executable
Is the box overloaded?uptime against nproc, then top, vmstat 1
Is memory short?free -h (available), dmesg -T | grep -i oom
Is the disk full?df -h, df -i, du -sh dir/*, lsof +L1
Is it out of descriptors?ls /proc/PID/fd | wc -l against /proc/PID/limits
Who listens on port 8080?ss -ltnp (sudo to see the process)
Can I open a TCP connection?nc -zv -w 3 host port
What does the name resolve to?dig +short name, getent hosts name
What does the server answer?curl -v url, curl -sS -o /dev/null -w "%{http_code}\n" url
What is wrong with the certificate?curl -v, openssl s_client -connect host:443 -servername host
Service state and logssystemctl status name, journalctl -u name -f

Back to Cloud and DevOps.