Skip to content
devops.academy

Module 2: Linux — The Complete Guide

Goal

Linux is the operating system of the cloud — ~96% of servers run it. Every container is a Linux process. This module makes you comfortable living in a terminal on a remote server, because that's where a DevOps engineer lives.


1. What Linux Is (and Kernel vs OS)

  • Kernel: the core program managing hardware — CPU scheduling, memory, disks, network. Written by Linus Torvalds (1991), now developed by thousands.
  • OS / Distribution (distro): kernel + package manager + system tools + defaults. Ubuntu, Debian, RHEL, Alpine are different distros sharing the same kernel family.

Choosing a distro in practice:

DistroWhere you'll meet it
Ubuntu / DebianMost common cloud servers, CI runners. Uses apt. Learn this first.
RHEL / Rocky / Amazon LinuxEnterprise, AWS defaults. Uses yum/dnf.
AlpineTiny (~5MB) — the standard base for Docker images. Uses apk.

Why servers run Linux: free, stable for years without reboot, scriptable, secure multi-user design, and it runs everything from a Raspberry Pi to all of Google.

Analogy

Think of a Linux server as a large office building. The kernel is the hidden infrastructure — wiring, plumbing, elevators — that every tenant depends on but never sees. A distribution is that same building fitted out by a different property company: Ubuntu and Alpine have different furniture, signage, and supplier catalogs, but the concrete core underneath is the same.


2. The Shell

The shell (usually bash) is a program that reads your commands and executes them. The terminal is the window it runs in. Anatomy of a command:

bash
ls -lh /var/log
  • ls — the command
  • -lh — flags/options (how to behave)
  • /var/log — the argument (what to act on)

Get help without Google: man ls, ls --help, tldr ls (community examples).

Analogy

The shell is the building's front desk: you state a request in a fixed format — what to do, how to do it, and what to do it to — and the desk dispatches it to the right department. The terminal is just the window you speak through. Man pages are the binder of standard request forms that always sits on the counter.


3. Filesystem Hierarchy — Where Everything Lives

Linux has one tree starting at /. Memorize this table — as a DevOps engineer you'll navigate these daily:

PathPurposeReal-life use
/etcConfiguration files/etc/nginx/nginx.conf, /etc/ssh/sshd_config
/var/logLog filesFirst stop when anything breaks
/home/<user>User home dirsYour files, ~/.ssh/ keys
/rootRoot user's home—
/tmpTemporary filesWiped on reboot
/usr/bin, /binInstalled programsWhere commands live
/optOptional/3rd-party appsManually installed software
/proc, /sysVirtual: kernel & process infocat /proc/meminfo
/devDevices as filesDisks: /dev/sda, /dev/null

Analogy

The filesystem is the building's floor plan, and every path is a walking route that starts in the lobby at the root. The records office is /etc, where every department keeps its official paperwork; /var/log is the archive room you visit first whenever something went wrong; /tmp is the bin that gets emptied overnight — never leave anything there that you want to keep.

bash
pwd                     # where am I
ls -lah                 # list: long, all (hidden), human sizes
cd /var/log             # absolute path
cd ..                   # up one; cd - (previous); cd (home)
mkdir -p app/config     # -p creates parents
touch notes.txt         # create empty file / update timestamp
cp file.txt backup.txt  # copy;  cp -r dir1 dir2 for directories
mv old.txt new.txt      # move AND rename are the same command
rm file.txt             # delete;  rm -rf dir   no trash, no undo

Analogy

Permissions are the building's key system. Every room has three lock settings: what the room's owner may do inside, what their team's key cards allow, and what any passer-by in the hallway can do. Setting 777 is taping the door open — anyone can walk in and rearrange the furniture. The fix for a locked-out colleague is issuing the right key, not removing the lock.

Career-defining warning: rm -rf / or a mistyped variable like rm -rf $DIR/ when $DIR is empty destroys the machine. Professionals echo the path first, or use rm -rf -- "${DIR:?}/" which aborts if unset.

Viewing files

bash
cat config.yml            # print whole file
less huge.log             # scroll (q quits, / searches) — use for big files
head -n 20 app.log        # first 20 lines
tail -n 50 app.log        # last 50 lines
tail -f app.log           # FOLLOW live — watching logs during a deploy

tail -f /var/log/nginx/error.log while reproducing a bug is the most common debugging move in ops.


4. Permissions & Ownership

Every file has an owner, a group, and permissions for owner/group/others:

text
-rwxr-xr--  1 deploy  www-data  1.2K  Jul 1 10:00  deploy.sh

Reading -rwxr-xr-- left to right:

CharsMeaning
-type: - file, d directory, l link
rwxowner: read + write + execute
r-xgroup: read + execute
r--others: read only

Numeric form: r=4, w=2, x=1 → rwx r-x r-- = 754.

bash
chmod 644 config.yml        # owner rw, everyone read (typical config)
chmod 600 id_rsa            # owner-only (REQUIRED for SSH private keys)
chmod +x deploy.sh          # make executable
chown deploy:www-data app/  # change owner and group
chown -R appuser: /opt/app  # recursive

Real scenarios:

  • SSH refuses your key with "permissions are too open" → chmod 600 ~/.ssh/id_rsa.
  • Nginx returns 403 → the nginx user can't read your files → fix ownership/permissions.
  • Anti-pattern: chmod 777 "to make it work". That lets anyone modify/execute the file. In production this is a security incident waiting to happen; fix ownership instead.

5. Users, Groups, sudo

Linux is multi-user by design. Services each run as their own low-privilege user (www-data, postgres) so a compromised app can't take the whole server — this is least privilege, a core DevOps principle.

bash
sudo adduser deploy               # create user (interactive, Debian/Ubuntu)
sudo groupadd developers
sudo usermod -aG developers alice # -aG = append to group (forgetting -a REPLACES groups!)
groups alice                      # check memberships
sudo usermod -aG sudo alice      # grant admin rights (Ubuntu)
sudo passwd alice                 # set/reset password
whoami; id                        # who am I, what are my groups

root & sudo: root (UID 0) can do anything. Direct root login is disabled on well-run servers; instead admins get sudo (run one command as root, logged in /var/log/auth.log — an audit trail of who did what). Config lives in /etc/sudoers, edited only via visudo.

Analogy

In the building, root holds the master key that opens every door, including the server room and the safe. Well-run buildings never hand that key out permanently; instead an employee signs it out from security for one specific task, and the logbook records who took it, when, and why. That signed logbook is sudo — and the audit trail is the whole point.

Real scenario: granting a CI runner permission to restart one service without full root:

text
# /etc/sudoers.d/ci-runner
ci ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart myapp

6. Package Management (apt)

bash
sudo apt update                 # refresh package index (always first)
sudo apt upgrade                # apply upgrades
sudo apt install nginx -y       # install
sudo apt remove nginx           # uninstall (purge = also delete configs)
apt search redis                # find packages
apt list --installed | grep ssl # what's installed

Real scenario — patching a CVE across a fleet: sudo apt update && sudo apt upgrade -y openssl (later you'll automate this exact command across 50 servers with Ansible).

Analogy

The package manager is the building's purchasing department with an approved supplier catalog. You never haul random furniture in off the street: you request an item from the catalog, and purchasing fetches the right version, checks that it fits, and knows how to remove it cleanly later. Running apt update first is asking for this month's catalog before placing the order.


7. Processes

Every running program is a process with a PID. Containers, when you get to Docker, are just Linux processes with isolation — so this section is secretly Docker fundamentals.

Analogy

Processes are the employees of the building: each has a badge number (the PID), a desk, and a job. A plain kill is a polite tap on the shoulder so they can file their work and leave tidily; kill -9 is security marching them out mid-sentence with papers still on the desk. A zombie is an employee who already left while HR never filed the exit paperwork — you fix HR (the parent process), not the ghost.

bash
ps aux                      # snapshot of all processes
ps aux | grep nginx         # find one
top                         # live view (htop is nicer: sudo apt install htop)
kill 1234                   # polite stop (SIGTERM 15) — app can clean up
kill -9 1234                # force kill (SIGKILL) — last resort
pkill -f gunicorn           # kill by name/pattern

Analogy

systemd is the building manager: it opens the building each morning, calls every employee in, replaces anyone who collapses at their desk, and keeps a diary of everything that happened. Asking systemctl status is stopping by the manager's office to ask how one employee is doing; journalctl is reading the manager's diary for that employee.

Reading top like a pro:

  • load average 0.5, 1.2, 2.0 = runnable processes averaged over 1/5/15 min. Rule of thumb: sustained load > CPU core count = saturation. (4 cores handling load 8 = trouble.)
  • %MEM / RES — who's eating RAM.
  • CPU 99% in wa (I/O wait) = disk is the bottleneck, not CPU.

Zombie processes: a finished child whose parent never collected its exit status; shows as Z/<defunct> in ps. It's dead — you can't kill it again; you fix it by restarting (or fixing) the parent. Many zombies usually indicate a buggy service. (In Docker, this is why minimal init processes like tini exist.)

Foreground/background: command & runs in background; jobs, fg, Ctrl+Z + bg manage them; nohup cmd & survives logout (though in production you'll use systemd instead).

systemd (managing services)

bash
sudo systemctl status nginx     # is it running? recent logs?
sudo systemctl restart nginx
sudo systemctl enable nginx     # start automatically on boot
journalctl -u nginx -f          # follow a service's logs
journalctl -u myapp --since "1 hour ago"

8. Disk & System Monitoring

bash
df -h                # free space per filesystem — THE first command when "server is broken"
du -sh /var/log/*    # size of each item — find what's eating the disk
free -h              # RAM usage ("available" is what matters, not "free")
uptime               # load averages at a glance

Classic real incident: app crashes, users report 500s. df -h shows / at 100% — logs filled the disk. Fix: du -sh /var/* → find the 40GB log → truncate/rotate it → configure logrotate so it never recurs. You will live this scenario. Memorize the diagnosis path: df -h → du -sh → clean → prevent.


9. Networking Commands (Preview of Module 4)

bash
ip addr              # my IP addresses (older: ifconfig)
ss -tulpn            # what ports are listening, and which process owns them
ping google.com      # basic reachability
curl -I https://myapp.com     # HTTP request, headers only
curl -s localhost:8080/health # hit a health endpoint
wget https://example.com/file.tar.gz   # download files

Scenario: "the app isn't reachable." ss -tulpn | grep 8080 — is anything even listening on 8080? If not, the app is down/misconfigured; if yes, suspect firewall/security group. This one command splits the problem space in half.


10. SSH — Your Gateway to Every Server

SSH gives you an encrypted shell on a remote machine. Keys > passwords, always.

bash
ssh-keygen -t ed25519 -C "you@example.com"   # creates ~/.ssh/id_ed25519 (+ .pub)
ssh-copy-id deploy@203.0.113.10              # install your public key on the server
ssh deploy@203.0.113.10                      # log in
ssh -i ~/.ssh/mykey.pem ubuntu@ec2-host      # AWS-style with specific key

How key auth works: server holds your public key (~/.ssh/authorized_keys); your private key never leaves your laptop; the server issues a challenge only your private key can answer.

Analogy

SSH is the building's secure service entrance. The guard keeps a photo of your key on file — your public key — while the physical key never leaves your pocket. To get in, the guard poses a challenge only the true key can answer, so nothing secret ever crosses the street. Password logins, by contrast, are shouting the door code from the sidewalk and hoping nobody is listening.

~/.ssh/config — save yourself typing forever:

text
Host prod-web
    HostName 203.0.113.10
    User deploy
    IdentityFile ~/.ssh/prod_key

Now just: ssh prod-web.

Hardening a server (day-one checklist): in /etc/ssh/sshd_config set PasswordAuthentication no and PermitRootLogin no, then sudo systemctl restart sshd. Internet-facing servers get thousands of brute-force attempts daily; key-only auth neutralizes them.

scp — copying files

bash
scp app.tar.gz deploy@prod-web:/opt/app/     # local → remote
scp deploy@prod-web:/var/log/app.log ./      # remote → local
scp -r ./configs deploy@prod-web:/etc/myapp/ # directories

(For big/repeated transfers, rsync -avz only sends differences.)


11. Text Processing & Editors

grep & find — searching

bash
grep -r "DATABASE_URL" /opt/app/       # search text recursively
grep -i error app.log                  # case-insensitive
grep -c "500" access.log               # count matches
grep -v "healthcheck" access.log       # invert: exclude noise
find / -name "*.conf" 2>/dev/null      # find files by name
find /var/log -size +100M              # files over 100MB
find /tmp -mtime +7 -delete            # delete files older than 7 days

Pipes — Linux's superpower

| sends one command's output into the next. Real log-analysis one-liner — top 5 IPs hitting your server:

bash
awk '{print $1}' access.log | sort | uniq -c | sort -rn | head -5

Redirection: > overwrite file, >> append, 2>&1 include errors, > /dev/null discard.

vim & nano

nano file — simple: edit, Ctrl+O save, Ctrl+X exit.

vim survival (it's on every server, so learn the minimum):

  • i insert mode → type normally → Esc back to normal mode
  • :wq save & quit · :q! quit without saving
  • /text search · dd delete line · u undo · gg/G top/bottom

Archives

bash
tar -czvf backup.tar.gz /opt/app     # create gzipped archive
tar -xzvf backup.tar.gz -C /restore  # extract  (mnemonic: eXtract Ze Vile Files)
zip -r site.zip site/ ; unzip site.zip

12. Cron — Scheduled Automation

bash
crontab -e     # edit your schedule;  crontab -l to list

Format: minute hour day-of-month month day-of-week command

text
# min  hour  dom  mon  dow  command
  0    2     *    *    *    /opt/scripts/backup.sh          # daily 02:00
  */5  *     *    *    *    curl -fsS localhost:8080/health || systemctl restart myapp
  0    9     *    *    1    /opt/scripts/weekly-report.sh   # Mondays 09:00

Real uses: nightly DB backups, log rotation, cert renewal, cleanup jobs. Pro tips: cron has a minimal PATH — use absolute paths in scripts; always log output: backup.sh >> /var/log/backup.log 2>&1. Check https://crontab.guru to decode schedules.

Analogy

Cron is the night janitor's wall schedule: mop the lobby at 2 a.m., check the boiler gauge every five minutes, take out the recycling on Mondays at nine. Nobody has to remember or even be present — the tasks simply happen on the clock. Just remember the janitor works a dim hallway with a short supply list, so write out full routes (absolute paths) and have them leave a written report (a log) after every round.


13. Boot Process & Troubleshooting Method

Boot in one line each: firmware (BIOS/UEFI) → bootloader (GRUB) → kernel loads → systemd (PID 1) starts every service. If a server "boots but the app is down," the investigation is: systemctl status app → journalctl -u app → fix → systemctl restart app.

Analogy

Booting is the building opening for the day: the power comes on, security unlocks the doors and picks which floor plan to use (the bootloader), the core infrastructure hums to life (the kernel), and finally the building manager walks in as employee number one and phones every worker to come in. If one shop stays dark, you don't rewire the whole building — you ask the manager which employee never showed up, and read the manager's diary about them.

Universal troubleshooting order (memorize):

  1. df -h — disk full?
  2. free -h — out of memory? (check dmesg | grep -i "killed process" for OOM-killer)
  3. top — CPU pegged? load high?
  4. systemctl status <svc> + journalctl -u <svc> -n 100 — what does the service say?
  5. ss -tulpn — is it listening?
  6. tail -f /var/log/... — reproduce and watch.

14. Hands-On Project (Do This)

Spin up a free Ubuntu VM (AWS free tier EC2, or Multipass/VirtualBox locally):

  1. SSH in with a key; then disable password auth and verify.
  2. Create user deploy, give it sudo, redo login as deploy.
  3. apt install nginx, confirm with systemctl status and curl localhost.
  4. Change nginx's page in /var/www/html/index.html using vim.
  5. Break it on purpose (edit /etc/nginx/nginx.conf badly), diagnose via nginx -t and journalctl -u nginx, fix it.
  6. Write a cron job that appends date + df -h output to /var/log/disk-report.log hourly.
  7. Fill /tmp with a big file (fallocate -l 1G /tmp/big), practice the df→du→delete diagnosis.
  8. Find the top 3 IPs in /var/log/nginx/access.log using a pipe chain.

15. Self-Check Questions

  • What does load average 6.0 mean on a 2-core server?
  • Why is chmod 777 wrong, and what's the right fix for a permission error?
  • Difference between kill and kill -9? Why prefer the first?
  • A disk is full: exact command sequence to find and fix the cause?
  • Why do SSH private keys need 600 permissions?
  • What runs as PID 1 and why does it matter?

Next → Module 3: Bash Scripting