Linux System Administration Questions
Operating and maintaining Linux and Unix systems: filesystems and permissions, process and service management, package management and updates, shell and scripting, storage, and network configuration on the host. Covers day-to-day administration, troubleshooting, monitoring and tuning host resource usage (CPU, memory, swap, and I/O), and hardening of Linux servers that underpin most infrastructure. The Linux operator's core skill set.
A Linux host needs to serve millions of short-lived TCP connections per minute, and it's starting to fail under load: some connections are refused, others hang. Design the kernel-level tuning you'd apply to fix this, covering port exhaustion, connection-state cleanup, and backlog/queue limits. For each change, explain the trade-off and how you'd validate it before rolling it out to production.
Sample Answer
Direct answer
Serving millions of short-lived TCP connections per minute means the bottleneck usually isn't raw bandwidth, it's the kernel running out of ephemeral ports, spending too long cleaning up connection state, or hitting backlog queue limits before a connection ever gets accepted. I'd tune all three layers together: widen the local port range and reuse connections in the TIME_WAIT state faster to fight port exhaustion, tune timeouts so dead connection state gets cleaned up promptly, and raise backlog and queue limits so bursts of incoming connections aren't rejected before the application even sees them. Every change here needs to be validated under realistic load before it goes anywhere near production, since these are host-wide kernel settings, not per-application config.
Structured elaboration
Port exhaustion. Each outbound TCP connection from this host consumes one ephemeral (local) port for its duration; at very high connection rates with short-lived connections, the default ephemeral port range can be exhausted faster than closed connections free their ports back up.
net.ipv4.ip_local_port_range(default often32768 60999, roughly 28,000 ports): widening this to something like10000 65535roughly doubles the available pool, directly raising the ceiling on concurrent short-lived outbound connections.net.ipv4.tcp_tw_reuse = 1: allows the kernel to reuse a socket still in theTIME_WAITstate for a new outgoing connection when it's safe to do so (based on TCP timestamps), which matters because a closed connection doesn't free its port immediately, it lingers inTIME_WAITfor a configured period specifically to catch late-arriving packets from the old connection. Trade-off: it relies on TCP timestamps being enabled and consistent between hosts; it's safe for outbound (client-side) connections in the vast majority of real deployments, but the OLDER, more aggressivetcp_tw_recyclesetting (now removed from modern kernels) had known correctness problems behind network address translation (NAT) and should not be confused withtw_reuse, which is the current, safe option.
Connection-state cleanup. A large number of connections sitting in states like TIME_WAIT or FIN_WAIT consume kernel memory and, combined with port exhaustion above, slow down how fast the host can accept new connections.
net.ipv4.tcp_fin_timeout(default 60 seconds): how long a socket stays inFIN_WAIT2after the local side has sent its close; lowering it (to 15-30 seconds, for instance) frees that state faster under high churn, at the cost of a smaller safety margin for genuinely slow-closing legitimate connections.- Monitor
ss -sfor a summary count of sockets by state; a very largeTIME_WAITcount relative to established connections is the direct signal that this layer needs attention.
Backlog and queue limits. Before a connection is even accepted by the application, it sits in kernel-managed queues; if those queues are too small for the connection rate, the kernel drops or refuses new connection attempts even though the server has capacity to eventually handle them.
net.core.somaxconn: the maximum length of the queue of fully-established connections waiting to beaccept()ed by the application; the application's ownlisten()backlog argument is also capped by this value, so raising only one side without the other doesn't help.net.ipv4.tcp_max_syn_backlog: the maximum number of half-open (SYN received, handshake not yet complete) connections the kernel will track; too small a value under a burst of new connection attempts causes the kernel to start dropping SYN packets, which clients experience as connection hangs or, eventually, failures.- For a process handling extremely high connection rates across multiple worker processes or threads,
SO_REUSEPORTlets multiple processes each bind and listen on the same port with the kernel load-balancing incoming connections across them, avoiding a single accept-queue bottleneck concentrated on one process.
Validating each change before production: never ship a batch of sysctl changes as one undifferentiated blob. Change one parameter, or one tightly related group (port range plus tw_reuse, as one group; backlog settings as another), reproduce the connection-rate scenario in a load test against a staging host with production-like traffic shape, and confirm the specific symptom (refused connections, hangs) actually improves and that ss -s state counts move the way you expect, before rolling further. Because these are host-wide kernel settings applied via sysctl, a bad value affects every process on the host, not just the one you're trying to fix, so validate on a non-critical host first and roll out gradually (the same canary-then-fleet pattern used for any host-wide kernel change), with the ability to revert (sysctl -w changes are live but not persistent until written to /etc/sysctl.d/, so a revert during validation is just re-running the previous value, not a reboot).
Worked example
A host handling roughly 50,000 new short-lived connections per minute (about 830 per second) starts seeing intermittent connection refusals under load. ss -s shows over 40,000 sockets in TIME_WAIT, and the default ephemeral port range (32768-60999, about 28,000 ports) is smaller than the TIME_WAIT count alone, confirming port exhaustion as at least part of the problem, since ports tied up in TIME_WAIT aren't available for new outbound connections. Applying net.ipv4.ip_local_port_range = 10000 65535 (about 55,000 ports, roughly double) and net.ipv4.tcp_tw_reuse = 1 on a canary host, then re-running the same load pattern, drops the TIME_WAIT versus available-port ratio well below saturation and the connection refusals stop; net.core.somaxconn is separately raised from its default of 4096 to 8192 once monitoring during the same test shows the accept queue occasionally hitting its old ceiling during traffic bursts, confirmed by watching netstat -s | grep -i "listen queue" overflow counters before and after.
Trade-offs & pitfalls
- These are host-wide
sysctlsettings; a value tuned for one workload's connection pattern can have unintended effects on every other process sharing that host, which is exactly why gradual, monitored rollout matters more here than for an application-level config change. tcp_tw_reuseis safe for outbound connections under normal conditions but depends on TCP timestamps; don't reach for the deprecatedtcp_tw_recycleinstead, it has known breakage behind NAT and was removed from modern kernels for good reason.- Widening the ephemeral port range or backlog queues treats the symptom of high churn; if the underlying issue is that connections should be kept alive and reused (persistent connections, connection pooling) rather than opened fresh millions of times per minute, that's often a cheaper and more durable fix than kernel tuning alone.
You're responsible for optimizing NFS performance for a build farm that has many small file reads. What kernel-level and mount-option settings would you consider changing on the client and server to improve throughput and reduce latency? Explain trade-offs.
Sample Answer
Direct answer
For a build farm's small-file-read pattern, the dominant cost is METADATA round-trips (an open, a stat, a
close, for every tiny file) rather than raw data throughput, so the highest-leverage changes are lengthening
the client's attribute cache and, on NFS (Network File System, the standard protocol for sharing filesystems
over a network) version 4.1 or newer, using delegations so a client can serve repeated opens and reads from
its own local cache with zero server round-trips. Recommend NFSv4.1+ with delegations as the default for
this workload over tuning NFSv3 options alone, and that recommendation flips for a workload dominated by many
clients concurrently WRITING to the same files, where delegations mostly can't be granted and their benefit
disappears.
Structured elaboration, client and server, with trade-offs
Client-side mount options:
rsize/wsize(the read/write buffer size per RPC, remote procedure call, request): raised toward the
maximum the server and network support (commonly up to 1MiB on a modern NFSv4 setup over a fast LAN)
reduces the NUMBER of round-trips per file read. Trade-off: larger buffers cost more memory per
outstanding request, though for genuinely tiny files this knob matters far less than the metadata-focused
ones below.actimeo(attribute cache timeout, how long the client trusts its cached copy of a file's size,
modification time, and permissions before re-validating with the server): raised from the historical
few-second default to somewhere in the 60 to 600 second range for a read-mostly, rarely-changing source
tree, cutting the exact "stat every file" round-trip pattern build tools are notorious for. Trade-off: a
longeractimeomeans a change made on one client or the server takes longer to become visible elsewhere,
fine for source checked out once per build, dangerous for files multiple agents actively read and write
concurrently.nconnect(multiple TCP, Transmission Control Protocol, connections per mount, supported on modern Linux
NFS clients) spreads many small, latency-bound requests across several connections instead of serializing
them behind one connection's round-trip time, directly attacking the "many tiny requests, each paying full
round-trip latency" cost profile. Trade-off: more open connections and threads on both client and server,
a real resource cost across many build clients at once.- NFSv4.1+ delegations: the server grants a client exclusive or read-only authority over a file, letting
the client serve subsequent opens, reads, and closes from local cache with zero server round-trip until
the delegation is recalled, the single biggest win for a build farm's repeatedly-opened header and source
files. Trade-off: delegations are recalled the moment any other client wants conflicting access, so heavy
cross-client writes to the same files get little benefit and pay some delegation-management overhead for
nothing. noatimeon the client mount to stop every read from also generating a metadata-updating write (access
time) back to the server, a nearly free win with no real use case in a build farm.
Server-side and kernel-level:
nfsdthread count: a small-file-heavy workload generates a high RATE of quick operations, benefiting
from more concurrent server threads than a large-sequential-file workload needs, but too many relative to
the server's actual disk and CPU capacity just adds contention, tune against observed server saturation,
not blindly.- Backing storage latency matters far more here than for large sequential workloads: small-file metadata
operations are latency-bound (each pays a full seek or lookup cost), not throughput-bound, so an SSD
(solid-state drive) backed export changes the picture dramatically compared to spinning disk, where
no client-side tuning fixes a genuinely slow backing store. asyncversussyncexport options trade write-acknowledgment speed against durability (a crash under
asynccan silently lose acknowledged writes); this workload, described as read-heavy small-file reads,
benefits far less from this knob than the read-side changes above, since the win is specifically on the
write path.
Worked example
A build farm of 200 continuous integration (CI) agents each checks out roughly 500,000 files, typically
under 4KiB each, from one NFS server before every build. On a baseline NFSv3 mount with default 8KiB
rsize/wsize and a 3-second actimeo, every checkout re-validates metadata for essentially every file
against the server: even at a conservative 1ms per round-trip, 500,000 metadata round-trips alone is over
eight minutes of pure wait per agent before any file content transfers at all (this is a direct arithmetic
consequence of the stated file count and an assumed round-trip time, not a benchmark claim, the real number
on any given network will differ, but the SHAPE, metadata round-trip count scaling linearly with file
count, is the reproducible point). Moving to NFSv4.1 with delegations means the second and later agents to
touch an unchanged tree serve most of those lookups from a granted delegation with zero server round-trips,
and raising actimeo to 300 seconds for agents that don't hold a delegation cuts their re-validation rate
by roughly two orders of magnitude relative to the 3-second default, both changes attacking the same
bottleneck the baseline arithmetic identifies: round-trip COUNT, not raw data throughput.
Trade-offs and pitfalls
The most common wrong turn on this exact workload is tuning rsize/wsize upward and stopping there, that
only helps DATA throughput for large reads, while a build farm's actual bottleneck, as the arithmetic above
shows, is metadata round-trip count for many tiny files, which actimeo, delegations, and nconnect
address directly and rsize/wsize barely touch. Also, applying an aggressive actimeo to a tree that IS
actively modified by other build steps (generated artifacts, not just checked-out source) reintroduces real
staleness bugs, agents silently working from stale metadata about files other agents just wrote, so long
cache lifetimes belong specifically on the read-only, checked-out-once source tree, with shorter caching (or
a separate mount) kept for any shared, actively-written build-output directory.
Explain the purpose and typical contents of /etc/resolv.conf on Linux. Describe how the name resolution flow can involve glibc NSS, systemd-resolved, NetworkManager, and local caches like dnsmasq. How do you change DNS temporarily and persistently?
Sample Answer
Direct answer
/etc/resolv.conf tells the system's name resolution machinery which DNS servers to query and in what order, via nameserver lines, plus optional search domains to try appending to unqualified hostnames. On a modern Linux host that file is rarely hand-maintained directly: it is usually generated and kept in sync by whichever layer is actually managing DNS underneath, most commonly systemd-resolved (the DNS-resolving component of systemd, the init system and service manager most modern Linux distributions use; it runs its own local stub resolver, typically listening on 127.0.0.53, and often makes /etc/resolv.conf a symlink pointing at a file it generates) or NetworkManager, sometimes with dnsmasq in front as a small local caching layer.
The resolution flow, layer by layer
- An application calls a resolution function from glibc (the standard C library most Linux programs are built against), which consults NSS, Name Service Switch: a configurable dispatch mechanism (
/etc/nsswitch.conf) that decides, for a given lookup type, which sources to check and in what order. Thehosts:line in that file, something likehosts: files dns, is what makes/etc/hostsget checked before DNS at all, for every application on the system, without each program needing its own logic for that. - If DNS is reached, glibc's resolver reads
/etc/resolv.conffor which server(s) to query. - On a host running
systemd-resolved,/etc/resolv.confcommonly just points at127.0.0.53,systemd-resolved's own stub listener, rather than at the real upstream DNS servers directly.systemd-resolveditself holds the actual upstream server list (learned from DHCP, static configuration, or per-interface settings) and does its own caching, so the file glibc reads and the servers actually queried over the network are two different things on such a host. - NetworkManager, when it manages DNS, can either write
/etc/resolv.confdirectly with the servers it learned from DHCP or static configuration, or hand the job off tosystemd-resolved(a mode controlled by NetworkManager's owndns=setting), depending on how the distribution configured it. dnsmasq, where present, is a small lightweight resolver and DHCP server often used as an additional local caching layer in front of upstream DNS, either standalone or as NetworkManager's local caching backend on some distributions.
Changing DNS, temporarily versus persistently
- Temporary (until the next reconnect, reboot, or manager restart):
resolvectl dns eth0 1.1.1.1on asystemd-resolvedhost (the modern command;systemd-resolveis the older, now-deprecated name for essentially the same functionality).- Editing
/etc/resolv.confdirectly works immediately for any new resolution, but only until whatever manages that file (systemd-resolved, NetworkManager) next regenerates it and overwrites your edit, which can happen at any reconnect or restart with no warning.
- Persistent:
- Netplan (Ubuntu): add a
nameservers:block under the relevant interface in the YAML config, thennetplan apply. - NetworkManager:
nmcli con mod <connection-name> ipv4.dns "1.1.1.1 8.8.8.8"followed bynmcli con up <connection-name>to apply it. systemd-networkd: add aDNS=line under[Network]in the relevant.networkfile, thensystemctl restart systemd-networkd.
- Netplan (Ubuntu): add a
Trade-offs and pitfalls
- The most common confusion is editing
/etc/resolv.confby hand on a host runningsystemd-resolvedor NetworkManager, seeing it work, and then being surprised it reverts on its own later; check whether the file is a symlink (ls -l /etc/resolv.conf) before assuming a manual edit is safe or durable. resolvectl statusshows you the actual per-interface DNS configurationsystemd-resolvedis using, which can differ from what a barecat /etc/resolv.confshows when the stub resolver is in play; when DNS behavior looks wrong, checkresolvectl status, not just the file, or you can chase a mismatch that does not actually explain the resolver's real behavior.searchdomains inresolv.confcan cause surprising, hard-to-debug behavior where an unqualified hostname silently resolves against the wrong domain (or leaks an internal hostname query to an external DNS server it should never have reached), which is a real concern worth checking for on hosts that handle sensitive internal name lookups.
Describe the tcpdump command to capture only DNS (UDP port 53) traffic to/from host 10.1.1.5 on interface eth0, rotate captures to avoid filling disk (ring buffer), and explain how to interpret DNS transaction IDs and flags in the pcap.
Sample Answer
Direct answer
tcpdump -i eth0 -n 'udp port 53 and host 10.1.1.5' -w /var/log/dns_capture.pcap -C 100 -W 5
-n skips reverse DNS lookups on captured addresses (avoids the tool itself generating more DNS traffic while you are capturing DNS traffic, and speeds up display). The filter expression restricts capture to DNS traffic (UDP port 53) to or from the specific host. -w writes to a capture file instead of printing decoded packets to the terminal. -C 100 rotates to a new file every time the current one reaches 100 million bytes, and -W 5 caps the ring buffer at 5 files total, so the oldest file is overwritten once that limit is reached rather than filling the disk indefinitely; this produces dns_capture.pcap0 through dns_capture.pcap4 cycling in place, a fixed roughly-500-megabyte disk footprint instead of an unbounded one.
Reading the transaction ID and flags in the capture
Every DNS message carries a 16-bit transaction ID, chosen by the client on the query and echoed back unchanged by the server on the response, which is how a client matches a response to the query that triggered it, especially important over UDP, since UDP itself carries no connection state to associate the two automatically. Alongside the ID, the DNS header carries a small set of flags: QR (0 for query, 1 for response), Opcode (almost always standard query in practice), AA (authoritative answer, set when the responding server is authoritative for that zone rather than just relaying a cached answer), TC (truncated, meaning the response was too large for UDP and the client should retry over TCP), RD (recursion desired, set by the client to ask the server to chase the answer itself rather than just returning what it already has), RA (recursion available, set by the server to say it is willing to do that), and RCODE (the response status, 0 for no error, 3 for NXDOMAIN, meaning the name does not exist, among others).
tcpdump decodes DNS natively without needing a hex dump: running it live (or reading back the capture with tcpdump -r dns_capture.pcap0 -n) prints lines like:
12:00:01.123456 IP 10.1.1.5.54321 > 8.8.8.8.53: 34521+ A? example.com. (29)
12:00:01.145678 IP 8.8.8.8.53 > 10.1.1.5.54321: 34521 1/0/0 A 93.184.216.34 (45)
34521 is the transaction ID, matching between the query and response lines, confirming they belong to the same exchange. The + after the ID on the query line indicates recursion desired (RD) was set. 1/0/0 on the response means one answer record, zero authority records, zero additional records. For deeper inspection than tcpdump's compact one-line summaries give you, such as fully decoded flag bits or malformed packets, reading the same capture in a protocol-aware analyzer like tshark or Wireshark against the saved .pcap file is the practical next step, since the capture format itself is standard and portable between tools.
Trade-offs and pitfalls
- Forgetting
-non a busy host generates a meaningful amount of extra DNS traffic just fromtcpdump's own reverse-lookup attempts on every captured address, which is a self-inflicted noise source specifically counterproductive while debugging DNS itself. -Cand-Wbound disk usage but do not bound time: on a very high-traffic host, a 5-file, 100MB-each ring buffer can rotate through its entire history in minutes, so if you are trying to catch an intermittent issue that only happens every few hours, this configuration will have already overwritten the relevant capture by the time you go looking; size the ring buffer to the actual traffic rate and the window of time you need to retain, not an arbitrary round number.- A filter this specific (single host, single port) is good practice for keeping capture size manageable and signal-to-noise high, but if the actual problem turns out to involve a different DNS server or a client the filter excludes, you will see nothing at all and can mistake an overly narrow filter for "there is no DNS traffic happening," which is a different conclusion than the correct one.
- Running
tcpdumpwith-wrequires elevated privileges (typically root, or a capability grant likeCAP_NET_RAWon the binary) and a filesystem location with enough free space for the configured ring buffer; on a host with tight partition sizing, writing the capture to/var/logalongside application logs risks filling that partition and affecting unrelated services, so a dedicated capture directory or partition is worth considering before running this on production infrastructure.
Explain the difference between DNAT and SNAT in iptables and give example commands: one for port forwarding (DNAT) and one for outbound source NAT (SNAT/MASQUERADE). Describe how conntrack maintains translations for returning traffic.
Sample Answer
Direct answer
DNAT rewrites a packet's destination address or port, applied at the PREROUTING hook before the kernel makes its routing decision, and is how you implement port forwarding or expose an internal service behind a single public address. SNAT rewrites a packet's source address, applied at POSTROUTING after the routing decision, and is how outbound traffic from a private network gets a routable source address before it leaves toward the internet. Neither would work for anything beyond a single packet without conntrack, the kernel's connection tracking subsystem, which remembers the translation it applied to the first packet of a flow so every subsequent packet in both directions gets translated consistently without needing a matching rule written for the return path.
DNAT: rewriting the destination
Forwarding external traffic on port 8080 to an internal host's port 80:
iptables -t nat -A PREROUTING -p tcp --dport 8080 -j DNAT --to-destination 10.0.0.5:80
This runs in PREROUTING, before the kernel decides where to route the packet, which is exactly why DNAT can work for traffic genuinely destined elsewhere: by the time routing happens, the destination has already been rewritten to the real internal target, so the kernel routes it there instead of to whatever the original destination was.
SNAT and MASQUERADE: rewriting the source
Giving an internal subnet a specific, static public source address on the way out:
iptables -t nat -A POSTROUTING -s 10.0.0.0/24 -o eth0 -j SNAT --to-source 203.0.113.10
or, when the outgoing interface's address is dynamic (DHCP-assigned, or simply not worth hardcoding), letting the kernel pick it up automatically each time:
iptables -t nat -A POSTROUTING -s 10.0.0.0/24 -o eth0 -j MASQUERADE
MASQUERADE is functionally SNAT with the source address determined automatically from whatever address the outgoing interface currently has, rather than a fixed one you specify; this is exactly the mechanism Docker itself uses by default to let containers on an internal bridge network reach the outside world through the host's real address.
How conntrack makes the return path work without a second rule
Every flow through netfilter gets an entry in the connection tracking table (visible with conntrack -L from the conntrack-tools package, or by reading /proc/net/nf_conntrack directly), recording the original tuple (protocol, source and destination address and port) and whatever NAT translation was applied to it. When a reply packet comes back, the kernel checks conntrack, recognizes it as belonging to an already-tracked flow, and automatically applies the inverse translation, un-DNATing a reply back to the original external client, or un-SNATing a reply back to the correct internal host, without you ever writing a rule for the return direction. This is also why DNAT and SNAT rules are only ever written for one direction (PREROUTING for DNAT, POSTROUTING for SNAT): the reverse translation on the way back is conntrack's job automatically, not something you configure separately.
Trade-offs and pitfalls
- Writing a matching rule for the "return" direction yourself (attempting to DNAT the reply traffic explicitly) is a common mistake for people new to NAT; it is not just unnecessary, it can actively conflict with what conntrack is already doing automatically and produce broken, asymmetric-looking connections.
MASQUERADEcosts a small amount of extra work per packet compared toSNATwith a fixed address, since the kernel has to look up the outgoing interface's current address on every relevant packet rather than using a value baked into the rule; on a genuinely static-IP outbound interface,SNAT --to-sourceis marginally more efficient, though the difference is rarely significant at typical traffic volumes.- If the conntrack table fills up (a real operational failure mode on a busy NAT gateway handling many concurrent short-lived connections), new connections can be silently dropped rather than translated at all;
sysctl net.netfilter.nf_conntrack_maxand the current entry count (conntrack -C) are worth monitoring on any host doing NAT at meaningful scale, not just assuming the default table size is enough. - DNAT changes the destination before the routing decision, which means the routing table then has to actually be able to reach the new destination; a DNAT rule that points at an address the box has no route to fails silently from the client's perspective (the connection just does not complete), which is worth checking with
ip route get <new-destination>as a first diagnostic step.
Unlock Full Question Bank
Get access to all 14 Linux System Administration interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.