📚 Module: Unit 3 • Systems & Infrastructure

Linux Operating System & The Command Line

A first-principles engineering textbook on the operating system foundation of modern cloud infrastructure. Master the Linux monolithic kernel architecture, virtual filesystem hierarchies, POSIX octal file permissions, process states, systemd service daemonization, secure shell cryptographic hardening, automated bash workflows, and enterprise log streaming.

🐧 Operating System: Linux (Ubuntu, Debian, RHEL, Alpine)
⚡ Init System: Systemd & Journald
🔐 Protocol: OpenSSH (Ed25519 & RSA)
🎯 Formula: 60% Theory • 20% Code • 20% Architecture
← Unit 02: Backend Programming (JS / TS) Backend & Cloud Track • Unit 03 of 12 Track Index Syllabus →

Introduction to Linux & Kernel Architecture

Virtually every production backend service, cloud virtual machine, container (Docker), and database cluster in modern enterprise computing executes on the Linux operating system. Developed by Linus Torvalds in 1991 following the POSIX and Unix design philosophies, Linux is a preemptive, multi-user, multitasking monolithic kernel.

User Space versus Kernel Space

Modern CPU architectures enforce hardware privilege levels (known as rings in x86-64). Linux exploits this boundary to protect physical hardware and memory integrity:

The System Call (Syscall) Interface

When a backend application reads a file from disk (fs.readFile), binds an HTTP port (listen(8080)), or allocates heap memory, it cannot perform the action directly. Instead, it must trigger a System Call (e.g., read(), write(), epoll_wait(), mmap()). The CPU executes a context switch from User Space to Kernel Space, the kernel verifies the process permissions, executes the hardware I/O, and transitions back to User Space with the return value.

Figure 3.1 — The Linux Operating System Stack & Syscall Boundary
+---------------------------------------------------------------------------------------+ | USER SPACE (Ring 3: Untrusted, Isolated Memory) | | | | [Node.js API Server] [PostgreSQL Database] [Bash Shell / CLI Utilities] | | | | | | | v v v | | GNU C Library (glibc) / POSIX Wrapper Functions (read, write, fork, socket) | +---------------------------------------------------------------------------------------+ | SYSTEM CALL INTERFACE (trap / syscall) | v +---------------------------------------------------------------------------------------+ | KERNEL SPACE (Ring 0: Hardware Privileged, Monolithic Kernel) | | | | +-------------------+ +--------------------+ +------------------+ +-------------+ | | | Process Scheduler | | Virtual Filesystem | | TCP/IP Net Stack | | Memory Paging| | | | (CFS Algorithm) | | (ext4, XFS, btrfs) | | (Sockets, epoll) | | (Virtual RAM)| | | +-------------------+ +--------------------+ +------------------+ +-------------+ | | | | | DEVICE DRIVERS (Block, Character, Network) | +---------------------------------------------------------------------------------------+ | v +---------------------------------------------------------------------------------------+ | PHYSICAL HARDWARE (x86_64 / ARM64 CPUs, NVMe Storage, RAM, Ethernet NICs) | +---------------------------------------------------------------------------------------+

Linux Distributions Taxonomy

A Linux distribution combines the Linux kernel with GNU system utilities, package managers, and default system services:

Filesystem Hierarchy Standard (FHS) & Inode Mechanics

In Linux, there are no drive letters (like Windows C:\ or D:\). The entire storage landscape is unified into a single hierarchical tree beginning at the root directory: /.

The Filesystem Hierarchy Standard (FHS)

Directory Designation & Architectural Responsibility
/bin & /sbin Essential system binaries (e.g., ls, cp, sh) and administrative binaries (iptables, reboot).
/etc Host-specific system-wide configuration files (e.g., /etc/hosts, /etc/nginx/, /etc/passwd).
/var Variable runtime data that grows dynamically during server life (e.g., /var/log/, /var/lib/postgresql/).
/tmp Temporary storage wiped on reboot; typically mounted in RAM (tmpfs) with sticky-bit permissions.
/proc & /sys Virtual in-memory filesystems generated on-the-fly by the kernel exposing live process metrics and hardware state.
/dev Special device node files representing physical and pseudo hardware (e.g., /dev/null, /dev/random, /dev/sda1).
/home & /root Personal user home directories and the dedicated home directory for the root superuser.

Inodes: How Linux Tracks Files

In Linux, the filename is merely a human-readable label pointing to an underlying data structure called an Inode (Index Node). The inode contains all metadata about the file:

⚠️ Notice: What is NOT Stored in the Inode

The inode does not contain the filename or the directory path! Filenames are stored inside directory data blocks, which map human strings to inode numbers. This allows multiple filenames to point to the exact same physical inode—a concept known as a Hard Link.

Figure 3.2 — Inode Structure: Hard Links vs Symbolic Links
Directory Entry A: "app.log" -------\ +----> [INODE #81429] Directory Entry B: "audit.log" ------/ - Permissions: -rw-r--r-- (Hard Link: Shares Inode & Data) - Size: 4096 bytes - Hard Link Count: 2 - Pointers: [Block 410, Block 411] | | v v [Data Block] [Data Block] ("2026-10-17 User logged in") Directory Entry C: "shortcut.lnk" (Symbolic Link: Separate Inode) | v [INODE #99312] (Type: Symlink) - Data Block Contains Target Path: "/var/log/app.log"

Essential Shell Commands & Stream Redirection

The shell is a command language interpreter that executes commands read from standard input devices or from files. Mastery of command pipelines allows backend engineers to diagnose production servers in seconds without deploying secondary telemetry agents.

The Unix Stream Trinity: stdin, stdout, stderr

Every process spawned by the Linux kernel automatically inherits three open file descriptors:

  1. Standard Input (stdin, Descriptor 0): The input stream (defaults to terminal keyboard input).
  2. Standard Output (stdout, Descriptor 1): The default output stream for program results.
  3. Standard Error (stderr, Descriptor 2): The unbuffered diagnostic and error stream, decoupled from standard output.
Bash Shell Terminal Session
# Stream Redirection Syntax Reference
# 1. Overwrite stdout to file
node dist/index.js > app.log

# 2. Append stdout to file without destroying existing contents
node dist/index.js >> app.log

# 3. Redirect stderr only to error.log
node dist/index.js 2> error.log

# 4. Redirect both stdout and stderr to the same consolidated logfile
node dist/index.js > combined.log 2>&1
# Modern Bash shorthand syntax:
node dist/index.js &> combined.log

# 5. Blackhole redirection: Discard output completely
python3 worker.py > /dev/null 2>&1

# 6. Pipeline: Connect stdout of Command A to stdin of Command B
cat /var/log/nginx/access.log | grep "500" | awk '{print $1}' | sort | uniq -c | sort -nr | head -n 10

Production Text Processing Toolkit

POSIX File Permissions, Octal Notation & Umask

Linux implements Discretionary Access Control (DAC). Every file and directory on disk is tagged with an ownership pairing (User Owner, Group Owner) and 9 fundamental permission bits grouped into three triads.

The Permission Triad & Binary Octal Calculation

Each triad governs access for: User (u), Group (g), and Others (o). The individual bits map directly to power-of-two values:

Figure 3.3 — Permission Bitfield Decomposition (-rwxr-xr--)
File Type Indicator (-) = Regular File (d = directory, l = symlink) | | USER (Owner) GROUP OTHERS (World) | +-------------+ +-------------+ +-------------+ v | r w x | | r - x | | r - - | - | 4 + 2 + 1 | | 4 + 0 + 1 | | 4 + 0 + 0 | +-------------+ +-------------+ +-------------+ | | | v v v Octal: 7 Octal: 5 Octal: 4 Full Permission String: -rwxr-xr-- ===> Octal Representation: 754
Octal String Notation Production Use Case & Security Justification
chmod 700 rwx------ Private administrative directories (e.g., ~/.ssh/). Disallows group or other access.
chmod 600 rw------- Private cryptographic keys (id_ed25519) and sensitive credentials files.
chmod 644 rw-r--r-- Standard public static files and codebases. Owner can edit; world can read.
chmod 755 rwxr-xr-x Standard executable binaries and traversable directories.
chmod 777 rwxrwxrwx Strict Security Anti-Pattern: Grants complete write and delete authority to everyone.

Special Permission Bits: SUID, SGID & Sticky Bit

Users, Groups & Privilege Escalation (sudo)

Linux enforces multi-tenant identity security through unique numeric identifiers: UID (User ID) and GID (Group ID).

System Identity Databases

The Principle of Least Privilege & Sudo

In cloud infrastructure, logging in directly as the root superuser (UID 0) is strictly prohibited. An accidental typo like rm -rf / will permanently destroy the OS without confirmation.

Engineers create unprivileged system users (e.g., deployer, shivan) and grant granular administrative authority via sudo (Superuser Do). The configuration file /etc/sudoers defines who can run what commands. It must only ever be edited using the visudo command, which performs syntax validation before saving, preventing locks caused by syntax errors.

Processes, POSIX Signals & Systemd Service Architecture

A process is an active instance of a running program in memory. The Linux kernel assigns each process a unique positive integer known as the PID (Process ID).

Process States in the Linux Scheduler

At any moment, a process exists in one of five core operational states:

POSIX Inter-Process Communication Signals

Signal Number Operational Meaning & Backend Behavior
SIGHUP 1 Hangup. Instructs server daemons (Nginx, Postgres) to reload configuration files without dropping connections.
SIGINT 2 Interrupt. Emitted by the terminal when a user presses Ctrl+C. Requests graceful termination.
SIGTERM 15 Termination. Standard graceful shutdown signal sent by Kubernetes and Systemd. Can be caught to drain database sockets.
SIGKILL 9 Kill. Uncatchable, unignorable. The kernel immediately destroys the process memory space. Does not allow socket cleanup.

Systemd: The Enterprise Init Daemon (PID 1)

When Linux boots, the kernel mounts the root filesystem and executes the first user-space process: systemd (PID 1). Systemd initializes hardware, mounts storage, manages network interfaces, and monitors background services (daemons).

Systemd Unit Configuration /etc/systemd/system/backend-api.service
[Unit]
Description=Production Node.js Backend API Service
Documentation=https://api.devascentacademy.me/docs
After=network.target postgresql.service redis.service
Wants=postgresql.service redis.service

[Service]
Type=simple
User=nodeapp
Group=nodeapp
WorkingDirectory=/var/www/backend-api
ExecStart=/usr/bin/node dist/index.js
Restart=always
RestartSec=5s

# Environment Configuration
Environment=NODE_ENV=production
EnvironmentFile=/etc/backend-api/production.env

# Security Hardening Directives
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/var/log/backend-api

# Resource Limits (Cgroups)
LimitNOFILE=65535
MemoryMax=2G

[Install]
WantedBy=multi-user.target
Bash Shell Systemctl Administration Commands
# Reload systemd manager configuration after creating or modifying unit file
sudo systemctl daemon-reload

# Enable service to boot automatically on OS start
sudo systemctl enable backend-api.service

# Start the service immediately
sudo systemctl start backend-api.service

# Inspect live status, uptime, and recent logs
sudo systemctl status backend-api.service

# Gracefully restart the service
sudo systemctl restart backend-api.service

Package Managers & Automated Provisioning

Linux does not use haphazard .exe downloaders. Software is installed from cryptographically verified, centralized package repositories.

Debian/Ubuntu Advanced Package Tool (APT)

Secure Shell (SSH) & Cryptographic Server Hardening

Production backend servers run headless in remote cloud data centers without physical monitors or keyboards. OpenSSH (Secure Shell) is the encrypted network protocol used to manage remote operating systems.

Public-Key Asymmetric Cryptography

Passwords are fundamentally vulnerable to brute-force dictionary attacks and credential stuffing. SSH authentication relies on asymmetric cryptographic key pairs:

  1. Private Key (~/.ssh/id_ed25519): Kept securely on the client workstation. Never transmitted across the network. Guarded by permissions 600.
  2. Public Key (~/.ssh/id_ed25519.pub): Placed on the remote server inside the user's ~/.ssh/authorized_keys file.
Figure 3.4 — SSH Challenge-Response Key Handshake Protocol
CLIENT WORKSTATION REMOTE CLOUD SERVER +------------------------+ +------------------------+ | 1. Request SSH Session | ===========================> | 2. Identify Public Key | | (user: deployer) | | in authorized_keys | +------------------------+ +------------------------+ ^ | | v +------------------------+ +------------------------+ | 4. Decrypt Random Token| <=========================== | 3. Generate Random | | using Private Key | Encrypted Challenge | Cryptographic Token | | (id_ed25519) | | Encrypt with PubKey | +------------------------+ +------------------------+ | | v v +------------------------+ +------------------------+ | 5. Send Decrypted Hash | ===========================> | 6. Verify Match: | | Signature to Server | | [ACCESS GRANTED] | +------------------------+ | Allocate PTY Shell | +------------------------+
OpenSSH Server Hardening /etc/ssh/sshd_config
# Enterprise Production SSH Hardening Policy
Port 2222                          # Evade automated generic port 22 bot scanners
PermitRootLogin no                 # Strictly disable direct root logins
PasswordAuthentication no          # Enforce cryptographic key pairs only
PubkeyAuthentication yes
MaxAuthTries 3                     # Drop connection after 3 failed attempts
X11Forwarding no                   # Disable graphical GUI forwarding
AllowUsers deployer shivan         # Whitelist specific administrative accounts
Bash Shell Client Workstation Workflow
# 1. Generate modern high-security Ed25519 key pair
ssh-keygen -t ed25519 -C "shivan@devascentacademy.me"

# 2. Copy public key to remote production server
ssh-copy-id -i ~/.ssh/id_ed25519.pub -p 2222 deployer@203.0.113.50

# 3. Synchronize build artifacts using rsync over encrypted SSH tunnel
rsync -avzP -e "ssh -p 2222" ./dist/ deployer@203.0.113.50:/var/www/backend-api/dist/

Bash Shell Scripting & Defensive Automation

Repeated administrative workflows must be codified into deterministic scripts. A production Bash script must be written defensively: if an intermediate step fails, execution must halt immediately rather than silently proceeding to corrupt data.

The Unofficial Bash Strict Mode

Every production bash script must declare: set -euo pipefail:

Bash scripts/deploy-production.sh
#!/usr/bin/env bash

# Enforce Strict Defensive Execution
set -euo pipefail

# Script Environment Variables
readonly APP_DIR="/var/www/backend-api"
readonly BACKUP_DIR="/var/backups/api"
readonly TIMESTAMP=$(date +"%Y%m%d_%H%M%S")

# Log Helper Function
log() {
  echo "[$(date +'%Y-%m-%dT%H:%M:%S%z')] [DEPLOY] $1"
}

# Graceful Error Cleanup Trap
cleanup_on_error() {
  log "❌ DEPLOYMENT FAILED! Initiating rollback..."
  sudo systemctl restart backend-api.service || true
}
trap cleanup_on_error ERR

log "Step 1: Creating snapshot backup of current build..."
mkdir -p "${BACKUP_DIR}"
tar -czf "${BACKUP_DIR}/release_${TIMESTAMP}.tar.gz" -C "${APP_DIR}" dist/

log "Step 2: Pulling latest Git commits..."
cd "${APP_DIR}"
git fetch --all --prune
git reset --hard origin/main

log "Step 3: Deterministic dependency installation & compilation..."
npm ci --production=false
npm run build
npm prune --production

log "Step 4: Executing database migrations..."
npm run db:migrate:deploy

log "Step 5: Zero-downtime service reload..."
sudo systemctl reload-or-restart backend-api.service

log "✅ DEPLOYMENT SUCCESSFULLY COMPLETED."

Server Logs, Journald & Logrotate Architecture

Linux centralizes logging via two main mechanisms: legacy plain-text files located under /var/log/, and the binary structured journal managed by systemd-journald.

Systemd Journal Administration with Journalctl

The journalctl command queries the systemd journal database directly. Because the journal indexes metadata, logs can be queried with extreme speed:

Disk Exhaustion Prevention with Logrotate

A high-traffic service emitting 50MB of logs daily will saturate server disk capacity within weeks. The logrotate utility automates log compression, truncation, and historical deletion.

Logrotate Policy /etc/logrotate.d/backend-api
/var/log/backend-api/*.log {
    daily                      # Rotate logs every 24 hours
    missingok                  # Do not throw error if file is missing
    rotate 14                  # Keep 14 days of historical logs, delete older
    compress                   # Gzip compress rotated archives
    delaycompress              # Delay compression until second rotation cycle
    notifempty                 # Do not rotate if log file is 0 bytes
    create 0640 nodeapp nodeapp# Create new empty log with secure permissions
    sharedscripts
    postrotate
        systemctl kill -s HUP backend-api.service
    endscript
}

University & Industrial Examination Review

1. Explain the architectural distinction between User Space (Ring 3) and Kernel Space (Ring 0). Why does an application require a System Call to bind to a TCP socket?
Answer: Kernel space (Ring 0) executes with full CPU privileges and direct physical hardware memory access. User space (Ring 3) runs applications in isolated, protected virtual memory to prevent crashes or malicious memory manipulation. Because network interface cards and ports are shared hardware resources, user space applications cannot manipulate hardware registers directly. They must trigger a System Call (such as socket() and bind()) to transition privilege levels, allowing the trusted Linux kernel to validate access and allocate the network resource.
2. Differentiate between a Hard Link and a Symbolic (Soft) Link at the inode and filesystem level. What happens when the original source file is deleted in each case?
Answer: A Hard Link creates a new directory entry pointing to the exact same Inode number as the original file, incrementing the inode's link count. If the original filename is deleted, the data remains intact and accessible via the hard link until the inode link count reaches zero. A Symbolic Link creates an entirely new Inode containing a string pointer to the pathname of the target file. If the original file is deleted, the symlink remains pointing to a non-existent path, becoming a broken (dangling) link.
3. Deconstruct the permission string `-rwxr-x---`. Provide its octal value, identify the rights granted to each identity group, and explain the security risk of using `777`.
Answer: The octal value is 750. User Owner has read, write, execute (4+2+1 = 7). Group members have read and execute (4+0+1 = 5). Others have no permissions (0). Using 777 (rwxrwxrwx) allows any unprivileged user, compromised service, or container escape on the system to overwrite, inject malicious code into, or delete the file, completely violating the principle of least privilege.
4. What is a Zombie process (`Z` state)? How is it formed, does it consume RAM, and how can an administrator clear it from the process table?
Answer: A Zombie process is a terminated process whose execution has ended, but whose parent process has not yet invoked the wait() system call to read its exit status. It consumes zero CPU and zero RAM, but occupies a slot in the operating system's finite PID table. A zombie cannot be killed with kill -9 (it is already dead). To clear it, the parent process must be sent a SIGCHLD signal to read the status, or the parent process must be terminated, causing the zombie to be adopted by PID 1 (systemd), which automatically calls wait() and cleans the entry.
5. Why is `set -euo pipefail` referred to as the unofficial Bash strict mode? Detail what each flag guarantees.
Answer: By default, bash continues executing subsequent lines even if a command fails, ignores uninitialized variables, and masks pipeline errors. The flags enforce: 1. -e: Causes the script to exit immediately if any command returns a non-zero exit status. 2. -u: Causes the script to exit immediately if an undefined variable is referenced. 3. -o pipefail: Ensures that if any command inside a pipeline fails, the entire pipeline returns that non-zero failure code rather than returning 0 from a trailing successful command.