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
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 command | Effect |
|---|---|
cmd &, jobs | Start in the background, list this shell's jobs |
| Ctrl+C, Ctrl+Z | SIGINT to the foreground job, or stop it (SIGTSTP) |
fg %1, bg %1 | Resume 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
A signal is a small asynchronous message to a process. Deploys and orchestrators stop a service with SIGTERM, wait, then send SIGKILL.
| Signal | Number | Sent by | Can be handled? |
|---|---|---|---|
| SIGINT | 2 | Ctrl+C | Yes |
| SIGTERM | 15 | kill PID, systemd, Docker, Kubernetes | Yes: finish work, then exit |
| SIGKILL | 9 | kill -9, the OOM killer | No: the kernel removes the process |
| SIGHUP | 1 | Terminal closed, kill -HUP | Yes: often "reload config" |
| SIGSTOP / SIGCONT | 19 / 18 | kill -STOP, kill -CONT | STOP 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
Both are about which of parent and child exits first.
- 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 --initadds a real init.
top, load average and nice
Read the header first, then the columns. htop shows the same fields with colours.
| Field | Meaning | Worry when |
|---|---|---|
| load average | Tasks running, waiting for a CPU or stuck in disk I/O: 1, 5 and 15 minute averages | It stays above the core count (nproc printed 10 here) |
us / sy / wa / st | CPU time in your code, in the kernel, waiting for disk, stolen by the hypervisor | wa high: disk. st high: noisy neighbour. |
| %CPU | Percent of one core | A threaded process can show 400 |
| VIRT | Address space reserved (KiB) | Rarely: it is not memory in use |
| RES | Physical memory held now (KiB) | It grows without bound: a leak |
| NI | Nice 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
Five places answer most "where is it?" questions on a server.
/etc, logs in /var/log, and every running process as a folder in /proc/PID./proc/PID/status,fd,limits,environandcwdshow what the process really has, not what the config says.
Permissions, users and sudo
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.
| Mode | Typical use |
|---|---|
| 644 / 755 | Ordinary file / directory or executable |
| 640, 600 | Secrets: group-readable, or owner only (SSH keys must be 600) |
1777 (drwxrwxrwt) | /tmp: anyone writes, only the owner deletes |
x on a directory | Permission 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
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.
> file 2>&1sends both streams to one file. Order matters:2>&1 > filedoes not.- A pipeline's exit code is the last command's. Scripts want
set -o pipefail.
Too many open files
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, notulimit -nin 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
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.
rmremoves 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
Linux uses spare RAM to cache file contents and gives it back on demand. Read available, not free.
| Field | Meaning |
|---|---|
free | Used by nothing at all. Low on a healthy server. |
buff/cache | Page cache: file data kept in RAM, reclaimable |
available | What a new process could get without swapping: free plus reclaimable cache |
si / so in vmstat 1 | Pages swapped in and out per second. Steadily non-zero means RAM is short and latency suffers. |
r / b in vmstat 1 | Tasks 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
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, orjournalctl -k), which this container may not read. docker inspectreportedOOMKilled=truefor this container. Kubernetes shows the same asOOMKilled.- Fix the memory use or the limit. Swap only turns a fast death into a slow one.
systemd units and systemctl
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.
| Command | Does |
|---|---|
systemctl daemon-reload | Re-read unit files after editing one |
systemctl enable --now bank | Start now and at every boot |
systemctl status bank | State, main PID, last log lines, last exit code |
systemctl restart bank | SIGTERM, wait up to TimeoutStopSec, SIGKILL, start |
journalctl -u bank -f | Follow the service's stdout and stderr |
journalctl -u bank --since "10 min ago" -p err | Recent errors only |
EnvironmentFileholds plainKEY=valuelines, 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
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.
copytruncatecopies 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,zgrepfor the compressed ones.
Network model and TCP
Part 4 of 6 · addresses, ports, and what a connection goes through
The layers a request crosses
Each layer wraps the one above and solves one problem. Debugging is finding the lowest layer that is broken.
| Layer | Question | Tool |
|---|---|---|
| Application | Does it answer correctly? | curl -v, dig |
| TCP | Does the port accept a connection? | nc -zv, ss |
| IP | Can packets reach the host? | ping, traceroute, ip route |
| Link | Is the interface up? | ip -br addr |
IP addresses, CIDR, ports and sockets
An IPv4 address is 32 bits. /N says how many leading bits name the network, and the rest name hosts inside it.
| Range | Addresses | Use |
|---|---|---|
10.0.0.0/8 | about 16.7 million | Private: large networks, cloud VPCs |
172.16.0.0/12 | about 1 million | Private: Docker's default range sits here |
192.168.0.0/16 | 65,536 | Private: home and office |
127.0.0.0/8 | Loopback: this machine only | |
169.254.0.0/16 | Link-local: cloud metadata endpoints | |
/24, /32 | 256, 1 | A 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
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.1on purpose is right for a database or admin port that only local processes should reach.
TCP handshake and teardown
Three packets open a connection, so a new connection costs one round trip before any data. Each side closes its own direction.
accept ever runs.The same exchange, captured with tcpdump on loopback for one curl localhost:8080/health:
- Flags:
SSYN,.ACK,Pdata pushed,FFIN,Rreset. - 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
ss -tan lists every TCP socket with its state. Three states cover most of what you will see.
| State | Meaning | Trouble sign |
|---|---|---|
| LISTEN | Waiting 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 |
| ESTAB | Open connection | The count only grows: a leak |
| TIME-WAIT | Closed by this side, port pair parked | Tens of thousands on a client: it opens a connection per request |
| CLOSE-WAIT | Peer closed, this app has not | Any that linger: the app forgot to close |
- Backlog is the smaller of what the app passes to
listen()(5 for Python'shttp.server) andnet.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
The three failures look alike in an error log and point at different culprits.
| Error | On the wire | Usual cause | Speed |
|---|---|---|---|
| Connection refused | SYN answered by RST | Host is up, nothing listens on that address and port: process down, wrong port, bound to localhost | Instant |
| Timeout | SYN gets no answer | Packets dropped: firewall, security group, wrong IP, host down, full backlog | As long as the client waits |
| Connection reset | RST on an open connection | Peer crashed or closed abruptly, or a proxy forgot an idle connection | Instant, 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.
ncnames it. - Without
--connect-timeoutthe 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
The application asks a local stub, the stub asks one recursive resolver, and the resolver walks the hierarchy and caches every answer.
Records, TTL and the local files
| Type | Maps a name to | Seen here |
|---|---|---|
| A / AAAA | IPv4 / IPv6 address | 104.20.23.154 |
| CNAME | Another name | www.wikipedia.org to dyna.wikimedia.org. |
| NS | The zone's authoritative servers | hera.ns.cloudflare.com. |
| MX | Mail servers, with priority | 0 . (accepts no mail) |
| TXT | Free text: SPF, domain verification | "v=spf1 -all" |
| PTR | An address back to a name | 8.8.8.8 to dns.google. |
| SRV | Host and port of a service | Not queried here |
files dns:/etc/hostswins over DNS.digignores it,getent hostsand your app do not.127.0.0.11is Docker's built-in resolver, which is howweb-1resolves 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
| Field | Read it as |
|---|---|
status: NOERROR | The name exists. NXDOMAIN (returned here for nosuch.example.com): it does not. SERVFAIL: the resolver could not get an answer. |
flags: qr rd ra | A response, recursion asked for and available. aa would mean it came straight from the authoritative server. |
ANSWER: 2 | Two A records: clients pick one, a simple form of load spreading |
377 | Seconds this answer may still be cached |
SERVER | Who answered. Add @8.8.8.8 to ask a different resolver and compare. |
Query time | Slow 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
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.
| Family | Meaning | Who fixes it |
|---|---|---|
| 2xx | Worked: 200, 201 created, 204 no body | |
| 3xx | Look elsewhere: 301, 302, 304 not modified | Client follows |
| 4xx | The request is wrong: 400, 401, 403, 404, 409, 429 | The caller |
| 5xx | The server failed: 500, then 502, 503, 504 from a proxy in front | The 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 #0for 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
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.
(OUT)and(IN)lines are the diagram's arrows, in order.CAfileis the trust store the chain is checked against. A minimal container image withoutca-certificatesfails every HTTPS call.- The four lines to read when TLS fails: subject, expire date, subjectAltName, issuer.
Certificates, chains and errors
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.
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 says | Cause | Fix |
|---|---|---|
(60) SSL certificate problem: self-signed certificate | No trusted issuer signed it | Trust that CA explicitly (--cacert), or use a real one |
(60) SSL certificate problem: certificate has expired | Today is past notAfter | Renew, 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 lists | Call the listed name, or reissue with that name |
(35) ... SSL routines::wrong version number | https:// to a port that speaks plain HTTP | Right scheme or port |
unable to get local issuer certificate (not reproduced) | Server omits an intermediate, or the client has no trust store | Serve 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
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 -ltnpnames the process holding the port. lsof -nP -p PIDlists everything one process has open: files, logs and each socket with its peer.
Where the time goes: curl -w
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}.
- 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
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
pingproves little: many networks drop ICMP while TCP works. A successfulncis the test that counts. tracerouteandmtrlist the routers on the path and where loss starts. Behind Docker's NAT only the gateway shows, andtraceroute -n example.comprinted*for every later hop.ncalso speaks: piping a hand-typedGET /health HTTP/1.1intonc web-1 8080returned 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
Work up the layers from the client, and let the kind of failure choose the branch.
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
| Question | Command |
|---|---|
| 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 logs | systemctl status name, journalctl -u name -f |
Back to Cloud and DevOps.