PrepStack › DevOps & Cloud › Linux & Shell
Linux & Shell interview cheat sheet
Filesystem, permissions, processes, signals, pipes, text tools, networking and troubleshooting
Linux questions show up in DevOps, SRE, backend and even frontend interviews. Interviewers check that you understand how the system works (inodes, permissions, processes, signals, file descriptors) and that you can debug a real box with the right commands: disk full, high CPU, port already in use, a slow server. Read the 15-minute revision first, then practise the troubleshooting scenarios out loud as if you were sharing your terminal.
15-minute revision
- Kernel manages hardware, memory, processes and syscalls. The shell (bash, zsh) is a user program that reads commands. A distro is kernel + userland + package manager + defaults (Ubuntu, RHEL, Debian, Alpine).
- Boot: firmware (BIOS/UEFI) → bootloader (GRUB) → kernel + initramfs → PID 1 (
systemd) → targets and services. - Everything is a file: regular files, directories, devices (
/dev/sda), pipes, sockets and kernel views (/proc,/sys) all use the same open/read/write API. - An inode holds metadata and block pointers, not the name. A hard link is another name for the same inode; a symlink is a small file that stores a path and can dangle.
- Permissions:
r=4 w=2 x=1for user/group/other.chmod 755=rwxr-xr-x. New file mode =666 & ~umask(dirs777 & ~umask), so umask022gives644/755. - setuid runs a binary as its owner (
passwd), setgid on a dir makes new files inherit the group, the sticky bit on/tmplets only owners delete their files. - Every process has a PID and PPID. New processes are made by
fork()(copy) thenexec()(replace image). Zombie = exited but not reaped by parent; orphan = parent died, adopted by PID 1 / a subreaper. SIGTERM(15) asks politely and can be trapped;SIGKILL(9) andSIGSTOPcannot be caught.SIGHUP(1) = terminal closed, often reused to reload config.killsendsSIGTERMby default.- fd 0 = stdin, 1 = stdout, 2 = stderr.
cmd > f 2>&1sends both tof;2>&1 > fdoes not (order matters).>/dev/nulldiscards. - A pipe connects stdout of one process to stdin of the next; all stages run concurrently.
$?is the last command's exit code;set -o pipefailmakes a pipeline fail if any stage fails. - Text toolkit:
grep(filter lines),sed(edit stream),awk(columns and logic),cut,sort | uniq -c | sort -rn(top-N),wc -l,xargs(args from stdin),find,tail -f. systemctl start|stop|restart|enable|status <unit>; logs withjournalctl -u <unit> -f.enable= start at boot;start= start now.- Load average is the 1/5/15-minute average of runnable + uninterruptible (D state) tasks. Compare it to the CPU count; on Linux high load can mean I/O wait, not just CPU.
free -h: look at available, not free. Linux uses spare RAM for page cache. When memory runs out the OOM killer kills the process with the highestoom_score.- Disk full?
df -h(space) anddf -i(inodes), thendu -sh * | sort -h. Space not freed afterrm? A process still holds the deleted file open:lsof +L1. - Port in use?
ss -ltnp | grep :8080orlsof -i :8080. Scripts should start with#!/usr/bin/env bashandset -euo pipefail, and always quote variables:"$var".
Foundations: kernel, boot & filesystem
Kernel vs shell vs distro (and package managers)
The kernel runs the hardware, the shell is just a program you type into, and a distro packages both with tools and a package manager.
- The kernel is the core of the OS. It runs in privileged mode and manages CPU scheduling, memory, devices, filesystems and networking. Programs reach it through system calls (
open,read,fork,execve). - User space is everything else: the shell, coreutils (
ls,cp), daemons and your apps. A bug in user space crashes one process; a kernel bug can crash the machine. - The shell is a command interpreter: it parses your line, expands variables and globs, sets up redirections and pipes, and then forks and execs programs. bash, zsh, sh (dash on Debian/Ubuntu) and fish are shells.
- A distribution bundles the Linux kernel, GNU or BusyBox userland, an init system, a package manager and default configs. Examples: Debian/Ubuntu (
apt,.deb), RHEL/Fedora/Rocky (dnf,.rpm), Alpine (apk, musl libc, popular in containers). - Package managers resolve dependencies, verify signatures and track installed files. Low-level tools (
dpkg,rpm) install a single file without dependency resolution.
Interview questions
- What is the difference between the kernel and the shell?
- What does a system call do, and how can you see them?
- Why is
cda shell builtin and not a program?
Boot process: firmware → GRUB → kernel → systemd
Firmware finds a bootloader, the bootloader loads the kernel and initramfs, the kernel mounts root and starts PID 1, and systemd brings up services.
- BIOS (legacy) runs POST and loads the first 512-byte sector (MBR). UEFI reads a FAT-formatted EFI System Partition and runs a
.efibootloader directly; it supports GPT disks over 2 TB and Secure Boot. - The bootloader (GRUB2, systemd-boot) shows a menu, loads the kernel image (
vmlinuz) and the initramfs into memory and passes the kernel command line (root=,quiet, ...). - The kernel decompresses itself, initialises CPU, memory and drivers, and unpacks the initramfs: a tiny root filesystem with the drivers and tools needed to find the real root (LVM, RAID, encryption).
- The real root filesystem is mounted and the kernel starts PID 1:
/sbin/init, which is systemd on almost all modern distros (SysV init and OpenRC still exist). - systemd reads unit files and starts services in parallel to reach the default target (
multi-user.targetfor servers,graphical.targetfor desktops). Targets replaced the old runlevels.
Interview questions
- Walk me through the Linux boot process.
- Difference between BIOS and UEFI?
- What is PID 1 and why is it special?
Filesystem hierarchy & “everything is a file”
One tree rooted at /; each top-level directory has a job, and devices, processes and kernel settings appear as files.
- There are no drive letters. Every disk is mounted somewhere in a single tree starting at
/. - Everything is a file: regular files, directories, block and character devices (
/dev/sda,/dev/null), named pipes, sockets and symlinks. The sameopen/read/write/closecalls work on all of them. /procand/sysare virtual filesystems created by the kernel in memory./proc/<pid>/shows each process;/proc/meminfo,/proc/cpuinfoshow system state;/sysexposes devices and drivers./tmpis for short-lived files (often atmpfsin RAM, cleared on reboot)./varholds data that changes: logs, caches, spools, databases.- File types appear as the first character of
ls -l:-file,ddir,lsymlink,cchar device,bblock device,ppipe,ssocket.
Interview questions
- What does “everything is a file” mean in Linux?
- What is
/procand is it on disk? - Difference between
/etc,/varand/usr?
Inodes, hard links & soft links
A directory maps names to inode numbers; a hard link is another name for an inode, a symlink is a separate file that stores a path.
- An inode stores file metadata: type, permissions, owner, size, timestamps (atime/mtime/ctime), link count and pointers to data blocks. It does not store the file name.
- A directory is a table of
name → inode numberentries.ls -ishows inode numbers;stat fileshows everything in the inode. - A hard link (
ln a b) adds another directory entry pointing at the same inode. Data is freed only when the link count reaches 0 and no process has the file open. - A symbolic (soft) link (
ln -s target link) is its own inode whose content is a path. It can cross filesystems and point to directories, but it breaks (dangles) if the target moves. - Filesystems have a fixed number of inodes. Millions of tiny files can exhaust them:
df -ishows 100% whiledf -hstill shows free space.
Interview questions
- What is an inode?
- Difference between a hard link and a soft link?
dfsays the disk has free space but you get “No space left on device”. Why?
Permissions, users & sudo
File permissions: rwx, octal, chmod, chown
Each file has an owner, a group and three rwx triplets (user, group, other) that are often written as octal digits.
ls -lshows-rwxr-x---: type, then user, group, other triplets. Digits:r=4,w=2,x=1, sorwx=7,r-x=5,r--=4.- On files: r = read content, w = modify content, x = execute. On directories: r = list names, w = create/delete/rename entries, x = enter (
cd) and access entries by name. - Deleting a file needs w + x on the directory, not write on the file itself.
chmod 640 f(octal) orchmod u+x,g-w,o= f(symbolic).chmod -Rrecurses.chown user:group fchanges owner and group (chownneeds root);chgrpchanges only the group.- The kernel checks one class only: if you are the owner, owner bits apply (even if group bits are more generous); else if in the group, group bits; else other. root bypasses most checks.
Interview questions
- What do r, w and x mean on a directory?
- Can a user delete a file they don't have write permission on?
- How does Linux decide which permission triplet applies?
umask, setuid, setgid & sticky bit
umask removes bits from default modes; setuid/setgid change who a program runs as, and the sticky bit protects shared directories.
- Programs create files asking for
666and directories asking for777. The process umask clears bits: mode = requested& ~umask. umask022→644/755;077→600/700. - umask is per process and inherited by children. Set it in shell startup files, in a service (
UMask=in a systemd unit) or with theumaskbuiltin. - setuid (
4xxx,sin user x slot): the program runs with the file owner's effective UID./usr/bin/passwdis setuid root so users can update/etc/shadow. Linux ignores setuid on scripts. - setgid (
2xxx): on a file it runs with the file's group; on a directory new files inherit the directory's group, great for shared team folders. - sticky bit (
1xxx,tin other x slot): in a world-writable directory like/tmp(1777), only the file owner, dir owner or root can delete or rename a file. - A capital
SorTmeans the special bit is set but the matching x bit is not, which is usually a mistake.
Interview questions
- What is umask and how is the final permission computed?
- Explain setuid with an example.
- How would you set up a shared folder for a team?
Users, groups & sudo
Users and groups are numbers (UID/GID) mapped to names in /etc files; sudo lets allowed users run commands as root with an audit trail.
- The kernel only knows UIDs and GIDs. Names come from
/etc/passwd(user, UID, GID, home, shell) and/etc/group. Password hashes live in/etc/shadow(readable only by root). - root is UID 0. System/service accounts usually have UIDs below 1000 and a shell of
/usr/sbin/nologin. - Each user has one primary group (used for new files) and any number of supplementary groups.
idshows them. useradd -m -s /bin/bash alice,passwd alice,usermod -aG docker alice(the-amatters: without it you replace all supplementary groups).- sudo runs a command as another user (root by default) after checking
/etc/sudoersand/etc/sudoers.d/. Always edit them withvisudo, which syntax-checks before saving. su -switches to another user and needs their password;sudoneeds your password and logs every command.
Interview questions
- Difference between
suandsudo? - Where are users and passwords stored?
- How do you give a user permission to restart one service without full root?
Processes, signals & services
Processes: PID, PPID, states, ps & top
A process is a running program with a PID, a parent, an owner, open files and a state; ps takes a snapshot and top watches live.
- Every process has a PID, a parent PPID, a UID, a working directory, an environment, open file descriptors and a state. All of it is visible in
/proc/<pid>/. - Threads are tasks that share memory with their process; in Linux they are also scheduled entities with their own TID (
ps -L,top -H). - States (
STATcolumn): R running/runnable, S interruptible sleep (waiting for an event), D uninterruptible sleep (usually disk or NFS I/O), T stopped, Z zombie. ps aux(BSD style) orps -ef(System V) list all processes.ps -o pid,ppid,stat,%cpu,%mem,cmd --sort=-%cpubuilds a custom view.pstree -pshows the tree.toprefreshes live: pressP(sort by CPU),M(by memory),1(per-CPU),k(kill). htop is a friendlier version with a tree view and mouse support.- Nice values (-20 to 19) influence CPU priority: higher nice = lower priority.
nice -n 10 cmd,renice 5 -p PID. Only root can lower nice.
Interview questions
- What is the difference between a process and a thread?
- What are the process states in Linux?
ps auxvsps -ef?
fork/exec, zombies & orphans
New programs start with fork (clone the parent) plus exec (replace the image); a dead child stays a zombie until its parent calls wait().
fork()creates a child that is a near-copy of the parent. Memory is shared copy-on-write, so fork is cheap. It returns0in the child and the child's PID in the parent.execve()replaces the current process image with a new program. The PID stays the same, and open fds (without close-on-exec) are inherited. That is how the shell sets up redirections before running a command.- When a child exits, the kernel keeps a tiny entry with its exit status until the parent calls
wait()/waitpid(). Until then it is a zombie (Z,<defunct>). Zombies use no memory or CPU, just a PID slot. - An orphan is a child whose parent died first. It is re-parented to PID 1 (or the nearest *subreaper*, like systemd user managers), which reaps it when it exits.
- You cannot kill a zombie: it is already dead. Fix or kill the parent, so PID 1 adopts the zombie and reaps it.
exec cmdin a shell script replaces the shell withcmd(no extra process). Docker entrypoint scripts useexec "$@"so the app becomes PID 1 and receives signals.
Interview questions
- Explain fork and exec.
- What is a zombie process and how do you get rid of it?
- What is copy-on-write in fork?
- Why should a container entrypoint script end with
exec "$@"?
Signals, kill, trap & job control
Signals are small async notifications; SIGTERM asks a process to stop, SIGKILL forces it, and the shell's job control uses signals for &, Ctrl+Z, bg and fg.
kill PIDsends SIGTERM (15) by default: a polite request the process can catch to clean up.kill -9 PIDsends SIGKILL, which the kernel enforces; no cleanup, no flushing, possible corrupted state.- SIGKILL and SIGSTOP can never be caught, blocked or ignored. Everything else can have a handler (
trapin bash). - SIGHUP (1): the controlling terminal closed. Many daemons reuse it to reload config (
nginx -s reload,kill -HUP). SIGINT (2) is Ctrl+C, SIGQUIT (3) is Ctrl+\ (core dump), SIGTSTP is Ctrl+Z. cmd &runs in the background.jobslists jobs,fg %1brings one to the foreground, Ctrl+Z stops the current one andbg %1resumes it in the background.- Closing the terminal sends SIGHUP to its jobs.
nohup cmd &ignores SIGHUP and writes output tonohup.out;disownremoves a job from the shell's table;setsidstarts a new session. For real services use systemd,tmuxorscreen. pkill -f patternandkillall namesignal by name.kill -0 PIDsends nothing but checks if the process exists and you may signal it.
Interview questions
- Difference between SIGTERM and SIGKILL?
- How do you keep a process running after you log out?
- What does
trapdo in a bash script? - A container exits with code 137. What happened?
systemd, systemctl, journalctl & cron
systemd is PID 1 and manages services as units; systemctl controls them, journalctl reads their logs, and cron or systemd timers schedule jobs.
- systemd manages units:
.service,.socket,.timer,.mount,.target. Vendor units live in/usr/lib/systemd/system/(or/lib/...); your own and overrides go in/etc/systemd/system/. systemctl start|stop|restart|reload|status NAME.enablecreates the symlinks so it starts at boot;enable --nowdoes both.maskblocks a unit from being started at all.- After editing a unit file run
systemctl daemon-reload. Usesystemctl edit NAMEto create a drop-in override instead of editing vendor files. - journald collects stdout/stderr of services plus kernel and syslog messages.
journalctl -u nginx -ffollows a unit,--since "1 hour ago",-p err,-b(this boot). - cron runs commands on a schedule:
crontab -eper user,/etc/crontaband/etc/cron.d/system-wide (those have an extra user field). Fields:min hour day-of-month month day-of-week. - Cron jobs run with a minimal environment (short
PATH, no.bashrc), so use absolute paths and redirect output to a log. systemd timers are the modern alternative with logging, dependencies andPersistent=catch-up.
Interview questions
- Difference between
systemctl startandsystemctl enable? - A service fails to start. How do you debug it?
- My cron job works by hand but not from cron. Why?
Shell: redirection, pipes, text & scripting
stdin/stdout/stderr, redirection & pipes
Every process starts with fd 0, 1 and 2; redirection rewires them to files and pipes connect one process's stdout to the next one's stdin.
- File descriptors:
0stdin,1stdout,2stderr. Programs print results to stdout and errors/diagnostics to stderr, so you can separate them. >overwrite,>>append,<read from file,2>redirect stderr,&>(bash) both,2>&1make fd 2 a copy of fd 1 as it is right now.- Redirections are processed left to right:
cmd > f 2>&1sends both tof;cmd 2>&1 > fsends stderr to the terminal (old stdout) and only stdout tof. - A pipe
a | bconnects a's stdout to b's stdin through a kernel buffer (64 KiB by default). Both run at the same time; a writer blocks when the buffer is full. - Here-doc
<<EOFand here-string<<< "$var"feed text to stdin.tee filecopies stdin to a file and stdout.set -o noclobberprevents>from overwriting. - Process substitution
<(cmd)gives a command's output as a filename:diff <(sort a) <(sort b).
Interview questions
- What do
2>&1and> /dev/null 2>&1mean? - How does a pipe work under the hood?
- Why does
sudo echo hi > /etc/motdgive “Permission denied”?
Text processing: grep, sed, awk, cut, sort, uniq, xargs, find
Small tools that each do one thing, chained with pipes, can answer most log and data questions in one line.
- grep filters lines:
-iignore case,-vinvert,-rrecursive,-nline numbers,-ccount,-Eextended regex,-oonly the match,-lfile names,-A/-B/-C Ncontext. - sed edits a stream:
sed 's/old/new/g', delete linessed '/^#/d', print a rangesed -n '10,20p'.-iedits in place (GNUsed -i, macOSsed -i ''). - awk splits each line into fields
$1..$NFand runspattern { action }:awk -F: '$3 >= 1000 {print $1}' /etc/passwd. It has variables, arrays andBEGIN/ENDblocks, ideal for sums and group-by. - cut picks fields (
cut -d, -f2) or chars; tr translates or deletes characters (tr a-z A-Z,tr -d '\r'); wc counts lines/words/bytes; head/tail take the start/end;tail -f(or-Fto survive log rotation) follows a growing file. - sort (
-nnumeric,-rreverse,-k2by column,-hhuman sizes,-uunique) and uniq (removes adjacent duplicates, so sort first;-ccounts). Classic top-N:sort | uniq -c | sort -rn | head. - find walks directories with tests:
find /var/log -name '*.log' -mtime +7 -size +100M. xargs turns stdin into arguments:find . -name '*.tmp' -print0 | xargs -0 rm.find -exec cmd {} +does the same without xargs.
Interview questions
- How do you find the top 10 most frequent IPs in a log file?
- Difference between grep, sed and awk?
- What does xargs do and why is it needed?
- How do you find files larger than 1 GB modified in the last day?
Environment variables, PATH & startup files
Exported variables are copied into child processes; PATH decides where commands are found; login and interactive shells read different startup files.
- A shell variable (
x=1) exists only in the current shell.export xmakes it an environment variable, copied into every child process. Children can never change the parent's environment. VAR=value cmdsets a variable only for that one command.env/printenvlist the environment;unset VARremoves it.- PATH is a colon-separated list of directories searched in order for commands.
which -a,type -aandcommand -vshow what will run. The current directory is not on PATH, hence./script.sh. - Login shell (SSH login,
bash -l, console): reads/etc/profile, then the first of~/.bash_profile,~/.bash_login,~/.profile. Interactive non-login shell (new terminal tab on most Linux desktops): reads~/.bashrc. - Usual setup: put exports in
~/.bash_profile(or~/.profile) and make itsource ~/.bashrc; put aliases, functions and prompt in~/.bashrc. Non-interactive scripts read neither (unlessBASH_ENVis set). source file(or. file) runs a file in the current shell, so its variables andcdstick. Running./fileuses a child shell and changes vanish.
Interview questions
- Difference between
.bashrcand.bash_profile? - Difference between a shell variable and an environment variable?
- Difference between
source script.shand./script.sh?
Shell scripting basics: variables, quoting, conditionals, loops, functions
A bash script is a list of commands with variables, tests and loops; exit codes drive the logic and quoting prevents most bugs.
- Start with a shebang:
#!/usr/bin/env bashfinds bash on PATH;#!/bin/shmeans POSIX sh (dash on Ubuntu), where bash features like[[ ]]and arrays don't exist. Make it executable withchmod +x. - Variables:
name=valuewith no spaces around=. Read with"$name". Arguments:$1..$9,$#count,"$@"all args as separate words,$0script name,$?last exit code,$$PID,$!last background PID. - Quoting: double quotes allow
$varand$(cmd)expansion but stop word-splitting and globbing; single quotes are fully literal. Always quote variables:rm "$file". - Exit codes: 0 = success, 1–255 = failure.
iftests the exit code of a command.&&runs the next command on success,||on failure. - Tests:
[[ -f file ]],-ddir,-zempty string,-nnon-empty,==string match (glob in[[ ]]),=~regex,-eq -lt -gtnumbers;(( n > 5 ))for arithmetic. - Loops:
for f in *.log; do ...; done,while read -r line; do ...; done < file,for ((i=0; i<3; i++)). Functions:name() { local x=$1; ...; return 0; }; they return a status and “return” data by echoing it.
Interview questions
- What is the shebang line and why use
#!/usr/bin/env bash? - Difference between single and double quotes in bash?
- What is the difference between
$@and$*? [ ]vs[[ ]]?
Robust scripts: set -euo pipefail, traps & pitfalls
Strict mode makes scripts fail fast on errors, unset variables and broken pipelines, but each flag has exceptions you must know.
set -e(errexit): exit when a command fails. It is ignored inif/whileconditions, in commands before&&/||, and in negated commands. Functions called inside those contexts also lose it.set -u(nounset): using an unset variable is an error. Use${VAR:-}when “unset” is a legal value.set -o pipefail: a pipeline's status is the last non-zero status of any stage, not just the last command's. Without itcurl bad | tee log“succeeds”.- Combined as
set -euo pipefailat the top of every script. Addtrap 'echo "failed at line $LINENO" >&2' ERRfor a useful error message andtrap cleanup EXITfor temp files and locks. - Pitfalls:
local x=$(cmd)hidescmd's failure (the status is that oflocal); split intolocal x; x=$(cmd).grepreturns 1 on no match, sogrep ... || truewhen that's fine.((count++))returns 1 when count was 0. - Make scripts idempotent (safe to re-run:
mkdir -p,ln -sf, check before create), usemktempfor temp files,flockto stop overlapping cron runs, and run ShellCheck in CI.
Interview questions
- What does
set -euo pipefaildo? - When does
set -enot stop the script? - Why is
pipefailimportant? - How do you stop a cron script from running twice at the same time?
System resources, networking & troubleshooting
Load average, memory, swap, OOM killer & disks
Read load against CPU count, memory via the “available” column, and disk via df (space and inodes), du (who uses it), lsblk and mount.
- Load average (
uptime,/proc/loadavg) is the exponentially-damped average of tasks that are runnable or in uninterruptible sleep (D), over 1, 5 and 15 minutes. Divide by the number of CPUs (nproc). Load 8 on 8 cores is full; on 2 cores tasks are queuing. - On Linux high load with low CPU usage usually means tasks stuck in D state on disk or NFS I/O. Check
waintop,vmstat 1andiostat -x 1. free -h: used, free, buff/cache and available. Linux fills spare RAM with page cache, so low “free” is normal; available estimates what apps can still get without swapping.- Swap is disk-backed overflow memory. Some swap use is fine; constant swap in/out (
si/soinvmstat) means thrashing.vm.swappinesstunes how eagerly the kernel swaps. - When memory can't be reclaimed, the OOM killer picks a victim by
oom_score(mostly memory size, adjusted byoom_score_adjfrom -1000 to 1000) and sends SIGKILL.dmesg -T | grep -i 'killed process'shows it. Containers hit their cgroup limit the same way. - Disks:
lsblkshows block devices and partitions,df -hfree space per mounted filesystem,df -iinodes,du -sh dirusage of a tree,mount/findmntmounts, and/etc/fstab(use UUIDs) persists them.
Interview questions
- What is load average and what is a “good” value?
- Load is 20 on a 4-core box but CPU is 10% used. What's going on?
freeshows almost no free memory. Is that a problem?- Difference between
dfanddu?
Networking commands: ip, ss, curl, dig, ping, traceroute, nc
Debug a network path bottom-up: interface and route (ip), DNS (dig), reachability (ping, traceroute), port (nc, ss), then the application (curl).
ip addr(interfaces and IPs),ip route(routing table, default gateway),ip link(up/down, MTU). They replace the deprecatedifconfigandroutefrom net-tools.ss -tulpnlists listening TCP/UDP sockets with the owning process (-pneeds root to see other users' processes).ss -tan state establishedshows connections.ssreplaces the oldernetstat.pingtests ICMP reachability and latency; many clouds and firewalls block ICMP, so no reply ≠ host down.traceroute/tracepath/mtrshow each hop to find where packets stop or slow down.dig example.com(ordig +short,dig @8.8.8.8,dig MX) queries DNS directly;nslookupandhostare simpler.getent hosts nameresolves the way apps do (including/etc/hosts, via nsswitch).curl -v https://host/pathshows DNS, TCP, TLS and HTTP headers;-Iheaders only,-Lfollow redirects,-osave,-w '%{http_code}'print fields.wgetis mainly for downloads.nc -zv host 5432checks if a TCP port is open;nc -l 9000opens a quick listener. Other tools:tcpdump -i any port 443captures packets,lsof -i :8080maps ports to processes, firewall viaiptables/nftables/ufw/firewalld.
Interview questions
- How do you check which process is listening on port 8080?
- A service can't reach the database. How do you debug it?
- Difference between
netstatandss? - What happens when you run
curl https://example.com?
SSH, keys, scp & rsync
SSH gives an encrypted remote shell; key-based auth proves identity with a private key that never leaves your machine; scp/rsync copy files over it.
ssh-keygen -t ed25519 -C you@example.comcreates a key pair:~/.ssh/id_ed25519(private, keep600) and.pub(public).ssh-copy-id user@hostappends the public key to the server's~/.ssh/authorized_keys.- Login with keys: the server sends a challenge, the client signs it with the private key, the server verifies with the stored public key. The private key is never sent.
- On first connect you accept the server's host key, stored in
~/.ssh/known_hosts. A later mismatch warning means the server was rebuilt or a man-in-the-middle; verify before deleting the entry. - Hardening
/etc/ssh/sshd_config:PasswordAuthentication no,PermitRootLogin no(orprohibit-password), restrict users, thensshd -tand reload. Permissions:~/.ssh700,authorized_keys600, or sshd ignores them. ~/.ssh/configstores host aliases, users, keys andProxyJump(bastion hosts).ssh-agentholds decrypted keys in memory; agent forwarding (-A) is convenient but risky on untrusted hosts.- Copying:
scp file host:/pathis simple; rsync (rsync -avz --delete src/ host:dst/) transfers only differences, can resume and preserve permissions, and is preferred for directories. Tunnels:-Llocal forward,-Rremote forward,-DSOCKS proxy.
Interview questions
- How does SSH key-based authentication work?
- What is
known_hostsand what does “REMOTE HOST IDENTIFICATION HAS CHANGED” mean? - scp vs rsync?
- How do you securely reach a database in a private subnet?
Troubleshooting scenarios: disk full, high CPU, port in use, slow server
Have a repeatable checklist: confirm the symptom, find the resource that is saturated, find the process responsible, fix safely, then prevent it.
- Disk full:
df -hto find the filesystem,df -ifor inodes,du -xh --max-depth=1 / | sort -hto drill down. Usual suspects: logs in/var/log, Docker images/volumes (docker system df), core dumps, old kernels, journal (journalctl --vacuum-size=500M). - Space not freed after deleting a big log? A process still has it open.
lsof +L1(orlsof | grep deleted) finds it; restart/reload the process or truncate via: > /proc/<pid>/fd/<n>. Next time truncate with: > fileinstead ofrm, and set up logrotate. - High CPU:
top/htopsorted by CPU, checkusvssyvswavsst. For the busy process:top -H -p PIDfor threads,strace -cp PIDfor syscalls,perf top, or language tools (jstack,py-spy). - Port already in use (
EADDRINUSE):ss -ltnp | grep :8080→ PID → is it an old instance, another service or a zombie container? Stop it properly; for restarts in your own code setSO_REUSEADDRto avoid waiting onTIME_WAIT. - Server slow (USE method: Utilization, Saturation, Errors for each resource):
uptime→dmesg -T | tail→vmstat 1→mpstat -P ALL 1→pidstat 1→iostat -xz 1→free -m→sar -n DEV 1→top. Then app logs and dependencies (DB, DNS, downstream APIs). - Always: check what changed (deploys, config, traffic), look at logs (
journalctl -p err -b), fix the symptom safely, then write down the root cause and add monitoring or alerts.
Interview questions
- A server says “No space left on device”. Walk me through it.
- A process is using 100% CPU. What do you do?
- Your app fails to start with “Address already in use”. How do you fix it?
- Users say the server is slow. How do you approach it?