{"linux/finding-your-way-around":"\n<p class=\"learn-lead\">Linux is the operating system almost every server, container and cloud machine runs on. When you do DevOps work you are mostly typing commands into a Linux shell, often on a machine with no screen at all, so being comfortable here is the foundation for everything else.</p>\n<div class=\"learn-callout\"><b>Brand new to all of this?</b> Set up a terminal, Git, Python and Docker on your computer first: <button type=\"button\" class=\"linkish\" data-docs-topic=\"Linux\" data-docs-ch=\"10\">Start here: set up your practice machine</button>. It takes about an hour, then come back to this chapter.</div>\n<div class=\"learn-callout\"><b>Want the whole picture?</b> The <a href=\"/linux\" data-go=\"linux\">Linux path</a> takes you from here to production troubleshooting in ten stages, with a lesson for every command, the combinations engineers use every day, incident walkthroughs and a safe practice lab.</div>\n\n<h4>What \"Linux\" actually means</h4>\n<p>Strictly, Linux is the <b>kernel</b>: the core program that talks to the hardware, shares out CPU time and memory, and manages files and networking. What you install is a <b>distribution</b> (distro) such as Ubuntu, Debian, Fedora or Rocky Linux, which bundles that kernel with tools, a package manager and default settings. You interact with it through a <b>shell</b> (usually <code>bash</code>), a program that reads the commands you type and runs them.</p>\n<p>DevOps leans on Linux because it is free, stable enough to run for years without a reboot, easy to automate (everything can be done from a script), and it is what Docker containers and cloud images are built on.</p>\n\n<h4>One tree, one root</h4>\n<p>Windows gives each drive its own letter (C:, D:). Linux has a single tree that starts at <code>/</code> (called \"root\"). Extra disks, USB sticks and even information about running programs are attached somewhere inside that one tree, so every file on the system has exactly one path that starts with <code>/</code>.</p>\n{{DIAG:FS_TREE}}\n<p>The top-level folders each have a job, and knowing them tells you where to look:</p>\n<ul>\n<li><code>/etc</code> holds system-wide configuration. Nginx's settings live in <code>/etc/nginx</code>, SSH's in <code>/etc/ssh</code>.</li>\n<li><code>/home</code> has one folder per user, for example <code>/home/demee</code>. The shortcut <code>~</code> always means your own home folder.</li>\n<li><code>/var</code> is for data that changes while the system runs, most importantly logs in <code>/var/log</code>.</li>\n<li><code>/usr</code> contains installed programs and their shared files; <code>/usr/bin</code> is where most commands live.</li>\n<li><code>/tmp</code> is scratch space that gets wiped on reboot.</li>\n<li><code>/dev</code> represents hardware as files (disks show up as <code>/dev/sda</code>), and <code>/proc</code> is a virtual folder where the kernel exposes live information about processes and the system.</li>\n</ul>\n<p><b>Swap</b> is a reserved piece of disk the kernel uses as overflow memory once RAM is full. It keeps the machine alive under memory pressure, but it is far slower than real RAM.</p>\n\n<h4>Absolute and relative paths</h4>\n<p>An <b>absolute path</b> starts at the root and works from anywhere: <code>/home/demee/projects</code>. A <b>relative path</b> starts from wherever you are right now: if you are in <code>/home/demee</code>, then <code>projects</code> means the same folder. Two special names help: <code>.</code> is the current folder and <code>..</code> is the one above it.</p>\n\n<h4>Moving around</h4>\n<pre><code>$ pwd                 # where am I?\n/home/demee\n$ ls                  # what's in here?\nprojects  notes.txt  scripts\n$ cd projects         # go into a folder (relative path)\n$ cd ..               # back up one level\n$ cd /var/log         # jump anywhere with an absolute path\n$ cd                  # no argument = straight back home\n$ ls -la              # long listing, including hidden files</code></pre>\n<p><code>ls -l</code> shows one file per line with its permissions, owner, size and date; adding <code>-a</code> includes hidden files, which in Linux are simply files whose names start with a dot, like <code>.bashrc</code> or <code>.git</code>.</p>\n\n<h4>Looking inside files</h4>\n<p><code>cat file</code> prints a whole file, which is fine for short ones. For long files use <code>less file</code> (scroll with arrow keys, search with <code>/word</code>, quit with <code>q</code>). <code>head -n 20 file</code> shows the first 20 lines and <code>tail -n 20 file</code> the last 20. The one you will use constantly on servers is <code>tail -f /var/log/syslog</code>: <code>-f</code> keeps the file open and prints new lines as they are written, so you can watch a log live while you reproduce a problem.</p>\n\n<h4>Creating, copying, moving, deleting</h4>\n<pre><code>$ mkdir -p app/config        # -p creates missing parent folders too\n$ touch app/config/.env      # empty file (or refresh the timestamp)\n$ cp notes.txt backup.txt    # copy a file\n$ cp -r app app-backup       # -r copies a folder and everything in it\n$ mv backup.txt old/         # move into a folder\n$ mv draft.txt final.txt     # \"move\" in place = rename\n$ rm final.txt               # delete a file\n$ rm -r app-backup           # delete a folder and its contents</code></pre>\n<div class=\"learn-callout warn\">There is no recycle bin in the shell. <code>rm</code> is permanent, and <code>rm -rf</code> deletes without asking even when files are write-protected. Read the path twice before pressing Enter, especially with <code>sudo</code>.</div>\n<p>A <b>symbolic link</b> (<code>ln -s target linkname</code>) is a shortcut that points to another path instead of copying it. Servers use them a lot, for example Nginx enables a site by linking a file from <code>sites-available</code> into <code>sites-enabled</code>. Delete the target and the link breaks.</p>\n\n<h4>Finding things</h4>\n<p><code>find</code> walks a folder tree and matches files by name, type, size or age: <code>find /etc -name \"*.conf\"</code> lists every <code>.conf</code> file under <code>/etc</code>, and <code>find . -type f -mtime -1</code> finds files changed in the last day. To locate a command rather than a file, <code>which python3</code> prints the path of the program that would run.</p>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=aIH72Jag4Vc&amp;t=40s\" target=\"_blank\" rel=\"noopener noreferrer\">Cloud Champ · How Linux is used in DevOps <span class=\"learn-sources-part\">· Why Linux is so popular (0:40)</span></a><a href=\"https://www.youtube.com/watch?v=cBokz0LTizk&amp;t=165s\" target=\"_blank\" rel=\"noopener noreferrer\">Traversy Media · Linux Tutorial - Basic Command Line <span class=\"learn-sources-part\">· The terminal (2:45)</span></a><a href=\"https://www.youtube.com/watch?v=CLh2ACdXNbc&amp;t=144s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · 20% of Linux Commands You'll Use 80% of the Time <span class=\"learn-sources-part\">· uname, pwd, cd, ls, cat (2:24)</span></a><a href=\"https://www.youtube.com/watch?v=lCq4mYQL0WY&amp;t=71s\" target=\"_blank\" rel=\"noopener noreferrer\">Cloud Champ · Linux commands for Cloud and DevOps engineers <span class=\"learn-sources-part\">· Creating, copying and deleting files (1:11)</span></a></div>","linux/permissions-and-users":"\n<p class=\"learn-lead\">Linux is built for many users sharing one machine, so every file records who owns it and what everyone else may do with it. Most \"Permission denied\" errors you will hit on a server come down to the rules in this chapter.</p>\n\n<h4>Owner, group, others</h4>\n<p>Every file has an <b>owner</b> (a user) and a <b>group</b>. When someone tries to open a file, Linux checks them in order: if you are the owner, the owner permissions apply; otherwise if you are in the file's group, the group permissions apply; otherwise the \"others\" permissions apply. Only one set is ever used.</p>\n<p>Each set is a mix of three permissions:</p>\n<ul>\n<li><b>r</b> (read): see the contents. For a folder, list what is inside.</li>\n<li><b>w</b> (write): change the contents. For a folder, create, rename or delete files inside it.</li>\n<li><b>x</b> (execute): run the file as a program. For a folder, it means you may enter it (<code>cd</code> into it) at all.</li>\n</ul>\n\n<h4>Reading <code>ls -l</code></h4>\n<pre><code>$ ls -l deploy.sh\n-rwxr-x--- 1 demee devs 812 Sep 27 10:14 deploy.sh</code></pre>\n<p>The first character is the type (<code>-</code> file, <code>d</code> directory, <code>l</code> link). Then come three groups of three: <code>rwx</code> for the owner (demee can do everything), <code>r-x</code> for the group (members of <i>devs</i> can read and run it), and <code>---</code> for everyone else (no access at all).</p>\n<figure class=\"learn-diagram dg\" data-dg=\"ls-l\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 190\" role=\"img\" aria-label=\"ls -l output split into file type, owner rwx, group r-x and others ---, which add up to chmod 750\" style=\"--dgw:680px\"><defs><marker id=\"ls-l--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><text class=\"tc\" x=\"20\" y=\"22\" text-anchor=\"start\" font-size=\"12\">$ ls -l deploy.sh   -&gt;   -rwxr-x---  demee  devs  deploy.sh</text><rect class=\"b\" x=\"20\" y=\"40\" width=\"56\" height=\"62\" rx=\"6\"/><text class=\"tb tm\" x=\"48\" y=\"69.9\" text-anchor=\"middle\" font-size=\"20\">-</text><text class=\"t2\" x=\"48\" y=\"86.5\" text-anchor=\"middle\" font-size=\"11\">type</text><rect class=\"b hi\" x=\"86\" y=\"40\" width=\"124\" height=\"62\" rx=\"6\"/><text class=\"tb ta tm\" x=\"148\" y=\"69.9\" text-anchor=\"middle\" font-size=\"20\">rwx</text><text class=\"t2\" x=\"148\" y=\"86.5\" text-anchor=\"middle\" font-size=\"11\">owner: demee</text><rect class=\"b\" x=\"220\" y=\"40\" width=\"124\" height=\"62\" rx=\"6\"/><text class=\"tb tm\" x=\"282\" y=\"69.9\" text-anchor=\"middle\" font-size=\"20\">r-x</text><text class=\"t2\" x=\"282\" y=\"86.5\" text-anchor=\"middle\" font-size=\"11\">group: devs</text><rect class=\"b\" x=\"354\" y=\"40\" width=\"124\" height=\"62\" rx=\"6\"/><text class=\"tb tm\" x=\"416\" y=\"69.9\" text-anchor=\"middle\" font-size=\"20\">---</text><text class=\"t2\" x=\"416\" y=\"86.5\" text-anchor=\"middle\" font-size=\"11\">everyone else</text><rect class=\"b ok\" x=\"522\" y=\"40\" width=\"140\" height=\"62\" rx=\"6\"/><text class=\"tb\" x=\"592\" y=\"68.3\" text-anchor=\"middle\" font-size=\"15\">chmod 750</text><text class=\"t2\" x=\"592\" y=\"84.0\" text-anchor=\"middle\" font-size=\"11\">= rwxr-x---</text><path class=\"ln\" d=\"M480,71 L520,71\" marker-end=\"url(#ls-l--n)\"/><text class=\"t2\" x=\"48\" y=\"126\" text-anchor=\"middle\" font-size=\"12\">file</text><text class=\"ta tb\" x=\"148\" y=\"126\" text-anchor=\"middle\" font-size=\"12\">4+2+1 = 7</text><text class=\"tb\" x=\"282\" y=\"126\" text-anchor=\"middle\" font-size=\"12\">4+0+1 = 5</text><text class=\"tb\" x=\"416\" y=\"126\" text-anchor=\"middle\" font-size=\"12\">0+0+0 = 0</text><text class=\"t2\" x=\"340\" y=\"166\" text-anchor=\"middle\" font-size=\"12\">r = 4   w = 2   x = 1   - = 0   (add them up per group)</text></svg></div><figcaption>Read the ten characters as 1 + 3 + 3 + 3. Each group of three is a sum of <code>r=4</code>, <code>w=2</code>, <code>x=1</code>, which is where numbers like <code>750</code> come from.</figcaption></figure>\n\n\n<h4>Changing permissions with <code>chmod</code></h4>\n<p>The numeric form is the one you will see in tutorials and exams. Each permission has a value: read = 4, write = 2, execute = 1. Add them up for each of owner, group and others, and you get three digits.</p>\n<pre><code>$ chmod 755 deploy.sh   # 7=rwx owner, 5=r-x group, 5=r-x others\n$ chmod 644 notes.txt   # 6=rw- owner, 4=r-- group, 4=r-- others\n$ chmod 600 ~/.ssh/id_ed25519   # private key: only you can read or write it\n$ chmod +x script.sh    # just add execute, leave the rest alone\n$ chmod -R g+w shared/  # give the group write access, recursively</code></pre>\n<p><code>755</code> is the usual setting for scripts and folders, <code>644</code> for ordinary files, and <code>600</code> for secrets. Play with the calculator to see how the digits and letters line up:</p>\n<div class=\"chmod-calc\" id=\"chmodCalc\"><div class=\"chmod-calc-title\" data-i18n=\"chmod_try_it\">Try it: chmod calculator</div><div class=\"chmod-calc-grid\"><div class=\"chmod-calc-col\"><div class=\"chmod-calc-role\">Owner</div><label><input type=\"checkbox\" data-role=\"owner\" data-perm=\"r\" checked> Read (4)</label><label><input type=\"checkbox\" data-role=\"owner\" data-perm=\"w\" checked> Write (2)</label><label><input type=\"checkbox\" data-role=\"owner\" data-perm=\"x\"> Execute (1)</label></div><div class=\"chmod-calc-col\"><div class=\"chmod-calc-role\">Group</div><label><input type=\"checkbox\" data-role=\"group\" data-perm=\"r\" checked> Read (4)</label><label><input type=\"checkbox\" data-role=\"group\" data-perm=\"w\"> Write (2)</label><label><input type=\"checkbox\" data-role=\"group\" data-perm=\"x\"> Execute (1)</label></div><div class=\"chmod-calc-col\"><div class=\"chmod-calc-role\">Others</div><label><input type=\"checkbox\" data-role=\"others\" data-perm=\"r\" checked> Read (4)</label><label><input type=\"checkbox\" data-role=\"others\" data-perm=\"w\"> Write (2)</label><label><input type=\"checkbox\" data-role=\"others\" data-perm=\"x\"> Execute (1)</label></div></div><div class=\"chmod-calc-result\"><span class=\"chmod-calc-octal\" id=\"chmodOctal\">644</span><span class=\"chmod-calc-symbolic\" id=\"chmodSymbolic\">-rw-r--r--</span></div><div class=\"chmod-calc-cmd\">$ chmod <span id=\"chmodOctalInline\">644</span> file</div><div class=\"chmod-calc-reverse\"><label for=\"chmodReverseInput\" data-i18n=\"chmod_or_type\">Or type a number:</label><input type=\"text\" id=\"chmodReverseInput\" maxlength=\"3\" inputmode=\"numeric\" placeholder=\"755\" value=\"644\"></div></div>\n\n<h4>Users, groups and ownership</h4>\n<p>Accounts are listed in <code>/etc/passwd</code> (name, user ID, home folder, login shell); the password hashes are kept separately in <code>/etc/shadow</code>, which only root can read. Groups let you give several people the same access without listing each one.</p>\n<pre><code>$ sudo adduser deploy              # new user with a home folder\n$ sudo usermod -aG sudo deploy     # add to the sudo group (-a = append, don't replace)\n$ sudo chown deploy:deploy /srv/app   # new owner:group\n$ sudo chown -R www-data /var/www     # recursively\n$ id deploy                        # which groups is deploy in?\n$ passwd                           # change your own password</code></pre>\n<div class=\"learn-callout warn\">Forgetting <code>-a</code> in <code>usermod -aG</code> replaces all the user's groups instead of adding one, which can lock them out of <code>sudo</code>.</div>\n\n<h4>root, <code>sudo</code> and <code>su</code></h4>\n<p><b>root</b> is the superuser: permissions don't apply to it, so it can read, change or delete anything. Working as root all the time is dangerous because one typo can destroy the system, which is why servers are normally set up with a regular user that borrows root powers only when needed.</p>\n<p><code>sudo command</code> runs one command as root after asking for <i>your own</i> password, and it logs what you did. <code>su username</code> switches your whole shell to another user and needs <i>their</i> password. In practice you use <code>sudo</code> for everything, and on many cloud servers root login is disabled entirely.</p>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=CLh2ACdXNbc&amp;t=1260s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · 20% of Linux Commands You'll Use 80% of the Time <span class=\"learn-sources-part\">· chmod (21:00)</span></a><a href=\"https://www.youtube.com/watch?v=7aRjGIhwyQM&amp;t=681s\" target=\"_blank\" rel=\"noopener noreferrer\">Traversy Media · Linux Server Setup & MERN Deployment <span class=\"learn-sources-part\">· Creating a sudo user on a server (11:21)</span></a><a href=\"https://www.youtube.com/watch?v=lCq4mYQL0WY&amp;t=2730s\" target=\"_blank\" rel=\"noopener noreferrer\">Cloud Champ · Linux commands for Cloud and DevOps engineers <span class=\"learn-sources-part\">· sudo and root (45:30)</span></a></div>","linux/processes-and-services":"\n<p class=\"learn-lead\">Every running program is a process. Servers are mostly long-running processes (web servers, databases, your app) that need to start on boot, restart when they crash and be stopped cleanly, and Linux has tools for each of those jobs.</p>\n\n<h4>What a process is</h4>\n<p>When you run a command, the kernel creates a <b>process</b>: a running copy of that program with its own memory, open files and a unique number called the <b>PID</b> (process ID). Every process is started by another one, its parent, so they form a tree. At the very top is PID 1, which on modern systems is <code>systemd</code>, the program that boots the system and supervises services.</p>\n{{DIAG:PROC_TREE}}\n\n<h4>Seeing what is running</h4>\n<pre><code>$ ps aux                     # snapshot of every process\n$ ps aux | grep nginx        # just the nginx ones\n$ top                        # live view, sorted by CPU (q to quit)\n$ htop                       # friendlier live view, if installed\n$ free -h                    # memory used / free\n$ uptime                     # running time + load average</code></pre>\n<p>In <code>ps aux</code> the useful columns are USER, PID, %CPU, %MEM and COMMAND. The <b>load average</b> in <code>uptime</code> (three numbers: last 1, 5 and 15 minutes) is roughly how many processes were waiting for CPU. Compare it with the number of CPU cores: a load of 4 on a 4-core machine means it is fully busy.</p>\n\n<h4>Stopping processes: signals</h4>\n<p>You don't really \"kill\" a process, you send it a <b>signal</b>. <code>kill PID</code> sends <b>SIGTERM</b> (15), a polite request: the program can finish writing files, close connections and exit cleanly. <code>kill -9 PID</code> sends <b>SIGKILL</b>, which the kernel enforces immediately and the program can't catch, so nothing gets cleaned up. Always try the polite one first; use <code>-9</code> only for something that's stuck. <code>pkill nginx</code> signals processes by name instead of number, and Ctrl+C in a terminal sends SIGINT to whatever is running in the foreground.</p>\n\n<h4>Foreground and background</h4>\n<p>A normal command holds your terminal until it finishes. Add <code>&amp;</code> to run it in the background (<code>./long-task.sh &amp;</code>), see background jobs with <code>jobs</code> and bring one back with <code>fg</code>. Background jobs still die when you close the SSH session; <code>nohup command &amp;</code> keeps them running, but for anything that should stay up permanently you want a service.</p>\n\n<h4>Services with systemd</h4>\n<p>A <b>service</b> (or daemon) is a background program that systemd starts, watches and restarts. Each one is described by a unit file, for example <code>/etc/systemd/system/myapp.service</code>, which says which command to run, as which user, and what to do if it crashes.</p>\n<pre><code>$ sudo systemctl status nginx     # running? recent log lines?\n$ sudo systemctl start nginx      # start now\n$ sudo systemctl stop nginx       # stop now\n$ sudo systemctl restart nginx    # stop + start (after config changes)\n$ sudo systemctl reload nginx     # re-read config without dropping connections\n$ sudo systemctl enable nginx     # start automatically on every boot\n$ sudo systemctl disable nginx    # don't start on boot\n$ journalctl -u nginx -f          # that service's logs, live</code></pre>\n<div class=\"learn-callout\"><code>start</code> and <code>enable</code> are different things: <code>start</code> affects right now, <code>enable</code> affects the next boot. A fresh install usually needs both (<code>systemctl enable --now nginx</code> does both at once).</div>\n<p>For Node.js apps you'll also meet <b>PM2</b>, a process manager that keeps the app running, restarts it on crash and can register itself with systemd, which is what the Traversy server-setup video uses.</p>\n\n<h4>Scheduled jobs with cron</h4>\n<p><b>cron</b> runs commands on a schedule. <code>crontab -e</code> opens your list of jobs; each line has five time fields followed by the command:</p>\n<pre><code># minute  hour  day-of-month  month  day-of-week  command\n0 3 * * *     /home/demee/backup.sh        # every day at 03:00\n*/15 * * * *  /usr/local/bin/healthcheck   # every 15 minutes\n0 9 * * 1     /home/demee/report.sh        # Mondays at 09:00</code></pre>\n<p><code>*</code> means \"every\", and <code>*/15</code> means \"every 15th\". Cron jobs run with a minimal environment, so use full paths in them.</p>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=cBokz0LTizk&amp;t=1027s\" target=\"_blank\" rel=\"noopener noreferrer\">Traversy Media · Linux Tutorial - Basic Command Line <span class=\"learn-sources-part\">· top (17:07)</span></a><a href=\"https://www.youtube.com/watch?v=7aRjGIhwyQM&amp;t=1760s\" target=\"_blank\" rel=\"noopener noreferrer\">Traversy Media · Linux Server Setup & MERN Deployment <span class=\"learn-sources-part\">· Keeping an app running with PM2 (29:20)</span></a><a href=\"https://www.youtube.com/watch?v=GzIFoJBVwh8&amp;t=183s\" target=\"_blank\" rel=\"noopener noreferrer\">edureka! · Linux Commands for DevOps <span class=\"learn-sources-part\">· Linux commands for DevOps (3:03)</span></a></div>","linux/packages-disks-and-archives":"\n<p class=\"learn-lead\">Setting up a server is mostly installing software, keeping an eye on disk space and moving files around in bundles. These are the everyday housekeeping commands.</p>\n\n<h4>Package managers</h4>\n<p>Instead of downloading installers from websites, Linux installs software from <b>repositories</b>: trusted online collections of packages maintained by the distro. A <b>package manager</b> downloads the package, installs its dependencies automatically, and can update or remove everything cleanly later. Which one you use depends on the distro family:</p>\n<ul>\n<li><code>apt</code> on Debian and Ubuntu (<code>.deb</code> packages)</li>\n<li><code>dnf</code> (older: <code>yum</code>) on Fedora, Red Hat, Rocky and Amazon Linux (<code>.rpm</code> packages)</li>\n</ul>\n<pre><code>$ sudo apt update            # refresh the list of available versions (installs nothing)\n$ sudo apt upgrade           # install newer versions of what you already have\n$ sudo apt install nginx git # install packages (dependencies come along)\n$ sudo apt remove nginx      # uninstall\n$ apt search postgres        # look for a package\n$ apt list --installed       # what's on this machine</code></pre>\n<div class=\"learn-callout\">Run <code>apt update</code> before installing on a fresh server. Without it, apt works from an old list and can fail to find packages or install outdated versions.</div>\n<p>Some tools aren't in the default repositories. Then you add the vendor's repository first (Node.js and Docker both document this), or install a language's own package manager like <code>pip</code> for Python or <code>npm</code> for Node.</p>\n\n<h4>Disk space</h4>\n<p>A full disk is one of the most common causes of mysterious failures: databases stop writing, logs stop, apps crash. Two commands answer the two questions you'll have:</p>\n<pre><code>$ df -h              # how full is each disk? (-h = human-readable sizes)\nFilesystem  Size  Used Avail Use% Mounted on\n/dev/sda1    25G   23G  2.0G  92% /\n\n$ du -sh /var/log    # how big is this one folder?\n$ du -sh /var/* | sort -h   # which folder is the culprit?</code></pre>\n<p><code>df</code> looks at whole filesystems; <code>du</code> adds up the files inside a folder. Logs in <code>/var/log</code> and old Docker images are the usual suspects. Attaching a new disk means <b>mounting</b> it onto a folder (<code>mount /dev/sdb1 /mnt/data</code>); to make that permanent it goes into <code>/etc/fstab</code>.</p>\n\n<h4>Archives and compression</h4>\n<p><code>tar</code> bundles many files into one archive; add <code>z</code> and it's also compressed with gzip, giving a <code>.tar.gz</code> file. Backups and software downloads use this constantly.</p>\n<figure class=\"learn-diagram dg\" data-dg=\"tar-gz\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 660 170\" role=\"img\" aria-label=\"tar bundles a folder into one .tar file, gzip then compresses it into .tar.gz\" style=\"--dgw:660px\"><defs><marker id=\"tar-gz--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"g\" x=\"10\" y=\"20\" width=\"170\" height=\"130\" rx=\"8\"/><text class=\"tg \" x=\"20\" y=\"36\" font-size=\"11\">app/</text><rect class=\"b\" x=\"26\" y=\"44\" width=\"138\" height=\"28\" rx=\"6\"/><text class=\"tm\" x=\"95\" y=\"61.8\" text-anchor=\"middle\" font-size=\"12\">app.py</text><rect class=\"b\" x=\"26\" y=\"78\" width=\"138\" height=\"28\" rx=\"6\"/><text class=\"tm\" x=\"95\" y=\"95.8\" text-anchor=\"middle\" font-size=\"12\">config.yml</text><rect class=\"b\" x=\"26\" y=\"112\" width=\"138\" height=\"28\" rx=\"6\"/><text class=\"tm\" x=\"95\" y=\"129.8\" text-anchor=\"middle\" font-size=\"12\">static/</text><rect class=\"b\" x=\"250\" y=\"50\" width=\"150\" height=\"70\" rx=\"6\"/><text class=\"tb\" x=\"325\" y=\"81.7\" text-anchor=\"middle\" font-size=\"13\">backup.tar</text><text class=\"t2\" x=\"325\" y=\"97.0\" text-anchor=\"middle\" font-size=\"11\">one file, same size</text><rect class=\"b ok\" x=\"470\" y=\"50\" width=\"170\" height=\"70\" rx=\"6\"/><text class=\"tb\" x=\"555\" y=\"81.7\" text-anchor=\"middle\" font-size=\"13\">backup.tar.gz</text><text class=\"t2\" x=\"555\" y=\"97.0\" text-anchor=\"middle\" font-size=\"11\">one file, smaller</text><path class=\"ln\" d=\"M182,85 L248,85\" marker-end=\"url(#tar-gz--n)\"/><text class=\"tl\" x=\"215\" y=\"76\" text-anchor=\"middle\" font-size=\"11\">tar -c</text><path class=\"ln\" d=\"M402,85 L468,85\" marker-end=\"url(#tar-gz--n)\"/><text class=\"tl\" x=\"435\" y=\"78\" text-anchor=\"middle\" font-size=\"11\">+ z (gzip)</text><text class=\"t2\" x=\"330\" y=\"160\" text-anchor=\"middle\" font-size=\"12\">tar -czvf does both steps; tar -xzvf undoes them</text></svg></div><figcaption><code>tar</code> bundles, <code>gzip</code> shrinks. The <code>z</code> in <code>-czvf</code> asks tar to do the gzip step for you.</figcaption></figure>\n\n<pre><code>$ tar -czvf backup.tar.gz app/    # c=create, z=gzip, v=list files, f=filename\n$ tar -tzvf backup.tar.gz         # t=list what's inside without extracting\n$ tar -xzvf backup.tar.gz         # x=extract into the current folder\n$ tar -xzvf backup.tar.gz -C /srv # extract somewhere else\n$ zip -r site.zip site/ ; unzip site.zip</code></pre>\n<p>A handy way to remember the letters: <b>c</b>reate, e<b>x</b>tract, lis<b>t</b>; <b>z</b> for gzip; <b>f</b> must come last because the filename follows it.</p>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=lCq4mYQL0WY&amp;t=1380s\" target=\"_blank\" rel=\"noopener noreferrer\">Cloud Champ · Linux commands for Cloud and DevOps engineers <span class=\"learn-sources-part\">· Installing packages (23:00)</span></a><a href=\"https://www.youtube.com/watch?v=cBokz0LTizk&amp;t=1060s\" target=\"_blank\" rel=\"noopener noreferrer\">Traversy Media · Linux Tutorial - Basic Command Line <span class=\"learn-sources-part\">· Disk space and package managers (17:40)</span></a><a href=\"https://www.youtube.com/watch?v=7aRjGIhwyQM&amp;t=618s\" target=\"_blank\" rel=\"noopener noreferrer\">Traversy Media · Linux Server Setup & MERN Deployment <span class=\"learn-sources-part\">· Updating a fresh server (10:18)</span></a></div>","linux/text-tools-pipes-redirection":"\n<p class=\"learn-lead\">Linux commands are small tools that each do one thing well, and the real power comes from chaining them together. Logs, config files and command output are all just text, so a handful of text tools lets you answer almost any question about a server.</p>\n\n<h4>Input, output and errors</h4>\n<figure class=\"learn-diagram dg\" data-dg=\"streams\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 250\" role=\"img\" aria-label=\"A command has three channels: stdin 0 comes in, stdout 1 and stderr 2 go out, each can be redirected to a file\" style=\"--dgw:680px\"><defs><marker id=\"streams--bad\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk bad\" d=\"M0,0 L8,4 L0,8 z\"/></marker><marker id=\"streams--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"b\" x=\"10\" y=\"92\" width=\"160\" height=\"52\" rx=\"6\"/><text class=\"tb\" x=\"90\" y=\"114.7\" text-anchor=\"middle\" font-size=\"13\">keyboard</text><text class=\"t2\" x=\"90\" y=\"130.0\" text-anchor=\"middle\" font-size=\"11\">or a file: &lt; in.txt</text><rect class=\"b hi\" x=\"260\" y=\"82\" width=\"160\" height=\"72\" rx=\"6\"/><text class=\"tb ta\" x=\"340\" y=\"115.0\" text-anchor=\"middle\" font-size=\"14\">./deploy.sh</text><text class=\"t2\" x=\"340\" y=\"130.5\" text-anchor=\"middle\" font-size=\"11\">a running command</text><rect class=\"b\" x=\"520\" y=\"30\" width=\"150\" height=\"52\" rx=\"6\"/><text class=\"tb\" x=\"595\" y=\"52.7\" text-anchor=\"middle\" font-size=\"13\">screen</text><text class=\"t2\" x=\"595\" y=\"68.0\" text-anchor=\"middle\" font-size=\"11\">or: &gt; out.log</text><rect class=\"b bad\" x=\"520\" y=\"150\" width=\"150\" height=\"52\" rx=\"6\"/><text class=\"tb\" x=\"595\" y=\"172.7\" text-anchor=\"middle\" font-size=\"13\">screen</text><text class=\"t2\" x=\"595\" y=\"188.0\" text-anchor=\"middle\" font-size=\"11\">or: 2&gt; errors.txt</text><path class=\"ln\" d=\"M172,118 L258,118\" marker-end=\"url(#streams--n)\"/><text class=\"tl\" x=\"215\" y=\"111\" text-anchor=\"middle\" font-size=\"11\">0  stdin</text><path class=\"ln\" d=\"M422,104 L476,104 L476,56 L518,56\" marker-end=\"url(#streams--n)\"/><text class=\"tl tb\" x=\"476\" y=\"40\" text-anchor=\"middle\" font-size=\"11\">1  stdout</text><path class=\"ln bad\" d=\"M422,134 L476,134 L476,176 L518,176\" marker-end=\"url(#streams--bad)\"/><text class=\"bad tb\" x=\"476\" y=\"200\" text-anchor=\"middle\" font-size=\"11\">2  stderr</text><text class=\"t2\" x=\"340\" y=\"236\" text-anchor=\"middle\" font-size=\"12\">2&gt;&amp;1 means: send 2 to wherever 1 is going right now</text></svg></div><figcaption>Three numbered channels. Redirection only changes where a number points: <code>&gt;</code> moves 1, <code>2&gt;</code> moves 2, and <code>2&gt;&amp;1</code> joins 2 to 1.</figcaption></figure>\n\n<p>Every command has three channels: <b>stdin</b> (input, usually your keyboard), <b>stdout</b> (normal output, usually your screen) and <b>stderr</b> (error messages, also the screen, but a separate channel). Redirection reroutes them:</p>\n<pre><code>$ ls > files.txt          # stdout into a file (overwrites it)\n$ echo \"done\" >> log.txt  # append instead of overwrite\n$ ./deploy.sh 2> errors.txt        # only the errors into a file\n$ ./deploy.sh > all.log 2>&amp;1      # errors into the same place as output\n$ ./noisy.sh > /dev/null           # throw output away</code></pre>\n<p><code>2&gt;&amp;1</code> reads as \"send channel 2 (errors) to wherever channel 1 (output) is going\". <code>/dev/null</code> is a special file that swallows everything written to it.</p>\n\n<h4>Pipes</h4>\n<p>The pipe <code>|</code> sends one command's output straight into the next command's input, so you build answers step by step:</p>\n<pre><code>$ ps aux | grep nginx                       # only nginx processes\n$ cat access.log | wc -l                    # how many requests?\n$ grep \" 500 \" access.log | wc -l           # how many were server errors?\n$ cut -d' ' -f1 access.log | sort | uniq -c | sort -rn | head\n#   ↑ which IP addresses hit us most often</code></pre>\n<p>Read that last line left to right: take the first space-separated field (the IP) from each line, sort them so duplicates sit together, count each group with <code>uniq -c</code>, sort by that count biggest first, show the top ten.</p>\n\n\n<figure class=\"learn-diagram dg\" data-dg=\"pipes\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 700 150\" role=\"img\" aria-label=\"A pipeline: cut takes the IP from each log line, sort groups them, uniq -c counts, sort -rn ranks, head keeps the top 10\" style=\"--dgw:700px\"><defs><marker id=\"pipes--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"b\" x=\"10\" y=\"40\" width=\"150\" height=\"52\" rx=\"6\"/><text class=\"tb tm\" x=\"85\" y=\"62.3\" text-anchor=\"middle\" font-size=\"12\">cut -d&#x27; &#x27; -f1</text><text class=\"t2\" x=\"85\" y=\"77.5\" text-anchor=\"middle\" font-size=\"11\">take the IP</text><rect class=\"b\" x=\"196\" y=\"40\" width=\"80\" height=\"52\" rx=\"6\"/><text class=\"tb tm\" x=\"236\" y=\"62.7\" text-anchor=\"middle\" font-size=\"13\">sort</text><text class=\"t2\" x=\"236\" y=\"78.0\" text-anchor=\"middle\" font-size=\"11\">group</text><rect class=\"b\" x=\"312\" y=\"40\" width=\"110\" height=\"52\" rx=\"6\"/><text class=\"tb tm\" x=\"367\" y=\"62.7\" text-anchor=\"middle\" font-size=\"13\">uniq -c</text><text class=\"t2\" x=\"367\" y=\"78.0\" text-anchor=\"middle\" font-size=\"11\">count each</text><rect class=\"b\" x=\"458\" y=\"40\" width=\"100\" height=\"52\" rx=\"6\"/><text class=\"tb tm\" x=\"508\" y=\"62.7\" text-anchor=\"middle\" font-size=\"13\">sort -rn</text><text class=\"t2\" x=\"508\" y=\"78.0\" text-anchor=\"middle\" font-size=\"11\">biggest 1st</text><rect class=\"b hi\" x=\"594\" y=\"40\" width=\"96\" height=\"52\" rx=\"6\"/><text class=\"tb ta tm\" x=\"642\" y=\"62.7\" text-anchor=\"middle\" font-size=\"13\">head</text><text class=\"t2\" x=\"642\" y=\"78.0\" text-anchor=\"middle\" font-size=\"11\">top 10</text><path class=\"ln\" d=\"M162,66 L194,66\" marker-end=\"url(#pipes--n)\"/><path class=\"ln\" d=\"M278,66 L310,66\" marker-end=\"url(#pipes--n)\"/><path class=\"ln\" d=\"M424,66 L456,66\" marker-end=\"url(#pipes--n)\"/><path class=\"ln\" d=\"M560,66 L592,66\" marker-end=\"url(#pipes--n)\"/><text class=\"t2\" x=\"350\" y=\"124\" text-anchor=\"middle\" font-size=\"12\">each | feeds one command&#x27;s output into the next command&#x27;s input</text></svg></div><figcaption>Read a pipeline left to right. No temporary files: the text flows from one small tool into the next.</figcaption></figure>\n<h4>grep: finding lines</h4>\n<pre><code>$ grep \"error\" app.log          # lines containing \"error\"\n$ grep -i \"error\" app.log       # case-insensitive\n$ grep -n \"timeout\" app.log     # show line numbers\n$ grep -v \"DEBUG\" app.log       # lines that DON'T match\n$ grep -r \"DB_HOST\" /etc/myapp  # search every file in a folder\n$ grep -c \"404\" access.log      # just count matches</code></pre>\n\n<h4>Sorting, counting, cutting</h4>\n<ul>\n<li><code>wc -l</code> counts lines (<code>-w</code> words, <code>-c</code> bytes).</li>\n<li><code>sort</code> sorts lines; <code>-n</code> numerically, <code>-r</code> reversed, <code>-h</code> understands sizes like 2G.</li>\n<li><code>uniq</code> collapses repeated neighbouring lines (so sort first); <code>-c</code> counts them.</li>\n<li><code>cut -d',' -f2</code> takes the 2nd comma-separated column.</li>\n<li><code>awk '{print $1, $9}'</code> prints chosen whitespace-separated columns, handy for logs.</li>\n<li><code>sed 's/old/new/g' file</code> finds and replaces; <code>sed -i</code> edits the file in place.</li>\n<li><code>diff a b</code> shows which lines differ between two files.</li>\n<li><code>xargs</code> turns input lines into arguments: <code>find . -name \"*.tmp\" | xargs rm</code>.</li>\n</ul>\n\n<h4>Environment variables and PATH</h4>\n<p>An <b>environment variable</b> is a named value that programs can read, which is how apps get settings like database addresses and API keys without hard-coding them. <code>export DB_HOST=10.0.0.5</code> sets one for the current shell and anything it starts; <code>echo $DB_HOST</code> reads it; <code>env</code> lists them all. Put exports in <code>~/.bashrc</code> to set them on every login.</p>\n<p><code>PATH</code> is the variable listing the folders the shell searches when you type a command name. \"command not found\" usually means the program isn't installed or its folder isn't in <code>PATH</code>.</p>\n<p>Your shell also remembers what you typed: <code>history</code> lists it, <code>!!</code> repeats the last command (<code>sudo !!</code> reruns it with sudo), and Ctrl+R searches back through it.</p>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=CLh2ACdXNbc&amp;t=381s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · 20% of Linux Commands You'll Use 80% of the Time <span class=\"learn-sources-part\">· grep (6:21)</span></a><a href=\"https://www.youtube.com/watch?v=CLh2ACdXNbc&amp;t=610s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · 20% of Linux Commands You'll Use 80% of the Time <span class=\"learn-sources-part\">· wc and find (10:10)</span></a><a href=\"https://www.youtube.com/watch?v=lCq4mYQL0WY&amp;t=2520s\" target=\"_blank\" rel=\"noopener noreferrer\">Cloud Champ · Linux commands for Cloud and DevOps engineers <span class=\"learn-sources-part\">· history and PATH (42:00)</span></a></div>","linux/remote-servers-ssh":"\n<p class=\"learn-lead\">Real servers live in a data centre or the cloud, so you manage them remotely. This chapter follows what the Traversy \"Linux Server Setup\" video does step by step: create a server, log in securely with keys, lock it down, and put a web app behind Nginx with HTTPS.</p>\n\n<h4>How SSH works</h4>\n<p><b>SSH</b> (Secure Shell) gives you a terminal on another machine over an encrypted connection. The server runs an SSH daemon (<code>sshd</code>) listening on port <b>22</b>; your laptop runs the client, <code>ssh</code>. Everything you type and everything the server prints travels encrypted, so nobody in between can read it.</p>\n<pre><code>$ ssh demee@203.0.113.10          # user@server-address\n$ ssh -i ~/.ssh/work_key demee@server   # use a specific key\n$ exit                            # leave the remote shell</code></pre>\n\n<h4>Key pairs instead of passwords</h4>\n<p>Passwords can be guessed, and servers on the internet get thousands of guessing attempts a day. SSH keys fix that. <code>ssh-keygen</code> creates a pair of matching keys:</p>\n<ul>\n<li>the <b>private key</b> (<code>~/.ssh/id_ed25519</code>) stays on your laptop and is never shared;</li>\n<li>the <b>public key</b> (<code>~/.ssh/id_ed25519.pub</code>) is copied to every server you want to log in to, into <code>~/.ssh/authorized_keys</code>.</li>\n</ul>\n<p>When you connect, the server sends a challenge that only the matching private key can answer. Your private key never leaves your machine, so there is nothing to guess or steal from the network.</p>\n<pre><code>$ ssh-keygen -t ed25519 -C \"demee laptop\"   # make the pair (Enter for defaults)\n$ ssh-copy-id demee@203.0.113.10             # install the public key on the server\n$ ssh demee@203.0.113.10                     # now logs in without a password</code></pre>\n<p>GitHub uses exactly the same idea: you paste your <i>public</i> key into GitHub's settings so <code>git push</code> can authenticate you.</p>\n\n\n<figure class=\"learn-diagram dg\" data-dg=\"ssh-keys\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 270\" role=\"img\" aria-label=\"SSH key login: the laptop keeps the private key, the server has the public key, the server sends a challenge that only the private key can answer\" style=\"--dgw:680px\"><defs><marker id=\"ssh-keys--hi\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk hi\" d=\"M0,0 L8,4 L0,8 z\"/></marker><marker id=\"ssh-keys--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker><marker id=\"ssh-keys--ok\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk ok\" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"g hi\" x=\"10\" y=\"14\" width=\"220\" height=\"240\" rx=\"8\"/><text class=\"tg hi\" x=\"20\" y=\"30\" font-size=\"11\">your laptop</text><rect class=\"g\" x=\"450\" y=\"14\" width=\"220\" height=\"240\" rx=\"8\"/><text class=\"tg \" x=\"460\" y=\"30\" font-size=\"11\">server</text><rect class=\"b hi\" x=\"26\" y=\"44\" width=\"188\" height=\"58\" rx=\"6\"/><text class=\"tb ta\" x=\"120\" y=\"63.2\" text-anchor=\"middle\" font-size=\"13\">private key</text><text class=\"t2\" x=\"120\" y=\"77.7\" text-anchor=\"middle\" font-size=\"10\">~/.ssh/id_ed25519</text><text class=\"t2\" x=\"120\" y=\"91.7\" text-anchor=\"middle\" font-size=\"10\">never leaves</text><rect class=\"b\" x=\"466\" y=\"44\" width=\"188\" height=\"58\" rx=\"6\"/><text class=\"tb\" x=\"560\" y=\"63.2\" text-anchor=\"middle\" font-size=\"13\">public key</text><text class=\"t2\" x=\"560\" y=\"77.7\" text-anchor=\"middle\" font-size=\"10\">in ~/.ssh/</text><text class=\"t2\" x=\"560\" y=\"91.7\" text-anchor=\"middle\" font-size=\"10\">authorized_keys</text><path class=\"ln\" d=\"M232,124 L448,124\" marker-end=\"url(#ssh-keys--n)\"/><text class=\"tl\" x=\"340\" y=\"118\" text-anchor=\"middle\" font-size=\"11\">1  ssh demee@server</text><path class=\"ln\" d=\"M448,160 L232,160\" marker-end=\"url(#ssh-keys--n)\"/><text class=\"tl\" x=\"340\" y=\"154\" text-anchor=\"middle\" font-size=\"11\">2  a random challenge</text><path class=\"ln hi\" d=\"M232,196 L448,196\" marker-end=\"url(#ssh-keys--hi)\"/><text class=\"ta\" x=\"340\" y=\"190\" text-anchor=\"middle\" font-size=\"11\">3  answer signed with private key</text><path class=\"ln ok\" d=\"M448,232 L232,232\" marker-end=\"url(#ssh-keys--ok)\"/><text class=\"tl\" x=\"340\" y=\"226\" text-anchor=\"middle\" font-size=\"11\">4  checks it with public key: in</text></svg></div><figcaption>Nothing secret crosses the network. The server only ever sees the signed answer, and the public key is useless to anyone who copies it.</figcaption></figure>\n<h4>First things to do on a new server</h4>\n<ol>\n<li><b>Update it:</b> <code>sudo apt update &amp;&amp; sudo apt upgrade</code>.</li>\n<li><b>Create a normal user</b> and give it sudo, so you stop working as root: <code>adduser demee</code>, <code>usermod -aG sudo demee</code>, then copy your public key into that user's <code>~/.ssh/authorized_keys</code>.</li>\n<li><b>Turn off password logins</b> and root login in <code>/etc/ssh/sshd_config</code>: set <code>PasswordAuthentication no</code> and <code>PermitRootLogin no</code>, then <code>sudo systemctl restart ssh</code>. Test a new key login in a second terminal before closing the first one, so you can't lock yourself out.</li>\n<li><b>Turn on a firewall</b> that only lets in what you need:</li>\n</ol>\n<pre><code>$ sudo ufw allow OpenSSH     # keep SSH open first!\n$ sudo ufw allow 80          # HTTP\n$ sudo ufw allow 443         # HTTPS\n$ sudo ufw enable\n$ sudo ufw status</code></pre>\n\n<h4>Copying files to and from servers</h4>\n<pre><code>$ scp app.tar.gz demee@server:/srv/        # copy up\n$ scp demee@server:/var/log/app.log .      # copy down\n$ rsync -avz site/ demee@server:/var/www/  # sync a folder, only sending changes</code></pre>\n\n<h4>Serving an app: Nginx as a reverse proxy</h4>\n<p>Your app (say a Node server on port 5000) shouldn't face the internet directly. Instead <b>Nginx</b> listens on ports 80/443 and forwards requests to the app. That is a <b>reverse proxy</b>: visitors only ever talk to Nginx, which also handles HTTPS, compression and serving static files efficiently.</p>\n<figure class=\"learn-diagram dg\" data-dg=\"nginx-proxy\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 180\" role=\"img\" aria-label=\"A browser talks to Nginx on port 80 or 443, Nginx forwards the request to the app on localhost:5000\" style=\"--dgw:680px\"><defs><marker id=\"nginx-proxy--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"b\" x=\"10\" y=\"64\" width=\"130\" height=\"52\" rx=\"6\"/><text class=\"tb\" x=\"75\" y=\"86.7\" text-anchor=\"middle\" font-size=\"13\">browser</text><text class=\"t2\" x=\"75\" y=\"102.0\" text-anchor=\"middle\" font-size=\"11\">visitor</text><rect class=\"g\" x=\"220\" y=\"14\" width=\"450\" height=\"150\" rx=\"8\"/><text class=\"tg \" x=\"230\" y=\"30\" font-size=\"11\">your server  (firewall: only 22, 80, 443 open)</text><rect class=\"b hi\" x=\"240\" y=\"64\" width=\"170\" height=\"52\" rx=\"6\"/><text class=\"tb ta\" x=\"325\" y=\"86.7\" text-anchor=\"middle\" font-size=\"13\">Nginx</text><text class=\"t2\" x=\"325\" y=\"102.0\" text-anchor=\"middle\" font-size=\"11\">:80 / :443</text><rect class=\"b\" x=\"480\" y=\"64\" width=\"170\" height=\"52\" rx=\"6\"/><text class=\"tb\" x=\"565\" y=\"86.7\" text-anchor=\"middle\" font-size=\"13\">your app</text><text class=\"t2\" x=\"565\" y=\"102.0\" text-anchor=\"middle\" font-size=\"11\">localhost:5000</text><path class=\"ln\" d=\"M142,90 L238,90\" marker-end=\"url(#nginx-proxy--n)\"/><text class=\"tl\" x=\"190\" y=\"83\" text-anchor=\"middle\" font-size=\"11\">HTTPS</text><path class=\"ln\" d=\"M412,90 L478,90\" marker-end=\"url(#nginx-proxy--n)\"/><text class=\"tl\" x=\"445\" y=\"83\" text-anchor=\"middle\" font-size=\"11\">proxy_pass</text><text class=\"t2\" x=\"445\" y=\"148\" text-anchor=\"middle\" font-size=\"12\">the app is never reachable from outside</text></svg></div><figcaption>Visitors only ever talk to Nginx. Port 5000 stays closed in the firewall, so the app is reachable only through the proxy.</figcaption></figure>\n\n<pre><code># /etc/nginx/sites-available/default\nserver {\n    listen 80;\n    server_name demee.cc;\n    location / {\n        proxy_pass http://localhost:5000;   # hand the request to the app\n    }\n}\n$ sudo nginx -t                  # check the config for typos\n$ sudo systemctl reload nginx    # apply it</code></pre>\n<p>Finally point your domain's DNS <b>A record</b> at the server's IP, and get a free HTTPS certificate from Let's Encrypt with <code>sudo certbot --nginx -d demee.cc</code>. Certbot edits the Nginx config for you and renews the certificate automatically.</p>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=7aRjGIhwyQM&amp;t=330s\" target=\"_blank\" rel=\"noopener noreferrer\">Traversy Media · Linux Server Setup & MERN Deployment <span class=\"learn-sources-part\">· Generating SSH keys (5:30)</span></a><a href=\"https://www.youtube.com/watch?v=7aRjGIhwyQM&amp;t=882s\" target=\"_blank\" rel=\"noopener noreferrer\">Traversy Media · Linux Server Setup & MERN Deployment <span class=\"learn-sources-part\">· Disabling password login (14:42)</span></a><a href=\"https://www.youtube.com/watch?v=7aRjGIhwyQM&amp;t=1830s\" target=\"_blank\" rel=\"noopener noreferrer\">Traversy Media · Linux Server Setup & MERN Deployment <span class=\"learn-sources-part\">· Firewall, Nginx, domain and SSL (30:30)</span></a><a href=\"https://www.youtube.com/watch?v=lCq4mYQL0WY&amp;t=2010s\" target=\"_blank\" rel=\"noopener noreferrer\">Cloud Champ · Linux commands for Cloud and DevOps engineers <span class=\"learn-sources-part\">· SSH and remote login (33:30)</span></a></div>","linux/debugging-workflow-editing-files":"\n<p class=\"learn-lead\">The TechWorld with Nana video builds its whole lesson around one realistic problem: an app on a server can't connect to its database. Working through a problem like that uses most of the commands from this topic, in a sensible order.</p>\n\n<h4>A step-by-step debugging routine</h4>\n<figure class=\"learn-diagram dg\" data-dg=\"debug-steps\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 640 330\" role=\"img\" aria-label=\"Six debugging steps in order: where am I, is it running, logs, config, connectivity, then fix and verify\" style=\"--dgw:640px\"><defs><marker id=\"debug-steps--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"b\" x=\"10\" y=\"6\" width=\"280\" height=\"34\" rx=\"6\"/><text class=\"tb\" x=\"150\" y=\"27.2\" text-anchor=\"middle\" font-size=\"13\">1  Where am I?</text><text class=\"tc\" x=\"310\" y=\"28\" text-anchor=\"start\" font-size=\"12\">uname -a, hostname</text><rect class=\"b\" x=\"10\" y=\"60\" width=\"280\" height=\"34\" rx=\"6\"/><text class=\"tb\" x=\"150\" y=\"81.2\" text-anchor=\"middle\" font-size=\"13\">2  Is it running?</text><text class=\"tc\" x=\"310\" y=\"82\" text-anchor=\"start\" font-size=\"12\">systemctl status myapp</text><path class=\"ln\" d=\"M150,42 L150,58\" marker-end=\"url(#debug-steps--n)\"/><rect class=\"b\" x=\"10\" y=\"114\" width=\"280\" height=\"34\" rx=\"6\"/><text class=\"tb\" x=\"150\" y=\"135.2\" text-anchor=\"middle\" font-size=\"13\">3  What do the logs say?</text><text class=\"tc\" x=\"310\" y=\"136\" text-anchor=\"start\" font-size=\"12\">journalctl -u myapp -n 50</text><path class=\"ln\" d=\"M150,96 L150,112\" marker-end=\"url(#debug-steps--n)\"/><rect class=\"b\" x=\"10\" y=\"168\" width=\"280\" height=\"34\" rx=\"6\"/><text class=\"tb\" x=\"150\" y=\"189.2\" text-anchor=\"middle\" font-size=\"13\">4  Is the config right?</text><text class=\"tc\" x=\"310\" y=\"190\" text-anchor=\"start\" font-size=\"12\">diff app.conf app.conf.bak</text><path class=\"ln\" d=\"M150,150 L150,166\" marker-end=\"url(#debug-steps--n)\"/><rect class=\"b\" x=\"10\" y=\"222\" width=\"280\" height=\"34\" rx=\"6\"/><text class=\"tb\" x=\"150\" y=\"243.2\" text-anchor=\"middle\" font-size=\"13\">5  Can it reach what it needs?</text><text class=\"tc\" x=\"310\" y=\"244\" text-anchor=\"start\" font-size=\"12\">curl -I, nc -zv db 5432</text><path class=\"ln\" d=\"M150,204 L150,220\" marker-end=\"url(#debug-steps--n)\"/><rect class=\"b ok\" x=\"10\" y=\"276\" width=\"280\" height=\"34\" rx=\"6\"/><text class=\"tb\" x=\"150\" y=\"297.2\" text-anchor=\"middle\" font-size=\"13\">6  Fix, restart, verify</text><text class=\"tc\" x=\"310\" y=\"298\" text-anchor=\"start\" font-size=\"12\">systemctl restart; tail -f</text><path class=\"ln\" d=\"M150,258 L150,274\" marker-end=\"url(#debug-steps--n)\"/></svg></div><figcaption>Go top to bottom and don't skip ahead. Most problems show themselves by step 3, and step 1 stops you fixing the wrong server.</figcaption></figure>\n\n<ol>\n<li><b>Where am I?</b> <code>uname -a</code> shows the kernel and architecture, <code>cat /etc/os-release</code> shows the distro and version, <code>hostname</code> and <code>whoami</code> confirm the machine and user. It sounds basic, but fixing the wrong server is a classic mistake.</li>\n<li><b>Is it running?</b> <code>systemctl status myapp</code> or <code>ps aux | grep myapp</code>. If it keeps restarting, the status output shows the last log lines.</li>\n<li><b>What do the logs say?</b> <code>journalctl -u myapp -n 50</code>, or <code>tail -n 100 /var/log/myapp/app.log</code>, then narrow it down: <code>grep -i \"error\\|refused\\|timeout\" app.log</code>.</li>\n<li><b>Is the config right?</b> Find it with <code>find / -name \"*.conf\" 2&gt;/dev/null | grep myapp</code>, read it with <code>cat</code> or <code>less</code>, and compare against a known good copy with <code>diff app.conf app.conf.backup</code>. In the video the bug is a wrong database host in the config.</li>\n<li><b>Can it reach what it needs?</b> <code>curl -I http://localhost:8080</code> fetches only the HTTP headers, a fast \"is the web server answering?\" test. <code>ping db-server</code> and <code>nc -zv db-server 5432</code> check the network path and whether the database port is open.</li>\n<li><b>Fix, restart, verify.</b> Edit the file, <code>sudo systemctl restart myapp</code>, and watch the log with <code>tail -f</code> to see it recover.</li>\n</ol>\n<div class=\"learn-callout\">Before editing a config, make a copy: <code>cp app.conf app.conf.bak</code>. If the change makes things worse, you can put the original back in seconds.</div>\n\n<h4>Editing files: nano and Vim</h4>\n<p>On servers there's no graphical editor, so you edit in the terminal. <b>nano</b> is the easy one: the shortcuts are listed at the bottom (Ctrl+O saves, Ctrl+X exits). <b>Vim</b> is installed almost everywhere, so it's worth knowing the survival basics. Vim has <b>modes</b>: in normal mode keys are commands, in insert mode keys type text.</p>\n<ul>\n<li><code>vim file</code> opens it in normal mode.</li>\n<li><code>i</code> enters insert mode so you can type; <code>Esc</code> goes back to normal mode.</li>\n<li><code>:w</code> saves, <code>:q</code> quits, <code>:wq</code> saves and quits, <code>:q!</code> quits and throws away changes.</li>\n<li><code>/word</code> searches, <code>dd</code> deletes a line, <code>u</code> undoes.</li>\n</ul>\n<p>If Vim seems to ignore you, you're almost certainly in the wrong mode: press <code>Esc</code> and try again.</p>\n\n<h4>Shell scripts: automating the routine</h4>\n<p>Any commands you type more than twice belong in a script. A script is a text file of commands that runs top to bottom:</p>\n<pre><code>#!/bin/bash\n# backup.sh - archive a folder with today's date\nset -e                      # stop at the first failing command\n\nSOURCE=\"$1\"                 # first argument\nDEST=\"/backups/$(date +%F).tar.gz\"\n\nif [ -z \"$SOURCE\" ]; then\n  echo \"usage: ./backup.sh folder\" &gt;&amp;2\n  exit 1\nfi\n\ntar -czf \"$DEST\" \"$SOURCE\"\necho \"saved $DEST\"\n\n$ chmod +x backup.sh\n$ ./backup.sh /srv/app</code></pre>\n<ul>\n<li>The first line, the <b>shebang</b> <code>#!/bin/bash</code>, says which program runs the file.</li>\n<li><code>$1</code>, <code>$2</code>… are the arguments; <code>$(command)</code> inserts a command's output.</li>\n<li>Every command returns an <b>exit code</b>: 0 means success, anything else is an error. <code>$?</code> holds the last one, and <code>set -e</code> makes the script stop as soon as one command fails, instead of carrying on in a broken state.</li>\n<li><code>for f in *.log; do gzip \"$f\"; done</code> loops over files.</li>\n</ul>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=CLh2ACdXNbc&amp;t=144s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · 20% of Linux Commands You'll Use 80% of the Time <span class=\"learn-sources-part\">· The full debugging scenario (2:24)</span></a><a href=\"https://www.youtube.com/watch?v=CLh2ACdXNbc&amp;t=929s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · 20% of Linux Commands You'll Use 80% of the Time <span class=\"learn-sources-part\">· diff and curl (15:29)</span></a><a href=\"https://www.youtube.com/watch?v=CLh2ACdXNbc&amp;t=1093s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · 20% of Linux Commands You'll Use 80% of the Time <span class=\"learn-sources-part\">· vim (18:13)</span></a><a href=\"https://www.youtube.com/watch?v=GzIFoJBVwh8&amp;t=3772s\" target=\"_blank\" rel=\"noopener noreferrer\">edureka! · Linux Commands for DevOps <span class=\"learn-sources-part\">· Shell scripting basics (1:02:52)</span></a></div>","linux/shell-scripting":"\n<p class=\"learn-lead\">The debugging chapter showed a tiny backup script. This chapter goes properly into bash scripting: how variables and quoting really work, how scripts make decisions and loop, and how to write scripts that stop loudly when something breaks instead of carrying on and doing damage.</p>\n\n<h4>Running a script</h4>\n<p>The first line, the <b>shebang</b>, tells Linux which program should run the file. <code>#!/bin/bash</code> points straight at bash; <code>#!/usr/bin/env bash</code> asks <code>env</code> to find bash in your <code>PATH</code>, which also works on systems where bash lives somewhere else (macOS with a newer bash, for example).</p>\n<pre><code>$ ./backup.sh              # needs the execute bit and uses the shebang\nbash: ./backup.sh: Permission denied\n$ chmod +x backup.sh       # fix: make it executable\n$ ./backup.sh              # runs in a new bash process\n$ bash backup.sh           # also works without +x (bash is the program, the file is its input)\n$ source backup.sh         # runs inside YOUR current shell (used for config files, not scripts)</code></pre>\n<p>The <code>./</code> is needed because the current folder is not in <code>PATH</code>. Avoid <code>sh backup.sh</code> on Ubuntu: <code>sh</code> is <b>dash</b>, a smaller shell that ignores the shebang and doesn't understand bash features like <code>[[ ]]</code>, so you get errors such as <code>[[: not found</code>.</p>\n\n<h4>Variables and quoting</h4>\n<pre><code>name=\"web-01\"                 # no spaces around = (name = x runs a command called \"name\")\ntoday=$(date +%F)             # command substitution: 2026-09-27\ncount=$((3 + 4))              # arithmetic: 7\necho \"Server $name on $today\" # double quotes: variables ARE expanded\necho 'Server $name'           # single quotes: printed literally -&gt; Server $name\necho \"${name}-backup.tar.gz\"  # braces mark where the name ends\necho \"${ENVIRONMENT:-dev}\"    # use \"dev\" if ENVIRONMENT is unset or empty\n: \"${API_KEY:?API_KEY must be set}\"   # stop the script with this message if it's missing</code></pre>\n<p><b>Always put variables in double quotes.</b> Unquoted, bash splits the value on spaces and expands wildcards, so a file called <code>my notes.txt</code> becomes two arguments:</p>\n<pre><code>file=\"my notes.txt\"\nrm $file      # tries to delete \"my\" and \"notes.txt\"\nrm \"$file\"    # deletes the one file you meant</code></pre>\n\n<h4>Arguments</h4>\n<div class=\"learn-table-wrap\"><table class=\"learn-table\"><thead><tr><th>Variable</th><th>Meaning</th></tr></thead><tbody>\n<tr><td><code>$0</code></td><td>the script's own name, as it was called</td></tr>\n<tr><td><code>$1</code>, <code>$2</code>…</td><td>the first, second… argument (<code>${10}</code> from ten on)</td></tr>\n<tr><td><code>$#</code></td><td>how many arguments were given</td></tr>\n<tr><td><code>\"$@\"</code></td><td>all arguments, each kept as a separate word. Use this form to pass them on or loop over them</td></tr>\n<tr><td><code>$?</code></td><td>exit code of the last command</td></tr>\n</tbody></table></div>\n\n<h4>Exit codes, <code>&amp;&amp;</code> and <code>||</code></h4>\n<p>Every command ends with an exit code: <b>0 means success</b>, 1–255 mean some kind of failure, and each program documents its own codes. <code>grep</code>, for example, returns 0 if it found a match, 1 if it didn't and 2 on an error.</p>\n<pre><code>$ ls /nope\nls: cannot access '/nope': No such file or directory\n$ echo $?\n2\n$ mkdir -p /tmp/build &amp;&amp; cd /tmp/build     # &amp;&amp; runs the second only if the first succeeded\n$ ping -c1 db-01 || echo \"db-01 is down\"     # || runs the second only if the first failed</code></pre>\n<p>Your own script sets its exit code with <code>exit 0</code> or <code>exit 1</code>. Cron, CI pipelines and monitoring tools look only at this number to decide whether your script worked.</p>\n\n\n<figure class=\"learn-diagram dg\" data-dg=\"exit-codes\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 200\" role=\"img\" aria-label=\"A command finishes with exit code 0 for success, which lets &amp;&amp; continue, or 1 to 255 for failure, which triggers ||\" style=\"--dgw:680px\"><defs><marker id=\"exit-codes--bad\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk bad\" d=\"M0,0 L8,4 L0,8 z\"/></marker><marker id=\"exit-codes--ok\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk ok\" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"b hi\" x=\"250\" y=\"20\" width=\"180\" height=\"50\" rx=\"6\"/><text class=\"tb ta tm\" x=\"340\" y=\"41.7\" text-anchor=\"middle\" font-size=\"13\">ping -c1 db-01</text><text class=\"t2\" x=\"340\" y=\"57.0\" text-anchor=\"middle\" font-size=\"11\">sets $?</text><rect class=\"b ok\" x=\"30\" y=\"120\" width=\"250\" height=\"56\" rx=\"6\"/><text class=\"tb\" x=\"155\" y=\"144.7\" text-anchor=\"middle\" font-size=\"13\">exit code 0</text><text class=\"t2\" x=\"155\" y=\"160.0\" text-anchor=\"middle\" font-size=\"11\">success: &amp;&amp; runs the next</text><rect class=\"b bad\" x=\"400\" y=\"120\" width=\"250\" height=\"56\" rx=\"6\"/><text class=\"tb\" x=\"525\" y=\"144.7\" text-anchor=\"middle\" font-size=\"13\">exit code 1-255</text><text class=\"t2\" x=\"525\" y=\"160.0\" text-anchor=\"middle\" font-size=\"11\">failure: || runs the next</text><path class=\"ln ok\" d=\"M300,72 L155,118\" marker-end=\"url(#exit-codes--ok)\"/><text class=\"tl\" x=\"200\" y=\"92\" text-anchor=\"middle\" font-size=\"11\">worked</text><path class=\"ln bad\" d=\"M380,72 L525,118\" marker-end=\"url(#exit-codes--bad)\"/><text class=\"tl\" x=\"480\" y=\"92\" text-anchor=\"middle\" font-size=\"11\">failed</text></svg></div><figcaption><code>&amp;&amp;</code> and <code>||</code> only look at that one number. So do cron, CI pipelines and monitoring tools.</figcaption></figure>\n<h4>Conditions: <code>if</code>, <code>[ ]</code> and <code>[[ ]]</code></h4>\n<p><code>if</code> runs a command and checks its exit code. <code>[ ... ]</code> (also called <code>test</code>) and bash's improved <code>[[ ... ]]</code> are just commands that succeed or fail. The spaces inside the brackets are required: <code>[$x -gt 3]</code> fails with <code>[5: command not found</code>.</p>\n<pre><code>if [[ -f /etc/nginx/nginx.conf ]]; then\n  echo \"nginx config found\"\nelif [[ -d /etc/apache2 ]]; then\n  echo \"looks like apache\"\nelse\n  echo \"no web server config\" &gt;&amp;2\nfi\n\nif grep -q \"ERROR\" app.log; then     # any command works as a condition\n  echo \"errors in the log\"\nfi\n\nif (( disk_used &gt;= 90 )); then echo \"disk almost full\"; fi   # (( )) for numbers</code></pre>\n<div class=\"learn-table-wrap\"><table class=\"learn-table\"><thead><tr><th>Test</th><th>True when</th></tr></thead><tbody>\n<tr><td><code>-f path</code> / <code>-d path</code> / <code>-e path</code></td><td>is a file / is a directory / exists at all</td></tr>\n<tr><td><code>-z \"$s\"</code> / <code>-n \"$s\"</code></td><td>string is empty / not empty</td></tr>\n<tr><td><code>\"$a\" == \"$b\"</code>, <code>!=</code></td><td>strings equal / different</td></tr>\n<tr><td><code>-eq -ne -lt -le -gt -ge</code></td><td>number comparisons (<code>&lt;</code> inside <code>[[ ]]</code> compares text, not numbers)</td></tr>\n<tr><td><code>[[ $f == *.log ]]</code></td><td>pattern match (only in <code>[[ ]]</code>)</td></tr>\n<tr><td><code>! test</code>, <code>&amp;&amp;</code>, <code>||</code></td><td>not, and, or</td></tr>\n</tbody></table></div>\n\n<h4>Loops</h4>\n<pre><code>for host in web-01 web-02 db-01; do        # over a list of words\n  ssh \"$host\" uptime\ndone\n\nfor f in /var/log/myapp/*.log; do          # over files (quote \"$f\"!)\n  gzip \"$f\"\ndone\n\nfor i in {1..5}; do echo \"attempt $i\"; done\n\nwhile IFS= read -r line; do                # a file line by line\n  echo \"host: $line\"\ndone &lt; hosts.txt\n\nuntil curl -fs http://localhost:8080/health &gt; /dev/null; do   # retry until it works\n  sleep 2\ndone</code></pre>\n<p><code>IFS= read -r</code> is the safe way to read lines: it keeps leading spaces and backslashes exactly as they are in the file.</p>\n\n<h4>Functions and reading input</h4>\n<pre><code>greet() {\n  local who=\"$1\"            # local: the variable disappears when the function ends\n  echo \"hello $who\"\n}\ngreet \"Demee\"\n\nread -rp \"Deploy to production? [y/N] \" answer\nif [[ \"$answer\" == \"y\" ]]; then echo \"deploying...\"; fi\nread -rsp \"Password: \" pw; echo   # -s hides what you type</code></pre>\n<p>Arguments inside a function are <code>$1</code>, <code>$2</code>… of that call, not of the script. A function's <code>return</code> sets its exit code (0–255); to hand back text, <code>echo</code> it and capture it with <code>result=$(myfunc)</code>.</p>\n\n<h4>Strict mode: <code>set -euo pipefail</code></h4>\n<p>By default bash ignores failures and keeps going. Put this line under the shebang of every serious script:</p>\n<ul>\n<li><code>-e</code>: exit as soon as a command fails (except inside <code>if</code> conditions and <code>&amp;&amp;</code>/<code>||</code> chains, where failure is expected).</li>\n<li><code>-u</code>: using a variable that was never set is an error (<code>unbound variable</code>) instead of silently being empty. That stops <code>rm -rf \"$DIR/\"</code> turning into <code>rm -rf /</code> because of a typo in the name.</li>\n<li><code>-o pipefail</code>: a pipeline fails if <i>any</i> part fails, not just the last. Without it, <code>false | true</code> counts as success.</li>\n</ul>\n<p><code>trap cleanup EXIT</code> runs a function called <code>cleanup</code> whenever the script ends, even after an error, which is the place to delete temp files.</p>\n\n<h4>A complete example: health check</h4>\n<pre><code>#!/usr/bin/env bash\n# healthcheck.sh - check free disk space and that some URLs answer\nset -euo pipefail\n\nTHRESHOLD=\"${THRESHOLD:-90}\"        # override: THRESHOLD=80 ./healthcheck.sh ...\nLOG_FILE=\"${LOG_FILE:-/tmp/healthcheck.log}\"\nfailures=0\n\nlog() {\n  echo \"$(date '+%F %T') $*\" | tee -a \"$LOG_FILE\"\n}\n\ncheck_disk() {\n  local mount=\"$1\" used\n  used=$(df --output=pcent \"$mount\" | tail -n 1 | tr -dc '0-9')\n  if (( used &gt;= THRESHOLD )); then\n    log \"FAIL disk $mount is ${used}% full\"\n    return 1\n  fi\n  log \"ok   disk $mount is ${used}% full\"\n}\n\ncheck_url() {\n  local url=\"$1\" code=0\n  curl -fs -o /dev/null --max-time 5 \"$url\" || code=$?\n  if (( code != 0 )); then\n    log \"FAIL $url (curl exit code $code)\"\n    return 1\n  fi\n  log \"ok   $url\"\n}\n\nif [[ $# -eq 0 ]]; then\n  echo \"usage: $0 URL [URL...]\" &gt;&amp;2\n  exit 2\nfi\n\ncheck_disk / || failures=$((failures + 1))\nfor url in \"$@\"; do\n  check_url \"$url\" || failures=$((failures + 1))\ndone\n\nif (( failures &gt; 0 )); then\n  log \"$failures check(s) failed\"\n  exit 1\nfi\nlog \"all checks passed\"</code></pre>\n<pre><code>$ chmod +x healthcheck.sh\n$ ./healthcheck.sh http://localhost:8080/ http://localhost:9000/health\n2026-09-27 10:15:02 ok   disk / is 29% full\n2026-09-27 10:15:02 ok   http://localhost:8080/\n2026-09-27 10:15:02 FAIL http://localhost:9000/health (curl exit code 7)\n2026-09-27 10:15:02 1 check(s) failed\n$ echo $?\n1</code></pre>\n<p><code>curl -f</code> makes HTTP errors (4xx/5xx) count as failures. Its exit code tells you why: 6 = couldn't resolve the host name, 7 = couldn't connect, 22 = the server answered with an HTTP error, 28 = timed out. The next chapter shows how to run this every few minutes with cron.</p>\n\n<h4>Common mistakes</h4>\n<ul>\n<li><code>name = value</code> gives <code>name: command not found</code>. Remove the spaces around <code>=</code>.</li>\n<li><code>((count++))</code> under <code>set -e</code> kills the script when <code>count</code> is 0, because <code>(( ))</code> returns failure when the result is 0. Use <code>count=$((count + 1))</code>.</li>\n<li>A script written on Windows has CRLF line endings; bash then reports <code>cannot execute: required file not found</code> (older versions: <code>/bin/bash^M: bad interpreter</code>). Fix with <code>sed -i 's/\\r$//' script.sh</code> or <code>dos2unix</code>.</li>\n<li>Unquoted <code>$var</code> or <code>$@</code> break on spaces. Quote them.</li>\n<li>Install <code>shellcheck</code> (<code>sudo apt install shellcheck</code>) and run <code>shellcheck script.sh</code>: it catches most of these before you run anything.</li>\n</ul>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=GzIFoJBVwh8&amp;t=3772s\" target=\"_blank\" rel=\"noopener noreferrer\">edureka! · Linux Commands for DevOps <span class=\"learn-sources-part\">· Shell scripting basics (1:02:52)</span></a></div>","linux/scheduling-jobs-reading-logs":"\n<p class=\"learn-lead\">A server does a lot of work when nobody is logged in: backups at night, cleanup every hour, health checks every few minutes. You schedule that work with cron or systemd timers, and you find out whether it worked by reading logs.</p>\n\n<h4>The crontab format</h4>\n<p>Each user has a <b>crontab</b>, a list of jobs. Every line is five time fields followed by the command to run:</p>\n<figure class=\"learn-diagram dg\" data-dg=\"crontab\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 640 200\" role=\"img\" aria-label=\"A crontab line: minute 30, hour 2, any day of month, any month, days 1-5, then the command\" style=\"--dgw:640px\"><rect class=\"b hi\" x=\"10\" y=\"20\" width=\"70\" height=\"48\" rx=\"6\"/><text class=\"tb ta tm\" x=\"45\" y=\"49.8\" text-anchor=\"middle\" font-size=\"18\">30</text><text class=\"t2\" x=\"45\" y=\"90\" text-anchor=\"middle\" font-size=\"11\">minute</text><text class=\"t2\" x=\"45\" y=\"106\" text-anchor=\"middle\" font-size=\"11\">0-59</text><rect class=\"b hi\" x=\"92\" y=\"20\" width=\"70\" height=\"48\" rx=\"6\"/><text class=\"tb ta tm\" x=\"127\" y=\"49.8\" text-anchor=\"middle\" font-size=\"18\">2</text><text class=\"t2\" x=\"127\" y=\"90\" text-anchor=\"middle\" font-size=\"11\">hour</text><text class=\"t2\" x=\"127\" y=\"106\" text-anchor=\"middle\" font-size=\"11\">0-23</text><rect class=\"b\" x=\"174\" y=\"20\" width=\"70\" height=\"48\" rx=\"6\"/><text class=\"tb tm\" x=\"209\" y=\"49.8\" text-anchor=\"middle\" font-size=\"18\">*</text><text class=\"t2\" x=\"209\" y=\"90\" text-anchor=\"middle\" font-size=\"11\">day of</text><text class=\"t2\" x=\"209\" y=\"106\" text-anchor=\"middle\" font-size=\"11\">month</text><rect class=\"b\" x=\"256\" y=\"20\" width=\"70\" height=\"48\" rx=\"6\"/><text class=\"tb tm\" x=\"291\" y=\"49.8\" text-anchor=\"middle\" font-size=\"18\">*</text><text class=\"t2\" x=\"291\" y=\"90\" text-anchor=\"middle\" font-size=\"11\">month</text><text class=\"t2\" x=\"291\" y=\"106\" text-anchor=\"middle\" font-size=\"11\">1-12</text><rect class=\"b hi\" x=\"338\" y=\"20\" width=\"70\" height=\"48\" rx=\"6\"/><text class=\"tb ta tm\" x=\"373\" y=\"49.8\" text-anchor=\"middle\" font-size=\"18\">1-5</text><text class=\"t2\" x=\"373\" y=\"90\" text-anchor=\"middle\" font-size=\"11\">day of</text><text class=\"t2\" x=\"373\" y=\"106\" text-anchor=\"middle\" font-size=\"11\">week</text><rect class=\"b\" x=\"430\" y=\"20\" width=\"200\" height=\"48\" rx=\"6\"/><text class=\"tb tm\" x=\"530\" y=\"40.7\" text-anchor=\"middle\" font-size=\"13\">/opt/backup.sh</text><text class=\"t2\" x=\"530\" y=\"56.0\" text-anchor=\"middle\" font-size=\"11\">the command</text><text class=\"ta tb\" x=\"320\" y=\"150\" text-anchor=\"middle\" font-size=\"14\">= at 02:30, Monday to Friday</text><text class=\"t2\" x=\"320\" y=\"180\" text-anchor=\"middle\" font-size=\"11\">* every value   1,15 a list   1-5 a range   */10 every 10th</text></svg></div><figcaption>Five time fields, then the command. Read them left to right as \"minute, hour, day, month, weekday\".</figcaption></figure>\n\n<div class=\"learn-table-wrap\"><table class=\"learn-table\"><thead><tr><th>Field</th><th>Allowed values</th></tr></thead><tbody>\n<tr><td>minute</td><td>0–59</td></tr>\n<tr><td>hour</td><td>0–23</td></tr>\n<tr><td>day of month</td><td>1–31</td></tr>\n<tr><td>month</td><td>1–12 (or <code>jan</code>–<code>dec</code>)</td></tr>\n<tr><td>day of week</td><td>0–7, where 0 and 7 are both Sunday (or <code>sun</code>–<code>sat</code>)</td></tr>\n</tbody></table></div>\n<p>In each field <code>*</code> means every value, <code>1,15</code> is a list, <code>1-5</code> a range and <code>*/10</code> a step (\"every 10th\").</p>\n<pre><code>*/5 * * * *    every 5 minutes\n0 * * * *      at the start of every hour\n30 2 * * *     every day at 02:30\n0 9 * * 1-5    09:00 Monday to Friday\n0 0 1 * *      midnight on the 1st of every month\n0 */6 * * *    every 6 hours (00:00, 06:00, 12:00, 18:00)\n@reboot        once, when cron starts after a boot\n@daily         same as 0 0 * * *   (also @hourly, @weekly, @monthly)</code></pre>\n<p>Times are in the server's time zone (check with <code>timedatectl</code>), which on cloud servers is often UTC. One oddity: if you restrict <i>both</i> day of month and day of week, the job runs when <i>either</i> matches, so <code>0 0 13 * 5</code> means every 13th and also every Friday.</p>\n\n<h4>Editing crontabs</h4>\n<pre><code>$ crontab -e          # edit your jobs (opens an editor, installs on save)\n$ crontab -l          # list your jobs\n$ sudo crontab -u deploy -l   # another user's jobs\n$ crontab -r          # DELETES your whole crontab without asking. Careful: -r is next to -e</code></pre>\n<p>There are also system-wide places: <code>/etc/crontab</code> and files in <code>/etc/cron.d/</code> have an extra field for the <b>user</b> to run as (<code>0 3 * * * root /usr/local/bin/backup</code>). Scripts dropped into <code>/etc/cron.daily/</code>, <code>cron.hourly</code>, <code>cron.weekly</code> or <code>cron.monthly</code> run on that schedule with no time fields at all, but on Debian and Ubuntu their file names may only contain letters, digits, <code>-</code> and <code>_</code>: <b>a file called <code>backup.sh</code> there is silently skipped</b>.</p>\n\n<h4>Cron's environment: why jobs work in the terminal but not in cron</h4>\n<p>Cron does not load your <code>~/.bashrc</code> or <code>~/.profile</code>. Jobs run with a tiny environment:</p>\n<ul>\n<li><code>PATH</code> is only <code>/usr/bin:/bin</code>, so anything in <code>/usr/local/bin</code>, <code>~/.local/bin</code> or a virtual environment is \"not found\". Use full paths, or set <code>PATH=...</code> on a line at the top of the crontab.</li>\n<li>The shell is <code>/bin/sh</code> (dash on Ubuntu), not bash. Put bash syntax in a script with a bash shebang and call the script.</li>\n<li>Your exported variables (API keys and so on) don't exist. Set them in the crontab, or have the script load them from a file.</li>\n<li>The working directory is your home folder, so relative paths in the script point there. Use absolute paths or <code>cd</code> first.</li>\n<li><code>%</code> is special in a crontab line (it means \"newline\"). <code>date +%F</code> must be written <code>date +\\%F</code>.</li>\n</ul>\n<p><b>Output</b> of a job is emailed to you, but only if the server has a mail program; on a typical Ubuntu server it isn't installed and the output is thrown away. Always redirect it to a log file so you can see what happened:</p>\n<pre><code>PATH=/usr/local/bin:/usr/bin:/bin\nMAILTO=\"\"\n\n# every 5 minutes, keep both output and errors\n*/5 * * * * /home/demee/bin/healthcheck.sh https://demee.cc &gt;&gt; /home/demee/logs/health.log 2&gt;&amp;1\n\n# nightly backup; flock -n skips this run if the previous one is still going\n0 3 * * * flock -n /tmp/backup.lock /home/demee/bin/backup.sh /srv/app &gt;&gt; /home/demee/logs/backup.log 2&gt;&amp;1</code></pre>\n<p>To check whether cron ran a job at all, look for its <code>CMD</code> lines: <code>journalctl -u cron --since today</code> or <code>grep CRON /var/log/syslog</code>.</p>\n\n<h4>systemd timers, briefly</h4>\n<p>A <b>timer</b> is systemd's alternative to cron. You write two small unit files: a <code>.service</code> that says what to run and a <code>.timer</code> that says when.</p>\n<pre><code># /etc/systemd/system/backup.service\n[Unit]\nDescription=Nightly backup\n\n[Service]\nType=oneshot\nUser=demee\nExecStart=/home/demee/bin/backup.sh /srv/app\n\n# /etc/systemd/system/backup.timer\n[Unit]\nDescription=Run backup every night\n\n[Timer]\nOnCalendar=*-*-* 03:00:00\nPersistent=true\n\n[Install]\nWantedBy=timers.target\n\n$ sudo systemctl daemon-reload\n$ sudo systemctl enable --now backup.timer\n$ systemctl list-timers                    # all timers, with next and last run\n$ systemd-analyze calendar \"Mon..Fri *-*-* 09:00\"   # check an OnCalendar expression</code></pre>\n<p>Compared with cron, the output lands in the journal automatically (<code>journalctl -u backup</code>), <code>Persistent=true</code> runs a missed job after the machine was off, and <code>systemctl start backup.service</code> runs it on demand for testing. Ubuntu itself uses timers for jobs like log rotation.</p>\n\n<h4>Reading logs with journalctl</h4>\n<p>systemd collects the output of every service, plus kernel and system messages, in the <b>journal</b>. <code>journalctl</code> reads it; newest entries are at the bottom.</p>\n<pre><code>$ journalctl -u nginx                  # one service (-u = unit)\n$ journalctl -u nginx -n 50            # just the last 50 lines\n$ journalctl -u nginx -f               # follow live, like tail -f\n$ journalctl -u nginx --since \"1 hour ago\"\n$ journalctl --since \"2026-09-27 09:00\" --until \"2026-09-27 10:00\"\n$ journalctl -p err -b                 # errors and worse, since this boot\n$ journalctl -u myapp -g \"timeout\"     # only lines matching a pattern\n$ journalctl -k                        # kernel messages (disks, out-of-memory kills)\n$ journalctl --disk-usage              # how much space the journal uses\n$ sudo journalctl --vacuum-time=14d    # delete journal data older than 14 days</code></pre>\n<p>Priorities from most to least severe: <code>emerg</code> (0), <code>alert</code>, <code>crit</code>, <code>err</code>, <code>warning</code>, <code>notice</code>, <code>info</code>, <code>debug</code> (7). <code>-p warning</code> shows warning <i>and everything more severe</i>. If you only see your own messages, use <code>sudo</code> or join the <code>adm</code> or <code>systemd-journal</code> group.</p>\n\n<h4>Classic log files in <code>/var/log</code></h4>\n<div class=\"learn-table-wrap\"><table class=\"learn-table\"><thead><tr><th>File</th><th>What's in it</th></tr></thead><tbody>\n<tr><td><code>/var/log/syslog</code></td><td>general system messages (Debian/Ubuntu; <code>/var/log/messages</code> on Red Hat family)</td></tr>\n<tr><td><code>/var/log/auth.log</code></td><td>logins, SSH, <code>sudo</code> use (<code>/var/log/secure</code> on Red Hat family)</td></tr>\n<tr><td><code>/var/log/kern.log</code></td><td>kernel messages</td></tr>\n<tr><td><code>/var/log/apt/history.log</code>, <code>dpkg.log</code></td><td>what was installed or upgraded, and when</td></tr>\n<tr><td><code>/var/log/nginx/access.log</code>, <code>error.log</code></td><td>each web request, and web server errors</td></tr>\n</tbody></table></div>\n<pre><code>$ sudo tail -f /var/log/auth.log                  # watch logins live\n$ sudo grep \"Failed password\" /var/log/auth.log | tail\n$ ls /var/log/syslog*\n/var/log/syslog  /var/log/syslog.1  /var/log/syslog.2.gz  ...\n$ zgrep -i \"error\" /var/log/syslog.2.gz           # grep inside a compressed old log\n$ zless /var/log/syslog.2.gz</code></pre>\n\n<h4>logrotate: stopping logs from filling the disk</h4>\n<p>Those <code>.1</code> and <code>.gz</code> files come from <b>logrotate</b>, which runs once a day (on Ubuntu via <code>logrotate.timer</code>). It renames the current log, starts a fresh one, compresses old ones and deletes the oldest. Packages put their rules in <code>/etc/logrotate.d/</code>; add one for your own app:</p>\n<pre><code># /etc/logrotate.d/myapp\n/var/log/myapp/*.log {\n    daily\n    rotate 14\n    compress\n    delaycompress\n    missingok\n    notifempty\n    copytruncate\n}\n\n$ sudo logrotate -d /etc/logrotate.d/myapp   # dry run: show what would happen\n$ sudo logrotate -f /etc/logrotate.d/myapp   # force a rotation now to test</code></pre>\n<ul>\n<li><code>daily</code>: rotate every day (or <code>weekly</code>, <code>monthly</code>, <code>size 100M</code>).</li>\n<li><code>rotate 14</code>: keep 14 old files and delete anything older.</li>\n<li><code>compress</code> gzips old files; <code>delaycompress</code> leaves the newest old one (<code>.1</code>) uncompressed for one more round.</li>\n<li><code>missingok</code>: no error if the log doesn't exist; <code>notifempty</code>: don't rotate an empty file.</li>\n<li><code>copytruncate</code>: copy the log, then empty the original, for apps that keep the file open.</li>\n</ul>\n<p>Comments in logrotate files must be on their own line: <code>rotate 14  # keep two weeks</code> is an error (\"bad rotation count\"). <code>copytruncate</code> is the simple choice when the app can't be told to reopen its log file; a few lines written during the copy can be lost. The alternative is <code>create</code> plus a <code>postrotate</code> script that tells the app to reopen its log. If logrotate complains that a directory has \"insecure permissions\", add a line like <code>su myapp myapp</code> to the rule so it knows which user to rotate as.</p>\n","linux/environment-shell-setup":"\n<p class=\"learn-lead\">Why does a command work in one terminal but not another, or on your laptop but not in cron or with <code>sudo</code>? Almost always the answer is the environment: which variables are set, what <code>PATH</code> contains, and which startup files your shell read. This chapter explains all three, plus the aliases and shortcuts that make the shell pleasant to use.</p>\n\n<h4>Shell variables vs environment variables</h4>\n<p>A plain assignment creates a <b>shell variable</b>: only the current shell can see it. <code>export</code> turns it into an <b>environment variable</b>, which is copied into every program the shell starts from then on.</p>\n<pre><code>$ GREETING=hello\n$ bash -c 'echo \"child sees: [$GREETING]\"'\nchild sees: []\n$ export GREETING\n$ bash -c 'echo \"child sees: [$GREETING]\"'\nchild sees: [hello]\n$ declare -p GREETING          # -x means exported\ndeclare -x GREETING=\"hello\"\n$ unset GREETING               # remove it again</code></pre>\n<p>Two more rules explain a lot of confusion:</p>\n<ul>\n<li><code>DEBUG=1 ./app.sh</code> sets the variable <b>for that one command only</b>, without changing your shell.</li>\n<li>The copy only goes downwards. A child process can never change its parent's variables, which is why a script that runs <code>export</code> or <code>cd</code> has no effect on your terminal after it finishes. To change the current shell, you <b>source</b> the file instead (see below).</li>\n</ul>\n\n<h4>Seeing the environment</h4>\n<pre><code>$ printenv PATH               # one variable\n$ printenv | sort | less      # all exported variables\n$ env | grep -i proxy         # env with no arguments also lists them\n$ env -i bash --norc          # a shell with an (almost) empty environment, for testing\n$ set | less                  # shell variables AND functions too, not just exported ones</code></pre>\n<p>Variables you'll meet constantly: <code>HOME</code> (your home folder), <code>USER</code>, <code>PWD</code> (current folder), <code>SHELL</code> (your login shell), <code>EDITOR</code> (used by <code>crontab -e</code> and <code>git commit</code>), <code>LANG</code> (language and character encoding) and <code>PATH</code>.</p>\n\n<h4>PATH and how a command is found</h4>\n<p>When you type <code>python3</code>, bash checks in this order: is it an <b>alias</b>? a shell <b>keyword</b> (<code>if</code>, <code>for</code>)? a <b>function</b>? a <b>builtin</b> (<code>cd</code>, <code>echo</code>, <code>export</code>)? Only then does it search the folders in <code>PATH</code> from left to right and run the <b>first</b> match. If nothing matches: <code>command not found</code>.</p>\n<figure class=\"learn-diagram dg\" data-dg=\"path-lookup\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 230\" role=\"img\" aria-label=\"Bash checks alias, keyword, function and builtin first, then searches each folder in PATH from left to right and runs the first match\" style=\"--dgw:680px\"><defs><marker id=\"path-lookup--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"b hi\" x=\"10\" y=\"20\" width=\"150\" height=\"44\" rx=\"6\"/><text class=\"tb ta tm\" x=\"85\" y=\"46.5\" text-anchor=\"middle\" font-size=\"14\">$ python3</text><rect class=\"b\" x=\"190\" y=\"20\" width=\"104\" height=\"44\" rx=\"6\"/><text class=\"tb\" x=\"242\" y=\"38.8\" text-anchor=\"middle\" font-size=\"12\">alias?</text><text class=\"t2\" x=\"242\" y=\"53.2\" text-anchor=\"middle\" font-size=\"10\">no</text><rect class=\"b\" x=\"310\" y=\"20\" width=\"104\" height=\"44\" rx=\"6\"/><text class=\"tb\" x=\"362\" y=\"38.8\" text-anchor=\"middle\" font-size=\"12\">keyword?</text><text class=\"t2\" x=\"362\" y=\"53.2\" text-anchor=\"middle\" font-size=\"10\">no</text><rect class=\"b\" x=\"430\" y=\"20\" width=\"104\" height=\"44\" rx=\"6\"/><text class=\"tb\" x=\"482\" y=\"38.8\" text-anchor=\"middle\" font-size=\"12\">function?</text><text class=\"t2\" x=\"482\" y=\"53.2\" text-anchor=\"middle\" font-size=\"10\">no</text><rect class=\"b\" x=\"550\" y=\"20\" width=\"104\" height=\"44\" rx=\"6\"/><text class=\"tb\" x=\"602\" y=\"38.8\" text-anchor=\"middle\" font-size=\"12\">builtin?</text><text class=\"t2\" x=\"602\" y=\"53.2\" text-anchor=\"middle\" font-size=\"10\">no</text><path class=\"ln\" d=\"M162,42 L188,42\" marker-end=\"url(#path-lookup--n)\"/><path class=\"ln\" d=\"M296,42 L308,42\" marker-end=\"url(#path-lookup--n)\"/><path class=\"ln\" d=\"M416,42 L428,42\" marker-end=\"url(#path-lookup--n)\"/><path class=\"ln\" d=\"M536,42 L548,42\" marker-end=\"url(#path-lookup--n)\"/><text class=\"t2\" x=\"20\" y=\"104\" text-anchor=\"start\" font-size=\"12\">then the folders in $PATH, left to right:</text><rect class=\"b\" x=\"10\" y=\"120\" width=\"156\" height=\"46\" rx=\"6\"/><text class=\"tb tm\" x=\"88\" y=\"139.8\" text-anchor=\"middle\" font-size=\"12\">/usr/local/sbin</text><text class=\"t2\" x=\"88\" y=\"154.2\" text-anchor=\"middle\" font-size=\"10\">not here</text><rect class=\"b\" x=\"178\" y=\"120\" width=\"156\" height=\"46\" rx=\"6\"/><text class=\"tb tm\" x=\"256\" y=\"139.8\" text-anchor=\"middle\" font-size=\"12\">/usr/local/bin</text><text class=\"t2\" x=\"256\" y=\"154.2\" text-anchor=\"middle\" font-size=\"10\">not here</text><path class=\"ln\" d=\"M166,143 L177,143\" marker-end=\"url(#path-lookup--n)\"/><rect class=\"b\" x=\"346\" y=\"120\" width=\"156\" height=\"46\" rx=\"6\"/><text class=\"tb tm\" x=\"424\" y=\"139.8\" text-anchor=\"middle\" font-size=\"12\">/usr/sbin</text><text class=\"t2\" x=\"424\" y=\"154.2\" text-anchor=\"middle\" font-size=\"10\">not here</text><path class=\"ln\" d=\"M334,143 L345,143\" marker-end=\"url(#path-lookup--n)\"/><rect class=\"b ok\" x=\"514\" y=\"120\" width=\"156\" height=\"46\" rx=\"6\"/><text class=\"tb tm\" x=\"592\" y=\"139.8\" text-anchor=\"middle\" font-size=\"12\">/usr/bin</text><text class=\"t2\" x=\"592\" y=\"154.2\" text-anchor=\"middle\" font-size=\"10\">found!</text><path class=\"ln\" d=\"M502,143 L513,143\" marker-end=\"url(#path-lookup--n)\"/><text class=\"ok tb\" x=\"340\" y=\"206\" text-anchor=\"middle\" font-size=\"13\">first match wins: /usr/bin/python3 runs</text></svg></div><figcaption>That order is why an alias can hide a program, and why the same name in two PATH folders runs the one listed first. <code>type -a</code> shows every match.</figcaption></figure>\n\n<pre><code>$ echo \"$PATH\"\n/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\n$ type ls\nls is aliased to `ls --color=auto'\n$ type cd\ncd is a shell builtin\n$ type python3\npython3 is /usr/bin/python3\n$ type -a python3        # every match, in PATH order\n$ which python3          # searches PATH only\n/usr/bin/python3\n$ which cd               # prints nothing: cd isn't a file, it's built into bash\n$ command -v docker      # script-friendly \"is it installed?\" check</code></pre>\n<p>Prefer <code>type</code> when debugging \"why is the wrong version running?\", because it also sees aliases and functions that <code>which</code> can't. Because the first match wins, the order matters: to use your own tools ahead of the system's, add their folder to the <b>front</b>:</p>\n<pre><code>export PATH=\"$HOME/.local/bin:$PATH\"    # prepend, keep everything that was there</code></pre>\n<div class=\"learn-callout warn\">Writing <code>export PATH=~/bin</code> (without <code>:$PATH</code>) replaces the whole list, and suddenly even <code>ls</code> is \"command not found\". Just open a new terminal, or run <code>export PATH=/usr/local/bin:/usr/bin:/bin</code> to get going again, then fix the line in your startup file.</div>\n<p>Bash also remembers where it found each command. If you install a new version in a different folder and the old one still runs, <code>hash -r</code> clears that memory. And note that <code>sudo</code> resets most variables and uses its own fixed <code>PATH</code> (<code>secure_path</code> in <code>/etc/sudoers</code>), so tools in <code>~/.local/bin</code> are \"not found\" under <code>sudo</code> unless you give the full path.</p>\n\n<h4>Startup files: <code>~/.bashrc</code> vs <code>~/.profile</code></h4>\n<p>Which files bash reads depends on how it was started:</p>\n<div class=\"learn-table-wrap\"><table class=\"learn-table\"><thead><tr><th>File</th><th>Read by</th><th>Put here</th></tr></thead><tbody>\n<tr><td><code>~/.profile</code></td><td><b>login</b> shells: SSH sessions and console logins (Ubuntu's graphical login reads it too)</td><td>environment variables and <code>PATH</code> changes</td></tr>\n<tr><td><code>~/.bashrc</code></td><td>every <b>interactive</b> bash that isn't a login shell, like a new terminal window on a desktop</td><td>aliases, functions, prompt, history settings</td></tr>\n<tr><td><code>/etc/profile</code>, <code>/etc/bash.bashrc</code></td><td>the system-wide versions, read before yours</td><td>settings for all users (needs sudo)</td></tr>\n</tbody></table></div>\n<p>On Ubuntu the default <code>~/.profile</code> also sources <code>~/.bashrc</code>, so SSH logins get your aliases too, and it already adds <code>~/bin</code> and <code>~/.local/bin</code> to <code>PATH</code> if those folders exist. Scripts (non-interactive shells) read <b>neither</b> file, and Ubuntu's <code>~/.bashrc</code> stops at its first lines when the shell isn't interactive.</p>\n<div class=\"learn-callout\">If a <code>~/.bash_profile</code> exists, login shells read it <b>instead of</b> <code>~/.profile</code>. Creating one \"to add a PATH line\" silently disables everything in <code>~/.profile</code>. On macOS the default shell is zsh, whose files are <code>~/.zprofile</code> and <code>~/.zshrc</code>.</div>\n\n<h4>Sourcing: apply changes now</h4>\n<p>Editing <code>~/.bashrc</code> changes nothing in terminals that are already open, because they read it when they started. Re-read it in the current shell with <code>source</code> (or its short form, a dot):</p>\n<pre><code>$ source ~/.bashrc\n$ . ~/.bashrc            # exactly the same thing</code></pre>\n<p>Running <code>bash ~/.bashrc</code> or <code>./file</code> would execute it in a child process, which then exits and takes its settings with it.</p>\n\n<h4>Aliases and small functions</h4>\n<pre><code>alias ll='ls -alF'                       # Ubuntu's .bashrc already defines ll, la and l\nalias k='kubectl'\nalias gs='git status'\nalias ports='sudo ss -tulpn'\n\nmkcd() { mkdir -p \"$1\" &amp;&amp; cd \"$1\"; }     # functions can take arguments\n\n$ alias                  # list all aliases\n$ unalias k              # remove one\n$ \\ls                    # run the real ls, skipping the alias</code></pre>\n<p>Put them in <code>~/.bashrc</code>, or in <code>~/.bash_aliases</code>, which Ubuntu's <code>.bashrc</code> loads automatically if it exists. Aliases are not expanded in scripts, so use full commands (or functions) there.</p>\n\n<h4><code>.env</code> files</h4>\n<p>Apps usually read secrets and settings from environment variables, and a <code>.env</code> file is a simple list of them kept next to a project:</p>\n<pre><code># .env\nDB_HOST=localhost\nDB_PORT=5432\nAPI_KEY=change-me</code></pre>\n<p>Docker Compose reads a <code>.env</code> file in the project folder automatically, Python has <code>python-dotenv</code>, Node has <code>dotenv</code>, and systemd services can load one with <code>EnvironmentFile=</code>. To load one into your current shell:</p>\n<pre><code>$ set -a            # auto-export every variable assigned from now on\n$ source .env\n$ set +a            # back to normal\n$ echo \"$DB_HOST\"\nlocalhost</code></pre>\n<div class=\"learn-callout warn\">A <code>.env</code> file usually contains secrets: add it to <code>.gitignore</code>, give it <code>chmod 600</code>, and commit a <code>.env.example</code> with dummy values instead so others know which variables exist.</div>\n\n<h4>History tricks and shortcuts</h4>\n<pre><code>$ history 20         # last 20 commands, numbered\n$ !42                # rerun command number 42\n$ !!                 # rerun the last command (sudo !! = again, with sudo)\n$ vim /etc/nginx/nginx.conf\n$ sudo nginx -t -c !$      # !$ = last argument of the previous command</code></pre>\n<p>Ubuntu's <code>.bashrc</code> sets <code>HISTCONTROL=ignoreboth</code>, which skips duplicate lines and any command that starts with a <b>space</b>. Typing a space first is a handy way to keep a command with a password in it out of <code>~/.bash_history</code>.</p>\n<div class=\"learn-table-wrap\"><table class=\"learn-table\"><thead><tr><th>Keys</th><th>Does</th></tr></thead><tbody>\n<tr><td>Ctrl+R</td><td>search history backwards as you type; Ctrl+R again for older matches, Enter runs it, Ctrl+G cancels</td></tr>\n<tr><td>Tab / Tab Tab</td><td>complete a command or path / list the possibilities</td></tr>\n<tr><td>Ctrl+A / Ctrl+E</td><td>jump to start / end of the line</td></tr>\n<tr><td>Ctrl+W / Ctrl+U / Ctrl+K</td><td>delete the previous word / everything before the cursor / everything after it</td></tr>\n<tr><td>Ctrl+Y</td><td>paste back what the last delete removed</td></tr>\n<tr><td>Alt+.</td><td>insert the last argument of the previous command</td></tr>\n<tr><td>Ctrl+L</td><td>clear the screen</td></tr>\n<tr><td>Ctrl+C / Ctrl+D</td><td>cancel the current command / log out (on an empty line)</td></tr>\n</tbody></table></div>\n<p><code>cd -</code> jumps back to the previous folder, which pairs nicely with all of the above.</p>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=lCq4mYQL0WY&amp;t=2520s\" target=\"_blank\" rel=\"noopener noreferrer\">Cloud Champ · Linux commands for Cloud and DevOps engineers <span class=\"learn-sources-part\">· history command (42:00)</span></a><a href=\"https://www.youtube.com/watch?v=lCq4mYQL0WY&amp;t=2770s\" target=\"_blank\" rel=\"noopener noreferrer\">Cloud Champ · Linux commands for Cloud and DevOps engineers <span class=\"learn-sources-part\">· Checking where a file or package lives (46:10)</span></a><a href=\"https://www.youtube.com/watch?v=7aRjGIhwyQM&amp;t=1491s\" target=\"_blank\" rel=\"noopener noreferrer\">Traversy Media · Linux Server Setup & MERN Deployment <span class=\"learn-sources-part\">· Environment setup for the app (24:51)</span></a></div>","linux/start-here-set-up-your-practice-machine":"\n<p class=\"learn-lead\">Everything in these Docs is learned by typing it, so before chapter 1 you need a Linux terminal and the core tools on your own computer. It takes about an hour, it's free, and you only do it once. If you already have a working terminal with Git, Python and Docker, skip to the checklist near the end.</p>\n\n<h4>What you're setting up</h4>\n<figure class=\"learn-diagram dg\" data-dg=\"setup-stack\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 640 220\" role=\"img\" aria-label=\"Your practice machine: Windows with WSL 2, macOS or Linux at the bottom, a bash shell on top, then Git, Python, Docker and VS Code\" style=\"--dgw:640px\"><rect class=\"b hi\" x=\"20\" y=\"20\" width=\"140\" height=\"52\" rx=\"6\"/><text class=\"tb ta\" x=\"90\" y=\"42.7\" text-anchor=\"middle\" font-size=\"13\">Git</text><text class=\"t2\" x=\"90\" y=\"58.0\" text-anchor=\"middle\" font-size=\"11\">save, share</text><rect class=\"b hi\" x=\"172\" y=\"20\" width=\"140\" height=\"52\" rx=\"6\"/><text class=\"tb ta\" x=\"242\" y=\"42.7\" text-anchor=\"middle\" font-size=\"13\">Python 3</text><text class=\"t2\" x=\"242\" y=\"58.0\" text-anchor=\"middle\" font-size=\"11\">automate</text><rect class=\"b hi\" x=\"324\" y=\"20\" width=\"140\" height=\"52\" rx=\"6\"/><text class=\"tb ta\" x=\"394\" y=\"42.7\" text-anchor=\"middle\" font-size=\"13\">Docker</text><text class=\"t2\" x=\"394\" y=\"58.0\" text-anchor=\"middle\" font-size=\"11\">containers</text><rect class=\"b hi\" x=\"476\" y=\"20\" width=\"140\" height=\"52\" rx=\"6\"/><text class=\"tb ta\" x=\"546\" y=\"42.7\" text-anchor=\"middle\" font-size=\"13\">VS Code</text><text class=\"t2\" x=\"546\" y=\"58.0\" text-anchor=\"middle\" font-size=\"11\">edit</text><rect class=\"b\" x=\"20\" y=\"92\" width=\"596\" height=\"44\" rx=\"6\"/><text class=\"tb\" x=\"318\" y=\"118.5\" text-anchor=\"middle\" font-size=\"14\">a Linux shell: bash</text><rect class=\"b mut\" x=\"20\" y=\"152\" width=\"190\" height=\"48\" rx=\"6\"/><text class=\"tb\" x=\"115\" y=\"172.7\" text-anchor=\"middle\" font-size=\"13\">Windows</text><text class=\"t2\" x=\"115\" y=\"188.0\" text-anchor=\"middle\" font-size=\"11\">+ WSL 2</text><rect class=\"b mut\" x=\"223\" y=\"152\" width=\"190\" height=\"48\" rx=\"6\"/><text class=\"tb\" x=\"318\" y=\"172.7\" text-anchor=\"middle\" font-size=\"13\">macOS</text><text class=\"t2\" x=\"318\" y=\"188.0\" text-anchor=\"middle\" font-size=\"11\">+ Homebrew</text><rect class=\"b mut\" x=\"426\" y=\"152\" width=\"190\" height=\"48\" rx=\"6\"/><text class=\"tb\" x=\"521\" y=\"172.7\" text-anchor=\"middle\" font-size=\"13\">Linux</text><text class=\"t2\" x=\"521\" y=\"188.0\" text-anchor=\"middle\" font-size=\"11\">or a cloud server</text></svg></div><figcaption>Pick one row at the bottom. Everything above it works the same on all three, which is why the rest of the Docs never needs to ask which one you have.</figcaption></figure>\n\n<ul>\n<li>A <b>Linux shell</b> (bash), where you'll type almost every command in these Docs.</li>\n<li><b>Git</b>, to save and share your work (the Git topic).</li>\n<li><b>Python 3</b>, for scripting and automation (the Python topic).</li>\n<li><b>Docker</b>, to build and run containers (the Docker topic, and everything after it).</li>\n<li>A <b>code editor</b>. VS Code is free and works the same on every system.</li>\n</ul>\n<p>Later topics add a few more tools (kubectl and kind for Kubernetes, the AWS CLI for Cloud); their chapters show how to install them when you get there.</p>\n\n<h4>Windows: WSL 2 gives you real Linux</h4>\n<p><b>WSL</b> (Windows Subsystem for Linux) runs a real Ubuntu next to Windows, with no separate virtual machine to manage. Open <b>PowerShell as Administrator</b> and run:</p>\n<pre><code>PS&gt; wsl --install          # installs WSL 2 and Ubuntu, then asks you to restart\nPS&gt; wsl -l -v               # after the restart: check it\n  NAME      STATE           VERSION\n* Ubuntu    Running         2</code></pre>\n<p>After the restart, Ubuntu opens and asks you to create a username and password. That's your Linux user, separate from your Windows account. The password is what <code>sudo</code> asks for later, and nothing appears on screen while you type it; that's normal.</p>\n<p>Two habits save a lot of pain:</p>\n<ul>\n<li>Keep your projects <b>inside Linux</b>, in your home folder (<code>~/projects</code>), not under <code>/mnt/c/...</code>. Files across that border are much slower and their permissions behave strangely.</li>\n<li>Use <b>Windows Terminal</b> (from the Microsoft Store) to open Ubuntu tabs. To see your Linux files in Explorer, run <code>explorer.exe .</code> from any folder.</li>\n</ul>\n\n<h4>macOS: Terminal and Homebrew</h4>\n<p>macOS is Unix underneath, so the built-in <b>Terminal</b> app already gives you a shell (zsh by default; the commands in these Docs work the same unless a chapter says otherwise). Install the developer tools, then <b>Homebrew</b>, the package manager most Mac developers use. Run the one-line installer shown on brew.sh, then:</p>\n<pre><code>$ xcode-select --install       # compilers and git\n$ brew install git python</code></pre>\n<p>One thing to know: macOS ships the BSD versions of some classic tools (<code>sed</code>, <code>date</code>, <code>grep</code>), which have slightly different options from the GNU versions on Linux servers. If a command from these Docs behaves oddly on a Mac, that's usually why; practising on a Linux VM or cloud server removes the difference.</p>\n\n<h4>Linux, or a small cloud server</h4>\n<p>On Ubuntu or Debian you already have the shell. Install the basics with the package manager (Linux chapter 4 explains how it works):</p>\n<pre><code>$ sudo apt update\n$ sudo apt install -y git python3 python3-venv python3-pip curl</code></pre>\n<p>Another option is a small cloud server: the Cloud topic shows how to start one on the free tier, and Linux chapter 6 shows how to connect to it over SSH.</p>\n\n<h4>Git: install it and introduce yourself</h4>\n<p>Git stamps every commit with a name and email, so set them once:</p>\n<pre><code>$ git --version\n$ git config --global user.name \"Your Name\"\n$ git config --global user.email \"you@example.com\"\n$ git config --global init.defaultBranch main</code></pre>\n<p>GitHub no longer accepts account passwords for Git, so give it an <b>SSH key</b> instead. Create one, then paste the <b>public</b> half into GitHub under Settings, then SSH and GPG keys, then New SSH key:</p>\n<pre><code>$ ssh-keygen -t ed25519 -C \"you@example.com\"   # press Enter to accept the default file\n$ cat ~/.ssh/id_ed25519.pub                       # copy this line into GitHub\n$ ssh -T git@github.com                           # test it\nHi yourname! You've successfully authenticated, but GitHub does not provide shell access.</code></pre>\n<p>The file without <code>.pub</code> is your <b>private</b> key. It never leaves your machine and never goes into a repository.</p>\n\n<h4>Python</h4>\n<pre><code>$ python3 --version           # 3.10 or newer is fine\n$ python3 -m venv .venv &amp;&amp; source .venv/bin/activate\n(.venv) $ python --version</code></pre>\n<p>If <code>venv</code> complains it isn't available on Ubuntu, install <code>python3-venv</code> (above). Python chapter 7 explains what a virtual environment is and why every project gets its own.</p>\n\n<h4>Docker</h4>\n<p>On <b>Windows and Mac</b>, install <b>Docker Desktop</b> from docker.com. On Windows, keep \"Use the WSL 2 based engine\" switched on, and under Settings, Resources, WSL Integration, enable your Ubuntu, so the <code>docker</code> command works inside Ubuntu. On <b>Linux</b>, install Docker Engine by following the page for your distribution on docs.docker.com, then let your user run it without <code>sudo</code>:</p>\n<pre><code>$ sudo usermod -aG docker $USER   # then log out and back in\n$ docker run hello-world\nHello from Docker!\nThis message shows that your installation appears to be working correctly.</code></pre>\n<p>Being in the <code>docker</code> group is equal to having root on that machine, which is fine on your own laptop but worth remembering on shared servers.</p>\n\n<h4>An editor: VS Code</h4>\n<p>Install VS Code from code.visualstudio.com. On Windows, add the <b>WSL</b> extension, then open projects from the Ubuntu terminal with <code>code .</code>: the editor runs on Windows but works directly on your Linux files and uses the Linux terminal. The Python, Docker and YAML extensions are worth adding too; they catch typos in Dockerfiles and YAML before you run anything.</p>\n\n<h4>The checklist</h4>\n<p>Run these in your terminal. Every line should print a version, not an error:</p>\n<pre><code>$ bash --version | head -1\n$ git --version\n$ python3 --version\n$ docker --version\n$ docker compose version\n$ code --version            # optional</code></pre>\n\n<h4>How to use these Docs</h4>\n<ul>\n<li>Go through the topics <b>in order</b>: Linux, Python, Networking, Git, Docker, Kubernetes, Cloud, then DevOps. Each one assumes the ones before it.</li>\n<li><b>Type every command yourself</b>, don't copy and paste. Change things, break them on purpose, and read the errors; that's where most of the learning happens.</li>\n<li>After a chapter, watch the \"Go deeper\" part of its video, then take that video's test. When a topic is done, try its Challenges.</li>\n<li>Finish with the <b>capstone</b> at the end of the DevOps topic, which builds and ships one app using everything.</li>\n</ul>\n\n<h4>Common setup problems</h4>\n<ul>\n<li><b><code>wsl --install</code> says virtualization isn't enabled</b>: turn on Intel VT-x or AMD-V (sometimes called SVM) in your computer's BIOS/UEFI settings, then try again.</li>\n<li><b><code>permission denied while trying to connect to the Docker daemon socket</code></b>: either Docker isn't running (start Docker Desktop), or you were added to the <code>docker</code> group but haven't logged out and back in yet.</li>\n<li><b><code>python: command not found</code></b>: use <code>python3</code>. Inside an activated virtual environment, plain <code>python</code> works.</li>\n<li><b>Git asks for a password when you push</b>: the remote uses HTTPS. Switch it to SSH with <code>git remote set-url origin git@github.com:you/repo.git</code>.</li>\n<li><b><code>docker</code> works in PowerShell but not in Ubuntu</b>: WSL Integration for Ubuntu is switched off in Docker Desktop's settings.</li>\n</ul>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=cBokz0LTizk&amp;t=165s\" target=\"_blank\" rel=\"noopener noreferrer\">Traversy Media · Linux Tutorial - Basic Command Line <span class=\"learn-sources-part\">· The terminal (2:45)</span></a><a href=\"https://www.youtube.com/watch?v=vA5TTz6BXhY&amp;t=685s\" target=\"_blank\" rel=\"noopener noreferrer\">Traversy Media · Git & GitHub Crash Course 2025 <span class=\"learn-sources-part\">· Installation & config (11:25)</span></a><a href=\"https://www.youtube.com/watch?v=pg19Z8LL06w&amp;t=1039s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Docker Crash Course <span class=\"learn-sources-part\">· Install Docker (17:19)</span></a></div>","python/syntax-types-variables":"\n<p class=\"learn-lead\">Python is the language DevOps engineers reach for when a shell script gets too complicated: it reads almost like English, runs everywhere, and has a library for nearly every tool and cloud. This chapter covers how a Python program runs and how it stores values.</p>\n\n<h4>How Python runs your code</h4>\n<p>Python is <b>interpreted</b>: there's no separate compile step. You write code in a <code>.py</code> file and the Python interpreter reads and runs it from the top down, line by line. You can also type <code>python3</code> on its own to get the <b>REPL</b> (the <code>&gt;&gt;&gt;</code> prompt, like the Python console on this site), which runs each line as you type it. Great for trying things out.</p>\n<pre><code>$ python3 hello.py        # run a file\n$ python3                 # interactive prompt\n&gt;&gt;&gt; 2 + 3\n5</code></pre>\n\n<h4>Indentation is the syntax</h4>\n<p>Many languages mark blocks with braces <code>{ }</code>. Python uses indentation instead: everything indented under an <code>if</code>, loop or function belongs to it, and the block ends when the indentation goes back. The convention is 4 spaces. Mixing tabs and spaces, or indenting inconsistently, gives an <code>IndentationError</code>. Comments start with <code>#</code> and are ignored.</p>\n\n<h4>Variables are labels</h4>\n<p>A variable is a name that points at a value. You don't declare a type; Python works it out from the value, which is called <b>dynamic typing</b>. The same name can later point at something of a different type.</p>\n<figure class=\"learn-diagram dg\" data-dg=\"py-labels\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 640 230\" role=\"img\" aria-label=\"Four names, server, port, load and healthy, each pointing at a value in memory, a str, an int, a float and a bool\" style=\"--dgw:640px\"><defs><marker id=\"py-labels--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><text class=\"t2 tb\" x=\"90\" y=\"18\" text-anchor=\"middle\" font-size=\"12\">names</text><text class=\"t2 tb\" x=\"420\" y=\"18\" text-anchor=\"middle\" font-size=\"12\">values in memory</text><rect class=\"b hi\" x=\"20\" y=\"30\" width=\"140\" height=\"36\" rx=\"6\"/><text class=\"tb ta tm\" x=\"90\" y=\"52.2\" text-anchor=\"middle\" font-size=\"13\">server</text><rect class=\"b\" x=\"340\" y=\"30\" width=\"160\" height=\"36\" rx=\"6\"/><text class=\"tb tm\" x=\"420\" y=\"52.2\" text-anchor=\"middle\" font-size=\"13\">&quot;web-01&quot;</text><path class=\"ln\" d=\"M162,48 L338,48\" marker-end=\"url(#py-labels--n)\"/><text class=\"t2\" x=\"520\" y=\"53\" text-anchor=\"start\" font-size=\"12\">str</text><rect class=\"b hi\" x=\"20\" y=\"78\" width=\"140\" height=\"36\" rx=\"6\"/><text class=\"tb ta tm\" x=\"90\" y=\"100.2\" text-anchor=\"middle\" font-size=\"13\">port</text><rect class=\"b\" x=\"340\" y=\"78\" width=\"160\" height=\"36\" rx=\"6\"/><text class=\"tb tm\" x=\"420\" y=\"100.2\" text-anchor=\"middle\" font-size=\"13\">8080</text><path class=\"ln\" d=\"M162,96 L338,96\" marker-end=\"url(#py-labels--n)\"/><text class=\"t2\" x=\"520\" y=\"101\" text-anchor=\"start\" font-size=\"12\">int</text><rect class=\"b hi\" x=\"20\" y=\"126\" width=\"140\" height=\"36\" rx=\"6\"/><text class=\"tb ta tm\" x=\"90\" y=\"148.2\" text-anchor=\"middle\" font-size=\"13\">load</text><rect class=\"b\" x=\"340\" y=\"126\" width=\"160\" height=\"36\" rx=\"6\"/><text class=\"tb tm\" x=\"420\" y=\"148.2\" text-anchor=\"middle\" font-size=\"13\">0.75</text><path class=\"ln\" d=\"M162,144 L338,144\" marker-end=\"url(#py-labels--n)\"/><text class=\"t2\" x=\"520\" y=\"149\" text-anchor=\"start\" font-size=\"12\">float</text><rect class=\"b hi\" x=\"20\" y=\"174\" width=\"140\" height=\"36\" rx=\"6\"/><text class=\"tb ta tm\" x=\"90\" y=\"196.2\" text-anchor=\"middle\" font-size=\"13\">healthy</text><rect class=\"b\" x=\"340\" y=\"174\" width=\"160\" height=\"36\" rx=\"6\"/><text class=\"tb tm\" x=\"420\" y=\"196.2\" text-anchor=\"middle\" font-size=\"13\">True</text><path class=\"ln\" d=\"M162,192 L338,192\" marker-end=\"url(#py-labels--n)\"/><text class=\"t2\" x=\"520\" y=\"197\" text-anchor=\"start\" font-size=\"12\">bool</text></svg></div><figcaption>A variable is a label tied to a value, not a box with a type. Point the same name at something else later and the label simply moves.</figcaption></figure>\n\n<pre><code>server = \"web-01\"      # str\nport = 8080            # int\nload = 0.75            # float\nhealthy = True         # bool\nowner = None           # \"no value yet\"\nprint(type(port))      # &lt;class 'int'&gt;</code></pre>\n<p>The core types:</p>\n<ul>\n<li><b>int</b>: whole numbers, any size. <b>float</b>: numbers with a decimal point.</li>\n<li><b>str</b>: text, in single or double quotes. Triple quotes span several lines.</li>\n<li><b>bool</b>: <code>True</code> or <code>False</code> (capitalised).</li>\n<li><b>None</b>: the absence of a value, what a function returns when it returns nothing.</li>\n</ul>\n\n<h4>Converting between types</h4>\n<p><code>input()</code> always gives you a string, even if the user typed a number, so you convert it before doing maths: <code>age = int(input(\"Age: \"))</code>. <code>int()</code>, <code>float()</code>, <code>str()</code> and <code>bool()</code> convert, and they raise an error if the conversion makes no sense (<code>int(\"abc\")</code>).</p>\n\n<h4>Strings you'll use every day</h4>\n<pre><code>name = \"Demee\"\nprint(f\"Hello {name}, you have {3 * 2} alerts\")   # f-string: values inside {}\n\"web-01\".upper()              # 'WEB-01'\n\"  text  \".strip()            # 'text' (trim spaces/newlines)\n\"a,b,c\".split(\",\")            # ['a', 'b', 'c']\n\"-\".join([\"2026\", \"09\", \"27\"])  # '2026-09-27'\n\"error\" in \"fatal error\"      # True\n\"nginx.conf\".endswith(\".conf\")  # True\nlen(\"devops\")                 # 6</code></pre>\n<p>Strings are <b>immutable</b>: methods like <code>.upper()</code> return a new string and leave the original unchanged. Lists, dicts and sets are <b>mutable</b>: you can change them in place. That difference explains a lot of surprising behaviour later.</p>\n\n<h4>Your first program, step by step</h4>\n<p>Make a file called <code>hello.py</code> (in VS Code, or <code>nano hello.py</code> in the terminal) and type this in:</p>\n<pre><code># hello.py: my first script\nname = input(\"What's your name? \")\nservers = 3\nprint(f\"Hi {name}! You look after {servers} servers.\")</code></pre>\n<pre><code>$ python3 hello.py\nWhat's your name? Demee\nHi Demee! You look after 3 servers.</code></pre>\n<p>Line by line: the first line is a <b>comment</b>, ignored by Python. <code>input()</code> prints the question, waits for you to type and press Enter, and gives back what you typed as a string, which is stored in <code>name</code>. <code>servers = 3</code> stores a number. The last line builds a sentence with an f-string and prints it. Python ran the lines from top to bottom, exactly once each; everything else in programming is about changing that order (decisions and loops, chapter 3).</p>\n\n<h4>Reading error messages</h4>\n<p>Errors aren't failure, they're Python telling you exactly what's wrong. Change <code>{name}</code> to <code>{nme}</code> and run it again:</p>\n<pre><code>Traceback (most recent call last):\n  File \"hello.py\", line 4, in &lt;module&gt;\n    print(f\"Hi {nme}! You look after {servers} servers.\")\nNameError: name 'nme' is not defined. Did you mean: 'name'?</code></pre>\n<p>Read it <b>from the bottom up</b>. The last line says what went wrong (<code>NameError</code>: a name Python doesn't know), and the lines above say where (<code>line 4</code>). The errors you'll meet most at the start:</p>\n<ul>\n<li><b><code>SyntaxError</code></b>: Python can't even read the line. Usually a missing quote, bracket or colon. Look at the line it names <i>and the one before it</i>.</li>\n<li><b><code>IndentationError</code></b>: a block isn't lined up, or tabs and spaces are mixed.</li>\n<li><b><code>NameError</code></b>: a typo in a name, or using a variable before giving it a value.</li>\n<li><b><code>TypeError: can only concatenate str (not \"int\") to str</code></b>: you tried <code>\"Total: \" + 5</code>. Text and numbers don't add; use an f-string (<code>f\"Total: {5}\"</code>) or <code>str(5)</code>.</li>\n<li><b><code>ValueError: invalid literal for int()</code></b>: <code>int(\"abc\")</code>, converting text that isn't a number.</li>\n</ul>\n\n<h4>Naming things</h4>\n<p>Names may contain letters, digits and underscores but can't start with a digit, and they're case-sensitive (<code>Port</code> and <code>port</code> are different). Python style is <b>snake_case</b>: <code>max_retries</code>, <code>server_name</code>. Values that never change are written in capitals by convention, <code>TIMEOUT = 30</code>. Good names make code read like a sentence; <code>x</code> and <code>data2</code> make you guess.</p>\n<div class=\"learn-try\"><h4>Try it yourself</h4><ol><li><p>Ask for a server name and a port, then print a line like <code>web-01 listens on 8080</code>.</p><details><summary>Show an answer</summary><pre><code>server = input(\"Server: \")\nport = input(\"Port: \")\nprint(f\"{server} listens on {port}\")</code></pre></details></li><li><p>Ask how many servers there are and what one costs per month (it can have cents), then print the total cost. Remember <code>input()</code> always gives text.</p><details><summary>Show an answer</summary><pre><code>count = int(input(\"How many servers? \"))\nprice = float(input(\"Price per server: \"))\nprint(f\"Total: {count * price}\")</code></pre></details></li><li><p>This line crashes. Why, and how do you fix it? <code>print(\"You have \" + 3 + \" alerts\")</code></p><details><summary>Show an answer</summary><p>It's a <code>TypeError</code>: <code>+</code> can't join text and a number. Use <code>print(f\"You have {3} alerts\")</code> or <code>print(\"You have \" + str(3) + \" alerts\")</code>.</p></details></li></ol></div><div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=fWjsdhR3z3c&amp;t=25s\" target=\"_blank\" rel=\"noopener noreferrer\">Indently · Learn Python in Less than 10 Minutes <span class=\"learn-sources-part\">· Variables and data types (0:25)</span></a><a href=\"https://www.youtube.com/watch?v=JJmcL1N2KQs&amp;t=135s\" target=\"_blank\" rel=\"noopener noreferrer\">Traversy Media · Python Crash Course For Beginners <span class=\"learn-sources-part\">· Comments, variables and data types (2:15)</span></a><a href=\"https://www.youtube.com/watch?v=t8pPdKYpowI&amp;t=1144s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Python Tutorial for Beginners (5 hours) <span class=\"learn-sources-part\">· Strings and numbers (19:04)</span></a><a href=\"https://www.youtube.com/watch?v=JJmcL1N2KQs&amp;t=590s\" target=\"_blank\" rel=\"noopener noreferrer\">Traversy Media · Python Crash Course For Beginners <span class=\"learn-sources-part\">· String formatting and methods (9:50)</span></a></div>","python/operators-expressions":"\n<p class=\"learn-lead\">Operators combine values into new ones. Most behave like school maths, but a few (division, equality versus identity, and how <code>and</code>/<code>or</code> work) trip people up in exams and in real code.</p>\n\n<h4>Arithmetic</h4>\n<pre><code>7 + 2    # 9\n7 - 2    # 5\n7 * 2    # 14\n7 / 2    # 3.5   (/ always gives a float)\n7 // 2   # 3     (floor division: drop the remainder)\n7 % 2    # 1     (modulo: just the remainder)\n2 ** 3   # 8     (power)</code></pre>\n<p><code>%</code> is more useful than it looks: <code>n % 2 == 0</code> tests for even numbers, and <code>i % 10 == 0</code> does something every tenth time in a loop. <code>+</code> also joins strings and lists, and <code>\"ab\" * 3</code> repeats a string (<code>'ababab'</code>).</p>\n<p>Order of operations: <code>**</code> first, then <code>* / // %</code>, then <code>+ -</code>, left to right. <code>2 + 3 * 4</code> is 14; use brackets when in doubt: <code>(2 + 3) * 4</code> is 20. Shortcuts like <code>count += 1</code> mean <code>count = count + 1</code>.</p>\n\n<h4>Comparisons</h4>\n<p><code>== != &lt; &gt; &lt;= &gt;=</code> compare values and give <code>True</code> or <code>False</code>. They can be chained: <code>1 &lt; x &lt; 10</code>. The <code>in</code> operator tests membership in strings, lists, sets and dict keys: <code>\"prod\" in env_name</code>, <code>port in [80, 443]</code>.</p>\n\n<h4><code>==</code> versus <code>is</code></h4>\n<p><code>==</code> asks \"do these have the same value?\"; <code>is</code> asks \"are these the very same object in memory?\".</p>\n<pre><code>a = [1, 2, 3]\nb = [1, 2, 3]\na == b   # True: same contents\na is b   # False: two separate lists</code></pre>\n<p>Use <code>==</code> for comparing values. The one standard use of <code>is</code> is checking for None: <code>if result is None:</code>.</p>\n\n<h4>Boolean logic and truthiness</h4>\n<p><code>and</code> is true only if both sides are, <code>or</code> if either is, <code>not</code> flips a value. They <b>short-circuit</b>: Python stops as soon as the answer is known, so in <code>user and user.is_admin</code> the second part never runs if <code>user</code> is None.</p>\n<p>Every value also counts as true or false in an <code>if</code>. \"Falsy\" values are <code>False</code>, <code>None</code>, <code>0</code>, empty strings, and empty lists/dicts/sets; everything else is \"truthy\". That's why <code>if errors:</code> works as \"if the list has anything in it\".</p>\n\n<h4>Indexing and slicing</h4>\n<p>Strings and lists are numbered from 0. Negative numbers count from the end: <code>items[-1]</code> is the last one. A slice <code>items[start:stop]</code> includes <code>start</code> but stops <i>before</i> <code>stop</code>, so <code>items[1:3]</code> gives positions 1 and 2. Leave a side empty to go to the edge: <code>items[:3]</code> is the first three, <code>items[::-1]</code> is reversed.</p>\n<figure class=\"learn-diagram dg\" data-dg=\"py-slice\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 640 200\" role=\"img\" aria-label=\"The string DEVOPS with positions 0 to 5 above and -6 to -1 below; the slice s[1:4] picks E, V and O\" style=\"--dgw:640px\"><text class=\"t2\" x=\"70\" y=\"46\" text-anchor=\"middle\" font-size=\"11\">index</text><text class=\"t2\" x=\"70\" y=\"128\" text-anchor=\"middle\" font-size=\"11\">from end</text><rect class=\"b\" x=\"140\" y=\"60\" width=\"54\" height=\"46\" rx=\"6\"/><text class=\"tb tm\" x=\"167\" y=\"88.8\" text-anchor=\"middle\" font-size=\"18\">D</text><text class=\"tc\" x=\"167\" y=\"46\" text-anchor=\"middle\" font-size=\"12\">0</text><text class=\"tc\" x=\"167\" y=\"128\" text-anchor=\"middle\" font-size=\"12\">-6</text><rect class=\"b hi\" x=\"200\" y=\"60\" width=\"54\" height=\"46\" rx=\"6\"/><text class=\"tb ta tm\" x=\"227\" y=\"88.8\" text-anchor=\"middle\" font-size=\"18\">E</text><text class=\"tc\" x=\"227\" y=\"46\" text-anchor=\"middle\" font-size=\"12\">1</text><text class=\"tc\" x=\"227\" y=\"128\" text-anchor=\"middle\" font-size=\"12\">-5</text><rect class=\"b hi\" x=\"260\" y=\"60\" width=\"54\" height=\"46\" rx=\"6\"/><text class=\"tb ta tm\" x=\"287\" y=\"88.8\" text-anchor=\"middle\" font-size=\"18\">V</text><text class=\"tc\" x=\"287\" y=\"46\" text-anchor=\"middle\" font-size=\"12\">2</text><text class=\"tc\" x=\"287\" y=\"128\" text-anchor=\"middle\" font-size=\"12\">-4</text><rect class=\"b hi\" x=\"320\" y=\"60\" width=\"54\" height=\"46\" rx=\"6\"/><text class=\"tb ta tm\" x=\"347\" y=\"88.8\" text-anchor=\"middle\" font-size=\"18\">O</text><text class=\"tc\" x=\"347\" y=\"46\" text-anchor=\"middle\" font-size=\"12\">3</text><text class=\"tc\" x=\"347\" y=\"128\" text-anchor=\"middle\" font-size=\"12\">-3</text><rect class=\"b\" x=\"380\" y=\"60\" width=\"54\" height=\"46\" rx=\"6\"/><text class=\"tb tm\" x=\"407\" y=\"88.8\" text-anchor=\"middle\" font-size=\"18\">P</text><text class=\"tc\" x=\"407\" y=\"46\" text-anchor=\"middle\" font-size=\"12\">4</text><text class=\"tc\" x=\"407\" y=\"128\" text-anchor=\"middle\" font-size=\"12\">-2</text><rect class=\"b\" x=\"440\" y=\"60\" width=\"54\" height=\"46\" rx=\"6\"/><text class=\"tb tm\" x=\"467\" y=\"88.8\" text-anchor=\"middle\" font-size=\"18\">S</text><text class=\"tc\" x=\"467\" y=\"46\" text-anchor=\"middle\" font-size=\"12\">5</text><text class=\"tc\" x=\"467\" y=\"128\" text-anchor=\"middle\" font-size=\"12\">-1</text><text class=\"ta tb\" x=\"320\" y=\"166\" text-anchor=\"middle\" font-size=\"13\">s[1:4]  -&gt;  &quot;EVO&quot;     starts at 1, stops before 4</text><text class=\"tc\" x=\"320\" y=\"190\" text-anchor=\"middle\" font-size=\"12\">s[-1]  -&gt;  &quot;S&quot;     s[:3]  -&gt;  &quot;DEV&quot;     s[::-1]  -&gt;  &quot;SPOVED&quot;</text></svg></div><figcaption>Count from 0 at the front or from -1 at the back. A slice includes its start and stops just before its end, so <code>s[1:4]</code> is three items.</figcaption></figure>\n\n\n<h4>Operators at work</h4>\n<p>Here's a small, realistic calculation: how full is a disk, as a percentage with one decimal?</p>\n<pre><code>used_gb = 412\ntotal_gb = 500\npercent = used_gb / total_gb * 100        # 82.39999999999999\nprint(f\"Disk is {round(percent, 1)}% full\")   # Disk is 82.4% full\nprint(\"warning\" if percent &gt; 80 else \"ok\")   # warning: a one-line if/else</code></pre>\n<p>A few built-in functions do a lot of everyday maths for you: <code>round(x, 1)</code>, <code>min(a, b)</code>, <code>max(list)</code>, <code>sum(list)</code> and <code>abs(-5)</code>.</p>\n\n<h4>Common mistakes</h4>\n<ul>\n<li><b><code>=</code> versus <code>==</code></b>: one equals sign <i>stores</i> a value, two <i>compare</i>. <code>if status = \"ok\":</code> is a <code>SyntaxError</code>; you meant <code>==</code>.</li>\n<li><b>Decimals aren't exact</b>: <code>0.1 + 0.2</code> gives <code>0.30000000000000004</code>, because computers store decimals in binary. Round before you display, and don't test floats with <code>==</code>; use <code>abs(a - b) &lt; 0.0001</code>.</li>\n<li><b>Text that looks like a number</b>: <code>\"10\" == 10</code> is <code>False</code>, and <code>\"10\" &lt; 5</code> is a <code>TypeError</code>. Values from files, <code>input()</code> and command arguments are text until you convert them.</li>\n<li><b>Floor division with negatives</b>: <code>-7 // 2</code> is <code>-4</code>, not <code>-3</code>. It rounds down, towards minus infinity.</li>\n</ul>\n<div class=\"learn-try\"><h4>Try it yourself</h4><ol><li><p>Write one line that is <code>True</code> only when <code>port</code> is a valid port number (1 to 65535).</p><details><summary>Show an answer</summary><pre><code>1 &lt;= port &lt;= 65535</code></pre><p>Chained comparisons read just like maths.</p></details></li><li><p><code>filename = \"backup-2026-09-30.tar.gz\"</code>. Use slicing to get the date part <code>2026-09-30</code>.</p><details><summary>Show an answer</summary><pre><code>filename[7:17]</code></pre><p>Count from 0: the date starts at position 7 and the slice stops before 17.</p></details></li><li><p>Without running it, what do these give: <code>7 // 2</code>, <code>7 % 2</code>, <code>2 ** 10</code>, <code>bool(\"\")</code>?</p><details><summary>Show an answer</summary><p><code>3</code>, <code>1</code>, <code>1024</code> and <code>False</code> (an empty string is falsy).</p></details></li></ol></div><div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=fWjsdhR3z3c&amp;t=230s\" target=\"_blank\" rel=\"noopener noreferrer\">Indently · Learn Python in Less than 10 Minutes <span class=\"learn-sources-part\">· Logic statements (3:50)</span></a><a href=\"https://www.youtube.com/watch?v=t8pPdKYpowI&amp;t=4528s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Python Tutorial for Beginners (5 hours) <span class=\"learn-sources-part\">· Conditionals and booleans (1:15:28)</span></a></div>","python/control-flow-functions":"\n<p class=\"learn-lead\">Control flow decides which lines run and how many times; functions package logic under a name so you can reuse it. Together they turn a list of statements into an actual program.</p>\n\n<h4>Making decisions</h4>\n<pre><code>cpu = 85\nif cpu &gt; 90:\n    print(\"critical\")\nelif cpu &gt; 70:\n    print(\"warning\")\nelse:\n    print(\"ok\")</code></pre>\n<p>Python checks each condition from the top and runs only the <b>first</b> block that matches, then skips the rest. Here it prints \"warning\" and never looks at <code>else</code>. <code>elif</code> and <code>else</code> are optional.</p>\n\n<h4>Loops</h4>\n<p>A <code>for</code> loop runs once for each item in something iterable (a list, a string, a file, a range of numbers). A <code>while</code> loop keeps going as long as a condition stays true, which is right when you don't know in advance how many times, like retrying until a server answers.</p>\n<pre><code>for host in [\"web-01\", \"web-02\", \"db-01\"]:\n    print(\"checking\", host)\n\nfor i in range(3):          # 0, 1, 2 (stops before 3)\n    print(i)\n\nattempts = 0\nwhile attempts &lt; 5:\n    attempts += 1           # without this the loop never ends\n    if try_connect():\n        break               # leave the loop early\n</code></pre>\n<ul>\n<li><code>break</code> exits the loop immediately; <code>continue</code> skips to the next item.</li>\n<li><code>range(start, stop, step)</code> produces numbers; <code>range(0, 10, 2)</code> gives 0, 2, 4, 6, 8.</li>\n<li><code>pass</code> does nothing. It's a placeholder where Python needs a statement but you have nothing to write yet.</li>\n</ul>\n\n<h4>Functions</h4>\n<p>A function is a named, reusable block. You define it once with <code>def</code> and call it as often as you like, passing in values (<b>arguments</b>) that fill its <b>parameters</b>.</p>\n<pre><code>def disk_status(used, total=100):\n    \"\"\"Return a label for how full a disk is.\"\"\"\n    percent = used / total * 100\n    if percent &gt; 90:\n        return \"full\"\n    return \"ok\"\n\ndisk_status(95)              # 'full' (total defaults to 100)\ndisk_status(40, total=500)   # 'ok'</code></pre>\n<ul>\n<li><code>return</code> sends a value back to whoever called the function and ends it. A function without <code>return</code> gives back <code>None</code>.</li>\n<li><code>print</code> only shows something on screen; it doesn't give the value back. Mixing these up is a very common beginner bug.</li>\n<li>A parameter with <code>=</code> has a <b>default</b>, which makes it optional.</li>\n<li><code>*args</code> collects any extra positional arguments into a tuple, <code>**kwargs</code> collects extra named ones into a dict: <code>def total(*args): return sum(args)</code>.</li>\n<li>The string right under <code>def</code> is a <b>docstring</b>, the function's built-in documentation.</li>\n</ul>\n\n\n<figure class=\"learn-diagram dg\" data-dg=\"py-func\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 220\" role=\"img\" aria-label=\"Calling disk_status(95) fills the parameters used=95 and total=100, runs the body, and return sends &quot;full&quot; back to the caller\" style=\"--dgw:680px\"><defs><marker id=\"py-func--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"b hi\" x=\"10\" y=\"84\" width=\"170\" height=\"52\" rx=\"6\"/><text class=\"tb ta tm\" x=\"95\" y=\"106.3\" text-anchor=\"middle\" font-size=\"12\">disk_status(95)</text><text class=\"t2\" x=\"95\" y=\"121.5\" text-anchor=\"middle\" font-size=\"11\">the call</text><rect class=\"g\" x=\"250\" y=\"14\" width=\"260\" height=\"192\" rx=\"8\"/><text class=\"tg \" x=\"260\" y=\"29\" font-size=\"10\">def disk_status(used, total=100)</text><rect class=\"b\" x=\"266\" y=\"42\" width=\"228\" height=\"42\" rx=\"6\"/><text class=\"tb tm\" x=\"380\" y=\"59.3\" text-anchor=\"middle\" font-size=\"12\">used = 95  total = 100</text><text class=\"t2\" x=\"380\" y=\"74.5\" text-anchor=\"middle\" font-size=\"11\">parameters filled in</text><rect class=\"b\" x=\"266\" y=\"102\" width=\"228\" height=\"42\" rx=\"6\"/><text class=\"tb tm\" x=\"380\" y=\"119.3\" text-anchor=\"middle\" font-size=\"12\">percent = 95.0</text><text class=\"t2\" x=\"380\" y=\"134.5\" text-anchor=\"middle\" font-size=\"11\">the body runs</text><rect class=\"b ok\" x=\"266\" y=\"162\" width=\"228\" height=\"36\" rx=\"6\"/><text class=\"tb tm\" x=\"380\" y=\"183.8\" text-anchor=\"middle\" font-size=\"12\">return &quot;full&quot;</text><path class=\"ln\" d=\"M380,86 L380,100\" marker-end=\"url(#py-func--n)\"/><path class=\"ln\" d=\"M380,146 L380,160\" marker-end=\"url(#py-func--n)\"/><path class=\"ln\" d=\"M182,100 L264,64\" marker-end=\"url(#py-func--n)\"/><text class=\"tl\" x=\"212\" y=\"70\" text-anchor=\"middle\" font-size=\"11\">arguments</text><rect class=\"b ok\" x=\"550\" y=\"140\" width=\"120\" height=\"52\" rx=\"6\"/><text class=\"tb tm\" x=\"610\" y=\"162.7\" text-anchor=\"middle\" font-size=\"13\">&quot;full&quot;</text><text class=\"t2\" x=\"610\" y=\"178.0\" text-anchor=\"middle\" font-size=\"11\">back to caller</text><path class=\"ln\" d=\"M496,180 L548,168\" marker-end=\"url(#py-func--n)\"/></svg></div><figcaption>Arguments go in, the body runs once, <code>return</code> hands one value back and ends the function. <code>total</code> wasn't passed, so its default was used.</figcaption></figure>\n<h4>Scope: where a variable exists</h4>\n<p>Variables created inside a function are <b>local</b>: they exist only while that function runs and disappear afterwards. Code inside a function can read variables from outside, but to <i>reassign</i> an outer variable you'd have to declare it <code>global</code> first. Usually it's cleaner to pass values in as arguments and return results.</p>\n<figure class=\"learn-diagram dg\" data-dg=\"py-scope\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 640 220\" role=\"img\" aria-label=\"A global scope holding LIMIT contains the local scope of check(), whose variable percent exists only while the function runs; the function can read LIMIT\" style=\"--dgw:640px\"><defs><marker id=\"py-scope--ok\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk ok\" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"g\" x=\"10\" y=\"10\" width=\"620\" height=\"200\" rx=\"8\"/><text class=\"tg \" x=\"20\" y=\"26\" font-size=\"11\">global scope: the whole script</text><rect class=\"b\" x=\"30\" y=\"44\" width=\"200\" height=\"40\" rx=\"6\"/><text class=\"tb tm\" x=\"130\" y=\"61.2\" text-anchor=\"middle\" font-size=\"13\">LIMIT = 90</text><text class=\"t2\" x=\"130\" y=\"75.7\" text-anchor=\"middle\" font-size=\"10\">lives all along</text><rect class=\"g hi\" x=\"270\" y=\"40\" width=\"340\" height=\"156\" rx=\"8\"/><text class=\"tg hi\" x=\"280\" y=\"56\" font-size=\"11\">local scope: inside check(used)</text><rect class=\"b\" x=\"290\" y=\"76\" width=\"300\" height=\"40\" rx=\"6\"/><text class=\"tb tm\" x=\"440\" y=\"93.2\" text-anchor=\"middle\" font-size=\"13\">percent = used / 2</text><text class=\"t2\" x=\"440\" y=\"107.7\" text-anchor=\"middle\" font-size=\"10\">exists only while it runs</text><rect class=\"b ok\" x=\"290\" y=\"134\" width=\"300\" height=\"44\" rx=\"6\"/><text class=\"tb tm\" x=\"440\" y=\"153.2\" text-anchor=\"middle\" font-size=\"13\">if percent &gt; LIMIT:</text><text class=\"t2\" x=\"440\" y=\"167.7\" text-anchor=\"middle\" font-size=\"10\">reading LIMIT is fine</text><path class=\"ln ok\" d=\"M288,156 L130,156 L130,86\" marker-end=\"url(#py-scope--ok)\"/><text class=\"tl\" x=\"200\" y=\"150\" text-anchor=\"middle\" font-size=\"11\">reads outward</text><text class=\"bad\" x=\"130\" y=\"196\" text-anchor=\"middle\" font-size=\"11\">percent is gone after return</text></svg></div><figcaption>Inside a function you can see out, but nothing outside can see in. When the function returns, its local variables are thrown away.</figcaption></figure>\n\n\n<h4>Tracing a loop by hand</h4>\n<p>When a loop confuses you, play computer: write down each variable after every step. Here's a loop that adds up response times:</p>\n<pre><code>times = [120, 80, 200]\ntotal = 0\nfor t in times:\n    total = total + t\nprint(total)   # 400</code></pre>\n<div class=\"learn-table-wrap\"><table class=\"learn-table\"><thead><tr><th>Step</th><th><code>t</code></th><th><code>total</code> after the step</th></tr></thead>\n<tbody><tr><td>before the loop</td><td>(none)</td><td>0</td></tr><tr><td>1st time round</td><td>120</td><td>120</td></tr><tr><td>2nd time round</td><td>80</td><td>200</td></tr><tr><td>3rd time round</td><td>200</td><td>400</td></tr></tbody></table></div>\n<p>Most loops follow one of a few patterns, and recognising them makes code much easier to write:</p>\n<pre><code># count: how many match?\ndown = 0\nfor s in statuses:\n    if s != \"up\":\n        down += 1\n\n# find: stop at the first match\nfirst_error = None\nfor line in lines:\n    if \"ERROR\" in line:\n        first_error = line\n        break\n\n# collect: build a new list\nbig = []\nfor f in files:\n    if f[\"size_mb\"] &gt; 100:\n        big.append(f[\"name\"])</code></pre>\n\n<h4>Why functions are worth it</h4>\n<p>The moment you copy and paste a block of code, it's time for a function. Copied code means every fix has to be made twice, and one copy always gets forgotten. A function also gives the logic a name, so the rest of the script reads like a description of what it does:</p>\n<pre><code>def is_valid_port(port):\n    return 1 &lt;= port &lt;= 65535\n\ndef parse_address(text):\n    host, port = text.split(\":\")       # \"db-01:5432\" -&gt; \"db-01\", \"5432\"\n    return host, int(port)             # a function can return several values\n\nhost, port = parse_address(\"db-01:5432\")\nif not is_valid_port(port):\n    print(\"bad port\")</code></pre>\n<p>Small functions that each do one job, with clear names, are the main difference between a script that's easy to change and one nobody wants to touch.</p>\n<div class=\"learn-try\"><h4>Try it yourself</h4><ol><li><p>Print the numbers 1 to 20, but print <code>check</code> instead of every multiple of 5.</p><details><summary>Show an answer</summary><pre><code>for n in range(1, 21):\n    if n % 5 == 0:\n        print(\"check\")\n    else:\n        print(n)</code></pre></details></li><li><p>Write a function <code>status(cpu)</code> that returns <code>\"critical\"</code> above 90, <code>\"warning\"</code> above 70, and <code>\"ok\"</code> otherwise.</p><details><summary>Show an answer</summary><pre><code>def status(cpu):\n    if cpu &gt; 90:\n        return \"critical\"\n    if cpu &gt; 70:\n        return \"warning\"\n    return \"ok\"</code></pre><p>Each <code>return</code> ends the function, so no <code>elif</code> is needed.</p></details></li><li><p>Use a <code>while</code> loop to count down from 5 to 1, then print <code>go!</code>.</p><details><summary>Show an answer</summary><pre><code>n = 5\nwhile n &gt; 0:\n    print(n)\n    n -= 1\nprint(\"go!\")</code></pre></details></li></ol></div><div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=JJmcL1N2KQs&amp;t=2965s\" target=\"_blank\" rel=\"noopener noreferrer\">Traversy Media · Python Crash Course For Beginners <span class=\"learn-sources-part\">· Conditionals (49:25)</span></a><a href=\"https://www.youtube.com/watch?v=JJmcL1N2KQs&amp;t=3549s\" target=\"_blank\" rel=\"noopener noreferrer\">Traversy Media · Python Crash Course For Beginners <span class=\"learn-sources-part\">· Loops (59:09)</span></a><a href=\"https://www.youtube.com/watch?v=t8pPdKYpowI&amp;t=2373s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Python Tutorial for Beginners (5 hours) <span class=\"learn-sources-part\">· Functions (39:33)</span></a><a href=\"https://www.youtube.com/watch?v=t8pPdKYpowI&amp;t=3240s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Python Tutorial for Beginners (5 hours) <span class=\"learn-sources-part\">· Scope (54:00)</span></a></div>","python/data-structures-comprehensions":"\n<p class=\"learn-lead\">Python has four built-in collections, and choosing the right one makes code simpler and faster. The question to ask is: does order matter, can it change, and do I look things up by position or by name?</p>\n\n<h4>list: an ordered, changeable sequence</h4>\n<p>Use a list when you have several items in order and might add or remove some. Items can be any type.</p>\n<pre><code>servers = [\"web-01\", \"web-02\"]\nservers.append(\"web-03\")      # add to the end\nservers.insert(0, \"lb-01\")    # add at a position\nservers.remove(\"web-02\")      # remove by value\nlast = servers.pop()          # remove and return the last one\nservers.sort()                # sort in place\nlen(servers)                  # how many</code></pre>\n\n<h4>tuple: an ordered sequence that can't change</h4>\n<p>A tuple, written with brackets <code>( )</code>, is like a list you can't modify. Use it for fixed groups of values, like coordinates or a <code>(host, port)</code> pair. Because it can't change, a tuple can be a dict key; a list can't.</p>\n\n<h4>dict: look things up by key</h4>\n<p>A dictionary stores <b>key: value</b> pairs and finds a value by its key instantly, however big it gets. It's the natural shape for configuration, JSON data and counting things.</p>\n<pre><code>config = {\"host\": \"db-01\", \"port\": 5432}\nconfig[\"port\"]                    # 5432\nconfig[\"user\"] = \"app\"            # add or change a key\nconfig.get(\"password\")            # None instead of an error if missing\nconfig.get(\"timeout\", 30)         # with a default\nfor key, value in config.items():\n    print(key, \"=\", value)</code></pre>\n\n<h4>set: unique items, no order</h4>\n<p>A set keeps only one copy of each item and is fast at \"is this in there?\" checks. <code>set(ip_list)</code> removes duplicates in one step, and sets support maths: <code>a | b</code> (union), <code>a &amp; b</code> (items in both), <code>a - b</code> (in a but not b).</p>\n\n<h4>Comprehensions: building a collection in one line</h4>\n<p>A comprehension creates a new list (or dict or set) by looping over something, optionally filtering, and transforming each item. It reads as \"give me <i>this</i> for each item in <i>that</i>, if <i>condition</i>\":</p>\n<pre><code>squares = [x * x for x in range(5)]            # [0, 1, 4, 9, 16]\nevens = [x for x in range(10) if x % 2 == 0]   # [0, 2, 4, 6, 8]\nnames = [s.upper() for s in servers]\nports = {name: 8000 + i for i, name in enumerate(servers)}   # dict comprehension</code></pre>\n{{DIAG:COMPREHENSION}}\n<p><code>enumerate()</code> gives you the position and the item together (<code>for i, item in enumerate(items)</code>), and <code>zip(a, b)</code> walks two lists side by side.</p>\n\n<h4>Nested data: what APIs and configs really look like</h4>\n<p>Real data is collections inside collections. A list of servers from an API, a JSON file or a YAML config usually looks like this, a <b>list of dicts</b>:</p>\n<pre><code>servers = [\n    {\"name\": \"web-01\", \"env\": \"prod\", \"cpu\": 35, \"tags\": [\"nginx\"]},\n    {\"name\": \"web-02\", \"env\": \"prod\", \"cpu\": 91, \"tags\": [\"nginx\", \"canary\"]},\n    {\"name\": \"db-01\",  \"env\": \"dev\",  \"cpu\": 12, \"tags\": []},\n]\n\nservers[1][\"name\"]            # 'web-02': position 1 in the list, then the \"name\" key\nservers[1][\"tags\"][0]         # 'nginx'\n\nfor s in servers:\n    if s[\"cpu\"] &gt; 80:\n        print(s[\"name\"], \"is busy\")\n\nprod = [s[\"name\"] for s in servers if s[\"env\"] == \"prod\"]   # ['web-01', 'web-02']</code></pre>\n<p>Read access paths left to right, one step at a time: <code>servers[1]</code> is a dict, so <code>[\"tags\"]</code> is a list, so <code>[0]</code> is its first item. When a key might be missing, <code>s.get(\"owner\", \"nobody\")</code> avoids a <code>KeyError</code>.</p>\n\n<h4>Copying versus sharing</h4>\n<p>Assigning a list to another name doesn't copy it; both names point at the same list:</p>\n<pre><code>a = [\"web-01\"]\nb = a\nb.append(\"web-02\")\nprint(a)          # ['web-01', 'web-02']: a changed too!\nc = a.copy()      # a real, separate copy (or list(a))</code></pre>\n<p>This surprises everyone once. If a function changes a list you passed in, the caller sees the change.</p>\n\n<h4>Sorting and counting</h4>\n<pre><code>by_cpu = sorted(servers, key=lambda s: s[\"cpu\"], reverse=True)   # busiest first\nby_cpu[0][\"name\"]                                                # 'web-02'\n\nfrom collections import Counter\nlevels = [\"INFO\", \"ERROR\", \"INFO\", \"WARN\", \"ERROR\", \"ERROR\"]\nCounter(levels)                    # Counter({'ERROR': 3, 'INFO': 2, 'WARN': 1})\nCounter(levels).most_common(1)     # [('ERROR', 3)]</code></pre>\n<p><code>sorted()</code> returns a new list and leaves the original alone; <code>list.sort()</code> sorts in place and returns <code>None</code>. The <code>key</code> is a small function that says what to sort by; <code>lambda s: s[\"cpu\"]</code> is a one-line function that takes a server and returns its CPU.</p>\n<div class=\"learn-try\"><h4>Try it yourself</h4><ol><li><p>From the <code>servers</code> list above, make a list of the names of servers that have the tag <code>\"nginx\"</code>.</p><details><summary>Show an answer</summary><pre><code>[s[\"name\"] for s in servers if \"nginx\" in s[\"tags\"]]</code></pre></details></li><li><p>Count how many lines in <code>lines</code> contain <code>\"ERROR\"</code>, without using <code>Counter</code>.</p><details><summary>Show an answer</summary><pre><code>errors = 0\nfor line in lines:\n    if \"ERROR\" in line:\n        errors += 1</code></pre><p>Or in one line: <code>sum(1 for line in lines if \"ERROR\" in line)</code>.</p></details></li><li><p>Remove duplicate IP addresses from a list but keep the order they first appeared in.</p><details><summary>Show an answer</summary><pre><code>unique = list(dict.fromkeys(ips))</code></pre><p>A <code>set</code> would remove duplicates too, but forgets the order. Dict keys keep it.</p></details></li></ol></div><div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=JJmcL1N2KQs&amp;t=1060s\" target=\"_blank\" rel=\"noopener noreferrer\">Traversy Media · Python Crash Course For Beginners <span class=\"learn-sources-part\">· Lists (17:40)</span></a><a href=\"https://www.youtube.com/watch?v=JJmcL1N2KQs&amp;t=1455s\" target=\"_blank\" rel=\"noopener noreferrer\">Traversy Media · Python Crash Course For Beginners <span class=\"learn-sources-part\">· Tuples and sets (24:15)</span></a><a href=\"https://www.youtube.com/watch?v=JJmcL1N2KQs&amp;t=1989s\" target=\"_blank\" rel=\"noopener noreferrer\">Traversy Media · Python Crash Course For Beginners <span class=\"learn-sources-part\">· Dictionaries (33:09)</span></a><a href=\"https://www.youtube.com/watch?v=t8pPdKYpowI&amp;t=9865s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Python Tutorial for Beginners (5 hours) <span class=\"learn-sources-part\">· Dictionary data type (2:44:25)</span></a></div>","python/oop-error-handling":"\n<p class=\"learn-lead\">Classes let you bundle data with the functions that work on it, which is how most Python libraries are organised. Error handling lets a script deal with things going wrong (a missing file, a server that doesn't answer) instead of crashing.</p>\n\n<h4>Classes and objects</h4>\n<p>A <b>class</b> is a blueprint; an <b>object</b> (or instance) is one thing built from it. The class defines what data each object holds (<b>attributes</b>) and what it can do (<b>methods</b>, functions that belong to it).</p>\n<pre><code>class Server:\n    def __init__(self, name, ip):\n        self.name = name        # attributes stored on this object\n        self.ip = ip\n        self.up = False\n\n    def start(self):\n        self.up = True\n        return f\"{self.name} ({self.ip}) is up\"\n\nweb = Server(\"web-01\", \"10.0.0.5\")   # __init__ runs here\nweb.start()                          # 'web-01 (10.0.0.5) is up'</code></pre>\n<p><code>__init__</code> runs automatically when an object is created and sets it up. <code>self</code> is the object itself: <code>self.name</code> means \"this server's name\", so each object keeps its own values.</p>\n\n<h4>Inheritance</h4>\n<p>A class can be based on another one and inherit all its attributes and methods, then add or <b>override</b> what's different. That avoids copying code between similar classes.</p>\n<pre><code>class Dog:\n    def __init__(self, name):\n        self.name = name\n    def bark(self):\n        return f\"{self.name} says woof\"\n\nclass Puppy(Dog):          # Puppy inherits from Dog\n    def bark(self):        # overrides one method\n        return f\"{self.name} says yip\"</code></pre>\n{{DIAG:INHERIT}}\n\n<h4>Exceptions: when things go wrong</h4>\n<p>When Python hits a problem it can't continue from, it raises an <b>exception</b>, such as <code>ZeroDivisionError</code>, <code>FileNotFoundError</code>, <code>KeyError</code> (missing dict key), <code>ValueError</code> (like <code>int(\"abc\")</code>) or <code>TypeError</code>. If nothing handles it, the program stops and prints a traceback that shows where it happened, read from the bottom up.</p>\n<pre><code>try:\n    with open(\"config.json\") as f:\n        config = json.load(f)\nexcept FileNotFoundError:\n    print(\"no config, using defaults\")\n    config = {}\nexcept json.JSONDecodeError as e:\n    print(\"config is broken:\", e)\n    raise                      # re-raise: this one should stop the script\nelse:\n    print(\"config loaded\")     # only if nothing went wrong\nfinally:\n    print(\"done\")              # always runs, error or not</code></pre>\n<ul>\n<li>Catch <b>specific</b> exceptions. A bare <code>except:</code> also hides typos and real bugs.</li>\n<li><code>raise ValueError(\"port must be a number\")</code> raises your own error.</li>\n<li><code>finally</code> is for clean-up that must happen no matter what, like closing a connection.</li>\n</ul>\n\n<h4>A class you'd actually write</h4>\n<p>Use a class when some data and the functions that work on it belong together, and you'll have several of them. A health check for a list of URLs is a good fit: each check has a URL, remembers its last result, and knows how to run itself.</p>\n<pre><code>import urllib.request\n\nclass HealthCheck:\n    def __init__(self, url, timeout=5):\n        self.url = url\n        self.timeout = timeout\n        self.last_status = None\n\n    def run(self):\n        try:\n            with urllib.request.urlopen(self.url, timeout=self.timeout) as r:\n                self.last_status = r.status\n        except Exception as e:\n            self.last_status = f\"failed: {e}\"\n        return self.last_status\n\n    def __repr__(self):                       # how it looks when printed\n        return f\"HealthCheck({self.url!r}, last={self.last_status})\"\n\nchecks = [HealthCheck(\"https://example.com\"), HealthCheck(\"https://example.org\")]\nfor c in checks:\n    c.run()\nprint(checks)</code></pre>\n<p>If there's no state to remember and you only need one action, a plain function is simpler. Plenty of good DevOps scripts never define a class at all.</p>\n\n<h4>with: clean-up that always happens</h4>\n<p><code>with open(...) as f:</code> opens a file and guarantees it's closed when the block ends, even if an error happens inside it. The same pattern is used for network connections, locks and temporary folders, so whenever a library offers <code>with</code>, use it.</p>\n<pre><code>with open(\"hosts.txt\") as f:\n    hosts = [line.strip() for line in f if line.strip()]\n# the file is closed here, whatever happened above</code></pre>\n\n<h4>Your own exceptions</h4>\n<p>For problems specific to your script, define your own exception type. Code calling yours can then catch exactly that problem and nothing else:</p>\n<pre><code>class ConfigError(Exception):\n    pass\n\ndef load_port(config):\n    if \"port\" not in config:\n        raise ConfigError(\"config has no 'port'\")\n    return int(config[\"port\"])\n\ntry:\n    port = load_port({})\nexcept ConfigError as e:\n    print(\"Fix your config:\", e)</code></pre>\n<div class=\"learn-try\"><h4>Try it yourself</h4><ol><li><p>Write a class <code>Counter</code> with an <code>add()</code> method that adds one, and a <code>value</code> attribute that starts at 0.</p><details><summary>Show an answer</summary><pre><code>class Counter:\n    def __init__(self):\n        self.value = 0\n    def add(self):\n        self.value += 1\n\nc = Counter()\nc.add(); c.add()\nprint(c.value)   # 2</code></pre></details></li><li><p>Write <code>safe_int(text, default=0)</code> that returns the number in <code>text</code>, or <code>default</code> if it isn't a number.</p><details><summary>Show an answer</summary><pre><code>def safe_int(text, default=0):\n    try:\n        return int(text)\n    except ValueError:\n        return default</code></pre></details></li><li><p>Read <code>servers.txt</code> and print how many lines it has, but print <code>no servers.txt yet</code> instead of crashing if it doesn't exist.</p><details><summary>Show an answer</summary><pre><code>try:\n    with open(\"servers.txt\") as f:\n        print(len(f.readlines()))\nexcept FileNotFoundError:\n    print(\"no servers.txt yet\")</code></pre></details></li></ol></div><div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=JJmcL1N2KQs&amp;t=4552s\" target=\"_blank\" rel=\"noopener noreferrer\">Traversy Media · Python Crash Course For Beginners <span class=\"learn-sources-part\">· Classes and objects (1:15:52)</span></a><a href=\"https://www.youtube.com/watch?v=t8pPdKYpowI&amp;t=17042s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Python Tutorial for Beginners (5 hours) <span class=\"learn-sources-part\">· Object-oriented programming (4:44:02)</span></a><a href=\"https://www.youtube.com/watch?v=t8pPdKYpowI&amp;t=6258s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Python Tutorial for Beginners (5 hours) <span class=\"learn-sources-part\">· Error handling with try/except (1:44:18)</span></a><a href=\"https://www.youtube.com/watch?v=fWjsdhR3z3c&amp;t=540s\" target=\"_blank\" rel=\"noopener noreferrer\">Indently · Learn Python in Less than 10 Minutes <span class=\"learn-sources-part\">· try/except (9:00)</span></a></div>","python/modules-files-python-for-devops":"\n<p class=\"learn-lead\">Real scripts read files, talk to APIs and use other people's code. This chapter covers how Python pulls in libraries, how it handles files and JSON, and the kinds of automation DevOps engineers actually write with it.</p>\n\n<h4>Modules and packages</h4>\n<p>A <b>module</b> is just a <code>.py</code> file; <code>import</code> loads it so you can use what's inside. Python ships with a big <b>standard library</b> (<code>os</code>, <code>json</code>, <code>datetime</code>, <code>subprocess</code>, <code>pathlib</code>…), and thousands more third-party packages live on <b>PyPI</b>, installed with <code>pip</code>.</p>\n<figure class=\"learn-diagram dg\" data-dg=\"py-modules\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 210\" role=\"img\" aria-label=\"A script imports from three places: your own .py files, the standard library that ships with Python, and PyPI packages installed with pip\" style=\"--dgw:680px\"><defs><marker id=\"py-modules--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"b hi\" x=\"250\" y=\"140\" width=\"180\" height=\"52\" rx=\"6\"/><text class=\"tb ta tm\" x=\"340\" y=\"162.7\" text-anchor=\"middle\" font-size=\"13\">monitor.py</text><text class=\"t2\" x=\"340\" y=\"178.0\" text-anchor=\"middle\" font-size=\"11\">your script</text><rect class=\"b\" x=\"10\" y=\"20\" width=\"200\" height=\"64\" rx=\"6\"/><text class=\"tb\" x=\"110\" y=\"42.2\" text-anchor=\"middle\" font-size=\"13\">your own files</text><text class=\"t2\" x=\"110\" y=\"56.7\" text-anchor=\"middle\" font-size=\"10\">utils.py</text><text class=\"t2\" x=\"110\" y=\"70.7\" text-anchor=\"middle\" font-size=\"10\">from utils import ...</text><rect class=\"b ok\" x=\"240\" y=\"20\" width=\"200\" height=\"64\" rx=\"6\"/><text class=\"tb\" x=\"340\" y=\"42.2\" text-anchor=\"middle\" font-size=\"13\">standard library</text><text class=\"t2\" x=\"340\" y=\"56.7\" text-anchor=\"middle\" font-size=\"10\">os, json, pathlib</text><text class=\"t2\" x=\"340\" y=\"70.7\" text-anchor=\"middle\" font-size=\"10\">comes with Python</text><rect class=\"b warn\" x=\"470\" y=\"20\" width=\"200\" height=\"64\" rx=\"6\"/><text class=\"tb\" x=\"570\" y=\"42.2\" text-anchor=\"middle\" font-size=\"13\">PyPI packages</text><text class=\"t2\" x=\"570\" y=\"56.7\" text-anchor=\"middle\" font-size=\"10\">requests, boto3</text><text class=\"t2\" x=\"570\" y=\"70.7\" text-anchor=\"middle\" font-size=\"10\">pip install first</text><path class=\"ln\" d=\"M110,86 L290,138\" marker-end=\"url(#py-modules--n)\"/><path class=\"ln\" d=\"M340,86 L340,138\" marker-end=\"url(#py-modules--n)\"/><path class=\"ln\" d=\"M570,86 L390,138\" marker-end=\"url(#py-modules--n)\"/><text class=\"tl\" x=\"352\" y=\"118\" text-anchor=\"start\" font-size=\"11\">import</text></svg></div><figcaption>All three look the same in code: <code>import name</code>. Only PyPI packages need installing first, ideally into the project's virtual environment.</figcaption></figure>\n\n<pre><code>import os                       # use as os.getenv(...)\nfrom datetime import datetime   # import one name directly\nimport subprocess as sp         # import under a shorter alias\n\n$ pip install requests boto3    # third-party packages from PyPI</code></pre>\n<p>Different projects need different package versions, so each project should get its own <b>virtual environment</b>: <code>python3 -m venv .venv</code>, then <code>source .venv/bin/activate</code>. <code>pip freeze &gt; requirements.txt</code> records the exact versions, and <code>pip install -r requirements.txt</code> recreates them on another machine.</p>\n<p>When a file is run directly, the special variable <code>__name__</code> is <code>\"__main__\"</code>; when it's imported it's the module's name. So code under <code>if __name__ == \"__main__\":</code> runs only when you execute the file, not when another script imports its functions.</p>\n\n<h4>Reading and writing files</h4>\n<pre><code>with open(\"hosts.txt\") as f:            # \"r\" (read) is the default\n    for line in f:\n        print(line.strip())\n\nwith open(\"report.txt\", \"w\") as f:      # \"w\" overwrites the file\n    f.write(\"all good\\n\")\n\nwith open(\"app.log\", \"a\") as f:         # \"a\" appends to the end\n    f.write(\"deploy finished\\n\")</code></pre>\n<p><code>with</code> closes the file automatically when the block ends, even if an error happens in the middle.</p>\n\n<h4>JSON: the format APIs speak</h4>\n<p>JSON maps straight onto Python: objects become dicts, arrays become lists. <code>json.load(f)</code> / <code>json.dump(data, f)</code> work with files; <code>json.loads(text)</code> / <code>json.dumps(data)</code> work with strings.</p>\n\n<h4>What Python is used for in DevOps</h4>\n<ul>\n<li><b>Scripting and automation:</b> replacing long, fragile shell scripts: rotating logs, cleaning up old backups, renaming thousands of files.</li>\n<li><b>Talking to APIs:</b> the <code>requests</code> library calls any REST API. The Nana course ends with a script that lists projects from the GitLab API.</li>\n<li><b>Cloud automation:</b> AWS's <code>boto3</code> library creates and manages resources from code. The Cloud Champ video launches an EC2 server and rotates a database password with it.</li>\n<li><b>Glue for tools:</b> Ansible is written in Python, and CI pipelines often call small Python scripts for checks and reports.</li>\n<li><b>Monitoring:</b> small web apps (for example with Flask) that report CPU, memory or disk use, or send alerts.</li>\n</ul>\n<pre><code>import requests\n\nresp = requests.get(\"https://api.github.com/repos/python/cpython\", timeout=10)\nresp.raise_for_status()               # error on 4xx/5xx\ndata = resp.json()                    # JSON body -> dict\nprint(data[\"stargazers_count\"])\n\nimport boto3\nec2 = boto3.client(\"ec2\", region_name=\"eu-central-1\")\nfor r in ec2.describe_instances()[\"Reservations\"]:\n    for i in r[\"Instances\"]:\n        print(i[\"InstanceId\"], i[\"State\"][\"Name\"])</code></pre>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=JJmcL1N2KQs&amp;t=3906s\" target=\"_blank\" rel=\"noopener noreferrer\">Traversy Media · Python Crash Course For Beginners <span class=\"learn-sources-part\">· Modules (1:05:06)</span></a><a href=\"https://www.youtube.com/watch?v=JJmcL1N2KQs&amp;t=5177s\" target=\"_blank\" rel=\"noopener noreferrer\">Traversy Media · Python Crash Course For Beginners <span class=\"learn-sources-part\">· Files and JSON (1:26:17)</span></a><a href=\"https://www.youtube.com/watch?v=t8pPdKYpowI&amp;t=13227s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Python Tutorial for Beginners (5 hours) <span class=\"learn-sources-part\">· Packages, PyPI and pip (3:40:27)</span></a><a href=\"https://www.youtube.com/watch?v=t8pPdKYpowI&amp;t=18875s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Python Tutorial for Beginners (5 hours) <span class=\"learn-sources-part\">· Project: API request to GitLab (5:14:35)</span></a><a href=\"https://www.youtube.com/watch?v=guCFLTU-XRM&amp;t=455s\" target=\"_blank\" rel=\"noopener noreferrer\">Cloud Champ · How I use Python as a DevOps Engineer <span class=\"learn-sources-part\">· Creating EC2 with boto3 (7:35)</span></a></div>","python/virtual-environments-packages":"\n<p class=\"learn-lead\">Almost every real Python project uses packages from PyPI, and every project needs its own versions of them. A virtual environment is the standard way to keep those packages separate per project, and on Ubuntu 24.04 it's no longer optional: plain <code>pip install</code> outside one is refused.</p>\n\n<h4>Why virtual environments exist</h4>\n<p>Without one, <code>pip install</code> puts packages into the Python that came with the operating system. That causes three problems:</p>\n<ul>\n<li><b>Version clashes:</b> project A needs <code>requests</code> 2.28, project B needs 2.32. One Python can only have one version installed.</li>\n<li><b>Breaking the OS:</b> Ubuntu's own tools are written in Python and installed with <code>apt</code>. Upgrading a library under them with pip can break them.</li>\n<li><b>No record:</b> nobody knows which packages the project actually needs, so it won't run on the next machine.</li>\n</ul>\n<p>A <b>virtual environment</b> (venv) is a folder containing its own <code>python</code>, its own <code>pip</code> and its own <code>site-packages</code> folder where installs go. Each project gets one, usually called <code>.venv</code> inside the project.</p>\n\n\n<figure class=\"learn-diagram dg\" data-dg=\"py-venv\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 210\" role=\"img\" aria-label=\"Three separate Pythons: the system one used by the OS, and two project virtual environments each with its own requests version\" style=\"--dgw:680px\"><rect class=\"g bad\" x=\"10\" y=\"14\" width=\"200\" height=\"182\" rx=\"8\"/><text class=\"tg bad\" x=\"20\" y=\"30\" font-size=\"11\">system Python</text><rect class=\"b bad\" x=\"26\" y=\"48\" width=\"168\" height=\"60\" rx=\"6\"/><text class=\"tb\" x=\"110\" y=\"68.2\" text-anchor=\"middle\" font-size=\"13\">used by the OS</text><text class=\"t2\" x=\"110\" y=\"82.7\" text-anchor=\"middle\" font-size=\"10\">apt&#x27;s own tools</text><text class=\"t2\" x=\"110\" y=\"96.7\" text-anchor=\"middle\" font-size=\"10\">don&#x27;t pip here</text><rect class=\"b\" x=\"26\" y=\"120\" width=\"168\" height=\"60\" rx=\"6\"/><text class=\"tb tm\" x=\"110\" y=\"146.7\" text-anchor=\"middle\" font-size=\"13\">python3</text><text class=\"t2\" x=\"110\" y=\"162.0\" text-anchor=\"middle\" font-size=\"11\">/usr/bin</text><rect class=\"g ok\" x=\"240\" y=\"14\" width=\"200\" height=\"182\" rx=\"8\"/><text class=\"tg ok\" x=\"250\" y=\"30\" font-size=\"11\">project-a/.venv</text><rect class=\"b ok\" x=\"256\" y=\"48\" width=\"168\" height=\"60\" rx=\"6\"/><text class=\"tb tm\" x=\"340\" y=\"75.2\" text-anchor=\"middle\" font-size=\"13\">requests 2.28</text><text class=\"t2\" x=\"340\" y=\"89.7\" text-anchor=\"middle\" font-size=\"10\">its own site-packages</text><rect class=\"b\" x=\"256\" y=\"120\" width=\"168\" height=\"60\" rx=\"6\"/><text class=\"tb tm\" x=\"340\" y=\"147.2\" text-anchor=\"middle\" font-size=\"13\">python, pip</text><text class=\"t2\" x=\"340\" y=\"161.7\" text-anchor=\"middle\" font-size=\"10\">its own copies</text><rect class=\"g ok\" x=\"460\" y=\"14\" width=\"200\" height=\"182\" rx=\"8\"/><text class=\"tg ok\" x=\"470\" y=\"30\" font-size=\"11\">project-b/.venv</text><rect class=\"b ok\" x=\"476\" y=\"48\" width=\"168\" height=\"60\" rx=\"6\"/><text class=\"tb tm\" x=\"560\" y=\"75.2\" text-anchor=\"middle\" font-size=\"13\">requests 2.32</text><text class=\"t2\" x=\"560\" y=\"89.7\" text-anchor=\"middle\" font-size=\"10\">its own site-packages</text><rect class=\"b\" x=\"476\" y=\"120\" width=\"168\" height=\"60\" rx=\"6\"/><text class=\"tb tm\" x=\"560\" y=\"147.2\" text-anchor=\"middle\" font-size=\"13\">python, pip</text><text class=\"t2\" x=\"560\" y=\"161.7\" text-anchor=\"middle\" font-size=\"10\">its own copies</text></svg></div><figcaption>Each project folder gets its own Python, pip and packages. Different versions stop clashing, and the system Python stays untouched.</figcaption></figure>\n<h4>Create, activate, deactivate</h4>\n<pre><code>$ cd ~/projects/monitor\n$ python3 -m venv .venv                # create it (once per project)\n$ source .venv/bin/activate            # Linux / macOS\n(.venv) $ which python\n/home/demee/projects/monitor/.venv/bin/python\n(.venv) $ python -m pip install requests\n(.venv) $ deactivate                   # back to the system Python</code></pre>\n<p>On Windows the folder is called <code>Scripts</code> instead of <code>bin</code>:</p>\n<pre><code>C:\\monitor&gt; py -m venv .venv\nC:\\monitor&gt; .venv\\Scripts\\activate            &lt;- cmd.exe\nPS C:\\monitor&gt; .venv\\Scripts\\Activate.ps1     &lt;- PowerShell</code></pre>\n<p>If PowerShell says running scripts is disabled, allow it for your user once with <code>Set-ExecutionPolicy -Scope CurrentUser RemoteSigned</code>.</p>\n<p>\"Activating\" does nothing magic: it puts <code>.venv/bin</code> at the front of your <code>PATH</code> (see the Linux chapter on environment) and adds <code>(.venv)</code> to the prompt. That also means you can skip activation and call the venv's Python directly, which is exactly what you do in cron jobs, systemd services and Dockerfiles:</p>\n<pre><code>$ /home/demee/projects/monitor/.venv/bin/python check.py</code></pre>\n<p>Add <code>.venv/</code> to <code>.gitignore</code>: it's big, contains machine-specific paths and can always be recreated. For the same reason you can't move or rename a venv folder; delete it and create a new one.</p>\n\n<h4>pip: installing and inspecting</h4>\n<pre><code>(.venv) $ pip install requests                 # latest version\n(.venv) $ pip install \"requests==2.32.3\"       # exact version\n(.venv) $ pip install \"requests&gt;=2.31,&lt;3\"     # any version in a range\n(.venv) $ pip install --upgrade requests       # newer version of an installed package\n(.venv) $ pip uninstall requests\n(.venv) $ pip list                             # everything installed\n(.venv) $ pip show requests                    # version, location, dependencies</code></pre>\n<p>Quote version specifiers: an unquoted <code>&gt;</code> or <code>&lt;</code> is shell redirection. <code>python -m pip</code> is the same as <code>pip</code> but guarantees you're using the pip that belongs to that exact <code>python</code>, which avoids a whole class of \"I installed it but it's not found\" problems.</p>\n\n<h4>requirements.txt: recording what the project needs</h4>\n<pre><code>(.venv) $ pip freeze &gt; requirements.txt\n(.venv) $ cat requirements.txt\ncertifi==2026.7.22\ncharset-normalizer==3.5.1\nidna==3.20\nPyYAML==6.0.2\nrequests==2.32.3\nurllib3==2.8.0\n\n# on another machine, or in CI / a Dockerfile:\n$ python3 -m venv .venv &amp;&amp; source .venv/bin/activate\n(.venv) $ pip install -r requirements.txt</code></pre>\n<p><code>pip freeze</code> lists <i>every</i> installed package with its exact version, including dependencies you never asked for (<code>certifi</code>, <code>idna</code> and friends come with <code>requests</code>). Your version numbers will differ from these. Pinning exact versions (<code>==</code>) means the server gets exactly what you tested; without pins, a new release published tomorrow can break a deploy that worked today. You can also write the file by hand with only your direct dependencies:</p>\n<pre><code># requirements.txt\nrequests~=2.32.0      # 2.32.x only: bug fixes yes, new minor version no\nPyYAML==6.0.2\n# comments and blank lines are allowed</code></pre>\n<p>Tools like Poetry and uv add lock files and speed on top of this, but they're built on the same ideas: one isolated environment per project and a recorded list of versions.</p>\n\n<h4>pipx: Python command-line tools</h4>\n<p>Some packages are really <i>applications</i> you want as a command everywhere (linters, formatters, <code>httpie</code>), not libraries for one project. <b>pipx</b> installs each one into its own hidden venv and puts just the command on your <code>PATH</code>:</p>\n<pre><code>$ sudo apt install pipx\n$ pipx ensurepath          # adds ~/.local/bin to PATH (open a new terminal after)\n$ pipx install black\n$ black --version\n$ pipx list                # what's installed\n$ pipx upgrade black\n$ pipx uninstall black</code></pre>\n\n<h4>Errors you will meet (and how to fix them)</h4>\n<p><b>externally-managed-environment</b> on Ubuntu 23.04+ and Debian 12+, when you <code>pip install</code> outside a venv:</p>\n<pre><code>$ pip install requests\nerror: externally-managed-environment\n\n× This environment is externally managed\n╰─&gt; To install Python packages system-wide, try apt install\n    python3-xyz, where xyz is the package you are trying to\n    install.\n    ...</code></pre>\n<p>This is deliberate (PEP 668): the system Python belongs to <code>apt</code>. Fixes, best first: use a venv; for a library a system tool needs, <code>sudo apt install python3-requests</code>; for a command-line app, <code>pipx install</code>. The flag <code>--break-system-packages</code> exists, but its name is an honest description of what it can do.</p>\n<p><b>No venv module</b> on a fresh Ubuntu:</p>\n<pre><code>$ python3 -m venv .venv\nThe virtual environment was not created successfully because ensurepip is not\navailable.  On Debian/Ubuntu systems, you need to install the python3-venv\npackage using the following command.\n\n    apt install python3.12-venv\n...\n$ sudo apt install python3-venv      # installs the right python3.X-venv, then create the venv again</code></pre>\n<p>Similarly, <code>pip: command not found</code> or <code>python: command not found</code> outside a venv is normal on Ubuntu 24.04: the command is <code>python3</code>, and pip comes from <code>sudo apt install python3-pip</code>. Inside an activated venv both <code>python</code> and <code>pip</code> exist.</p>\n<p><b>ModuleNotFoundError: No module named 'requests'</b> almost always means the package was installed into a <i>different</i> Python from the one running your script: the venv isn't activated, the script runs under <code>sudo</code> or cron (both use the system Python), or your editor picked another interpreter. Ask Python which one it is:</p>\n<pre><code>$ python -c \"import sys; print(sys.executable)\"\n$ python -m pip --version    # shows which Python this pip installs into</code></pre>\n<p>Also check the <b>import name</b>, which isn't always the package name: <code>pip install PyYAML</code> gives <code>import yaml</code>, <code>pip install python-dotenv</code> gives <code>import dotenv</code>, <code>pip install beautifulsoup4</code> gives <code>import bs4</code>.</p>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=t8pPdKYpowI&amp;t=13227s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Python Tutorial for Beginners (5 hours) <span class=\"learn-sources-part\">· Packages, PyPI and pip (3:40:27)</span></a><a href=\"https://www.youtube.com/watch?v=JJmcL1N2KQs&amp;t=3906s\" target=\"_blank\" rel=\"noopener noreferrer\">Traversy Media · Python Crash Course For Beginners <span class=\"learn-sources-part\">· Modules (1:05:06)</span></a></div>","python/json-yaml-calling-apis":"\n<p class=\"learn-lead\">DevOps is full of structured data: API responses are JSON, Kubernetes manifests and CI pipelines are YAML, and tools talk to each other over HTTP. This chapter goes beyond the quick JSON example from earlier: reading and writing both formats safely, and calling web APIs without your script hanging or crashing on the first network hiccup.</p>\n\n<h4>JSON in and out</h4>\n<p>JSON types map directly onto Python types:</p>\n<div class=\"learn-table-wrap\"><table class=\"learn-table\"><thead><tr><th>JSON</th><th>Python</th></tr></thead><tbody>\n<tr><td>object <code>{\"a\": 1}</code></td><td><code>dict</code></td></tr>\n<tr><td>array <code>[1, 2]</code></td><td><code>list</code> (tuples are written as arrays too)</td></tr>\n<tr><td>string, number</td><td><code>str</code>, <code>int</code> / <code>float</code></td></tr>\n<tr><td><code>true</code> / <code>false</code> / <code>null</code></td><td><code>True</code> / <code>False</code> / <code>None</code></td></tr>\n</tbody></table></div>\n<p>The four functions: <code>loads</code>/<code>dumps</code> work with <b>s</b>trings, <code>load</code>/<code>dump</code> work with open files.</p>\n<pre><code>import json\n\ntext = '{\"service\": \"api\", \"replicas\": 3, \"debug\": false}'\ndata = json.loads(text)          # str -&gt; dict\ndata[\"debug\"]                    # False\ndata[\"replicas\"] = 5\n\njson.dumps(data)                 # '{\"service\": \"api\", \"replicas\": 5, \"debug\": false}'\nprint(json.dumps(data, indent=2, sort_keys=True))\n# {\n#   \"debug\": false,\n#   \"replicas\": 5,\n#   \"service\": \"api\"\n# }\n\njson.dumps({\"name\": \"café\"})                      # '{\"name\": \"caf\\u00e9\"}'\njson.dumps({\"name\": \"café\"}, ensure_ascii=False)  # '{\"name\": \"café\"}'</code></pre>\n<p><code>indent</code> makes output readable, <code>sort_keys=True</code> keeps key order stable (nice for diffs in git), and <code>ensure_ascii=False</code> keeps non-English letters readable instead of <code>\\u</code> codes.</p>\n\n<h4>A config file with defaults</h4>\n<pre><code>import json\n\nDEFAULTS = {\"port\": 8080, \"log_level\": \"INFO\", \"timeout\": 5}\n\ndef load_config(path):\n    try:\n        with open(path, encoding=\"utf-8\") as f:\n            user = json.load(f)\n    except FileNotFoundError:\n        user = {}\n    return {**DEFAULTS, **user}    # values from the file win over the defaults\n\nconfig = load_config(\"config.json\")\n\nwith open(\"config.json\", \"w\", encoding=\"utf-8\") as f:\n    json.dump(config, f, indent=2)</code></pre>\n<p>From the shell, <code>python3 -m json.tool config.json</code> pretty-prints a file and reports exactly where it's broken, and <code>curl -s URL | python3 -m json.tool</code> does the same for an API response.</p>\n<p>Errors you'll see:</p>\n<ul>\n<li><code>Expecting property name enclosed in double quotes: line 1 column 2 (char 1)</code>: JSON needs double quotes, so <code>{'a': 1}</code> (Python style) is invalid. A trailing comma gives the same message in Python 3.12 (3.13 and newer say <code>Illegal trailing comma</code>).</li>\n<li><code>Expecting value: line 1 column 1 (char 0)</code>: the text is empty or isn't JSON at all, typically an HTML error page from an API.</li>\n<li><code>TypeError: Object of type datetime is not JSON serializable</code>: convert it first, or pass <code>default=str</code> to <code>dumps</code>.</li>\n</ul>\n\n<h4>YAML with PyYAML</h4>\n<p>YAML is what humans write config in: CI pipelines, Docker Compose, Kubernetes, Ansible. Install with <code>pip install PyYAML</code>, import as <code>yaml</code>.</p>\n<pre><code># services.yaml\ntimeout: 5\nservices:\n  - name: api\n    url: http://localhost:8000/health\n  - name: website\n    url: https://demee.cc</code></pre>\n<pre><code>import yaml\n\nwith open(\"services.yaml\", encoding=\"utf-8\") as f:\n    config = yaml.safe_load(f)     # -&gt; {'timeout': 5, 'services': [{...}, {...}]}\n\nfor svc in config[\"services\"]:\n    print(svc[\"name\"], svc[\"url\"])\n\nprint(yaml.safe_dump(config, sort_keys=False))   # dict -&gt; YAML text</code></pre>\n<ul>\n<li>Always use <b><code>safe_load</code></b>. Full <code>yaml.load</code> can build arbitrary Python objects from a file, which is dangerous with untrusted input; in PyYAML 6 it won't even run without an explicit <code>Loader</code>.</li>\n<li>Files with several documents separated by <code>---</code> (common in Kubernetes) need <code>yaml.safe_load_all(f)</code>, which yields one dict per document.</li>\n<li>YAML indentation must be spaces; a tab gives a <code>ScannerError</code>.</li>\n<li>YAML guesses types. <code>country: NO</code> loads as <code>False</code>, <code>yes</code>/<code>on</code> as <code>True</code>, and <code>version: 3.10</code> as the number <code>3.1</code>. Quote anything that must stay text: <code>version: \"3.10\"</code>.</li>\n</ul>\n\n<h4>Calling APIs with requests</h4>\n<p><code>requests</code> (<code>pip install requests</code>) is the standard HTTP library. A request has a method (<code>GET</code> to read, <code>POST</code> to create or send), a URL, optional headers and optionally a body; the response has a status code, headers and a body.</p>\n<figure class=\"learn-diagram dg\" data-dg=\"py-api\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 220\" role=\"img\" aria-label=\"The script sends a GET request with params and headers to the API, gets a 200 response with a JSON body, and resp.json() turns it into a Python dict\" style=\"--dgw:680px\"><defs><marker id=\"py-api--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker><marker id=\"py-api--ok\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk ok\" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"b hi\" x=\"10\" y=\"30\" width=\"180\" height=\"56\" rx=\"6\"/><text class=\"tb ta\" x=\"100\" y=\"54.7\" text-anchor=\"middle\" font-size=\"13\">your script</text><text class=\"t2\" x=\"100\" y=\"70.0\" text-anchor=\"middle\" font-size=\"11\">requests.get(url)</text><rect class=\"b\" x=\"490\" y=\"30\" width=\"180\" height=\"56\" rx=\"6\"/><text class=\"tb\" x=\"580\" y=\"54.7\" text-anchor=\"middle\" font-size=\"13\">the API</text><text class=\"t2\" x=\"580\" y=\"70.0\" text-anchor=\"middle\" font-size=\"11\">api.github.com</text><path class=\"ln\" d=\"M192,48 L488,48\" marker-end=\"url(#py-api--n)\"/><text class=\"tl\" x=\"340\" y=\"40\" text-anchor=\"middle\" font-size=\"11\">GET + params + headers</text><path class=\"ln ok\" d=\"M488,72 L192,72\" marker-end=\"url(#py-api--ok)\"/><text class=\"ok\" x=\"340\" y=\"92\" text-anchor=\"middle\" font-size=\"11\">200 OK + JSON body</text><rect class=\"b\" x=\"10\" y=\"130\" width=\"180\" height=\"56\" rx=\"6\"/><text class=\"tb tm\" x=\"100\" y=\"154.7\" text-anchor=\"middle\" font-size=\"13\">resp.json()</text><text class=\"t2\" x=\"100\" y=\"170.0\" text-anchor=\"middle\" font-size=\"11\">text -&gt; Python</text><rect class=\"b ok\" x=\"260\" y=\"130\" width=\"410\" height=\"56\" rx=\"6\"/><text class=\"tb tm\" x=\"465\" y=\"154.3\" text-anchor=\"middle\" font-size=\"12\">{&quot;items&quot;: [{&quot;name&quot;: ...}, ...]}</text><text class=\"t2\" x=\"465\" y=\"169.5\" text-anchor=\"middle\" font-size=\"11\">a dict you can loop over</text><path class=\"ln\" d=\"M100,88 L100,128\" marker-end=\"url(#py-api--n)\"/><path class=\"ln\" d=\"M192,158 L258,158\" marker-end=\"url(#py-api--n)\"/></svg></div><figcaption>Check <code>resp.status_code</code> (or call <code>raise_for_status()</code>) before trusting the body, and always pass a <code>timeout</code>.</figcaption></figure>\n\n<pre><code>import requests\n\nresp = requests.get(\n    \"https://api.github.com/search/repositories\",\n    params={\"q\": \"topic:devops\", \"sort\": \"stars\", \"per_page\": 5},   # the ?query=string\n    headers={\"Accept\": \"application/vnd.github+json\"},\n    timeout=10,\n)\nprint(resp.url)          # https://api.github.com/search/repositories?q=topic%3Adevops&amp;sort=stars&amp;per_page=5\nprint(resp.status_code)  # 200\nresp.raise_for_status()  # raises HTTPError for any 4xx / 5xx\nfor repo in resp.json()[\"items\"]:      # .json() parses the body into a dict\n    print(repo[\"full_name\"], repo[\"stargazers_count\"])</code></pre>\n<ul>\n<li><code>params=</code> builds and URL-encodes the query string for you.</li>\n<li><b>Always pass <code>timeout=</code></b>. requests has no default timeout, so a server that never answers makes your script wait forever.</li>\n<li><code>raise_for_status()</code> turns error status codes into exceptions. Without it, a 404 or 500 looks like a normal response.</li>\n<li><code>resp.text</code> is the raw body, <code>resp.headers</code> the response headers (case-insensitive dict).</li>\n</ul>\n<p>Sending data: <code>json=</code> encodes a dict as JSON and sets <code>Content-Type: application/json</code>, which is what most APIs and chat webhooks expect. <code>data=</code> sends it as an HTML form instead. Secrets come from the environment, never from the code:</p>\n<pre><code>import os\nimport requests\n\nresp = requests.post(\n    os.environ[\"WEBHOOK_URL\"],\n    json={\"text\": \"Deploy of api finished\"},   # Slack uses \"text\"; Discord uses \"content\"\n    headers={\"Authorization\": f\"Bearer {os.environ['API_TOKEN']}\"},\n    timeout=10,\n)\nresp.raise_for_status()</code></pre>\n\n<h4>Handling network errors</h4>\n<p>All requests errors inherit from <code>requests.exceptions.RequestException</code>, so you can catch specific ones first and everything else at the end:</p>\n<pre><code>import requests\n\ndef get_json(url):\n    try:\n        resp = requests.get(url, timeout=5)\n        resp.raise_for_status()\n        return resp.json()\n    except requests.exceptions.Timeout:\n        print(f\"{url}: timed out\")\n    except requests.exceptions.ConnectionError:\n        print(f\"{url}: could not connect (DNS, refused, network down)\")\n    except requests.exceptions.HTTPError as e:\n        print(f\"{url}: HTTP {e.response.status_code}\")\n    except requests.exceptions.JSONDecodeError:\n        print(f\"{url}: answered, but not with JSON\")\n    return None</code></pre>\n<p>The GitHub API is a good one to practise on: public data needs no token, but unauthenticated requests are limited to 60 per hour per IP address. Send a token in the <code>Authorization</code> header to get a higher limit, and read <code>resp.headers[\"X-RateLimit-Remaining\"]</code> to see how many calls you have left.</p>\n\n<h4>A realistic script: check every health endpoint</h4>\n<p>This reads the <code>services.yaml</code> from above, checks each URL with a couple of retries for network blips, prints a summary and exits non-zero if anything is down, so cron or a CI job can react.</p>\n<pre><code>#!/usr/bin/env python3\n\"\"\"check_services.py - hit every health endpoint listed in services.yaml.\"\"\"\nimport sys\nimport time\n\nimport requests\nimport yaml\n\n\ndef check(url, timeout, retries=2):\n    \"\"\"Return (ok, detail). Retries only connection problems, not HTTP errors.\"\"\"\n    for attempt in range(1, retries + 2):\n        try:\n            resp = requests.get(url, timeout=timeout)\n            resp.raise_for_status()\n            ms = resp.elapsed.total_seconds() * 1000\n            return True, f\"{resp.status_code} in {ms:.0f} ms\"\n        except requests.exceptions.HTTPError as e:\n            return False, f\"HTTP {e.response.status_code}\"    # it answered: don't retry\n        except requests.exceptions.RequestException as e:\n            if attempt &gt; retries:\n                return False, type(e).__name__\n            time.sleep(2 ** attempt)                           # wait 2 s, then 4 s\n\n\ndef main():\n    with open(\"services.yaml\", encoding=\"utf-8\") as f:\n        config = yaml.safe_load(f)\n\n    timeout = config.get(\"timeout\", 5)\n    failed = 0\n    for svc in config[\"services\"]:\n        ok, detail = check(svc[\"url\"], timeout)\n        print(f\"{'OK ' if ok else 'BAD'}  {svc['name']:&lt;10} {detail}\")\n        if not ok:\n            failed += 1\n    return 1 if failed else 0\n\n\nif __name__ == \"__main__\":\n    sys.exit(main())</code></pre>\n<pre><code>$ python check_services.py\nOK   api        200 in 3 ms\nBAD  website    HTTP 503\nBAD  admin      ConnectionError\n$ echo $?\n1</code></pre>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=JJmcL1N2KQs&amp;t=5457s\" target=\"_blank\" rel=\"noopener noreferrer\">Traversy Media · Python Crash Course For Beginners <span class=\"learn-sources-part\">· Working with JSON (1:30:57)</span></a><a href=\"https://www.youtube.com/watch?v=iYM2zFP3Zn0&amp;t=218s\" target=\"_blank\" rel=\"noopener noreferrer\">Traversy Media · HTTP Crash Course & Exploration <span class=\"learn-sources-part\">· HTTP request methods (3:38)</span></a><a href=\"https://www.youtube.com/watch?v=t8pPdKYpowI&amp;t=18875s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Python Tutorial for Beginners (5 hours) <span class=\"learn-sources-part\">· Project: API request to GitLab (5:14:35)</span></a></div>","python/automating-the-system":"\n<p class=\"learn-lead\">Once a shell script needs real error handling, options and logic, Python is usually the better tool. This chapter covers the standard-library modules that replace everyday shell work (files, environment variables, running commands, copying and archiving) and how to wrap them into a proper command-line tool with options, logs and exit codes.</p>\n\n<h4>pathlib: paths as objects</h4>\n<p><code>pathlib.Path</code> replaces string juggling with <code>os.path</code>. The <code>/</code> operator joins path parts, and methods do the file work:</p>\n<pre><code>from pathlib import Path\n\nlogs = Path(\"/var/log/myapp\")\nreport = Path.home() / \"reports\" / \"daily.txt\"      # /home/demee/reports/daily.txt\nreport.parent.mkdir(parents=True, exist_ok=True)     # like mkdir -p\n\nfor f in sorted(logs.glob(\"*.log\")):                 # rglob() searches subfolders too\n    print(f\"{f.name:&lt;20} {f.stat().st_size / 1024:8.1f} KB\")\n\nreport.write_text(\"all good\\n\")                      # create / overwrite\ntext = report.read_text()\n\np = Path(\"/etc/nginx/sites-available/site.conf\")\np.name, p.stem, p.suffix    # ('site.conf', 'site', '.conf')\np.parent                    # PosixPath('/etc/nginx/sites-available')\np.exists(), p.is_file(), p.is_dir()\np.with_suffix(\".bak\")       # PosixPath('/etc/nginx/sites-available/site.bak')\nPath(\"old.tmp\").unlink(missing_ok=True)              # delete, no error if already gone</code></pre>\n<p><code>f.stat()</code> gives file details: <code>st_size</code> in bytes and <code>st_mtime</code>, the last-modified time in seconds since 1970, which you compare with <code>time.time()</code> to find old files.</p>\n\n<h4>Environment variables</h4>\n<pre><code>import os\n\ndb_host = os.environ[\"DB_HOST\"]                    # KeyError if missing: fail early and loudly\nport = int(os.environ.get(\"PORT\", \"8080\"))         # default if missing; values are ALWAYS strings\ndebug = os.environ.get(\"DEBUG\", \"\").lower() in (\"1\", \"true\", \"yes\")</code></pre>\n<p>Watch the last line: <code>bool(\"false\")</code> is <code>True</code>, because any non-empty string is truthy, so compare the text explicitly. Assigning <code>os.environ[\"X\"] = \"1\"</code> affects your script and the commands it starts, never the shell that ran it.</p>\n\n<h4>Running commands with subprocess</h4>\n<pre><code>import subprocess\n\nresult = subprocess.run(\n    [\"systemctl\", \"is-active\", \"nginx\"],   # a list: program, then each argument\n    capture_output=True,                   # collect stdout/stderr instead of printing them\n    text=True,                             # give str, not bytes\n)\nresult.returncode          # 0 if active, non-zero otherwise\nresult.stdout.strip()      # 'active', 'inactive', 'failed'...\n\ntry:\n    commit = subprocess.run(\n        [\"git\", \"rev-parse\", \"--short\", \"HEAD\"],\n        capture_output=True, text=True, check=True, timeout=30,\n    ).stdout.strip()\nexcept FileNotFoundError:\n    print(\"git is not installed\")\nexcept subprocess.CalledProcessError as e:     # raised by check=True on a non-zero exit\n    print(f\"git failed ({e.returncode}): {e.stderr.strip()}\")\nexcept subprocess.TimeoutExpired:\n    print(\"git took too long\")</code></pre>\n<ul>\n<li>Without <code>check=True</code> a failing command is silently ignored unless you look at <code>returncode</code> yourself. It's the Python version of <code>set -e</code>.</li>\n<li>Pass arguments as a <b>list</b>. <code>shell=True</code> with a string lets the shell interpret it, so a file name like <code>x; rm -rf ~</code> coming from user input would run as a command. Only use it for fixed strings where you really need pipes or wildcards.</li>\n<li><code>shutil.which(\"docker\")</code> returns the path of a command or <code>None</code>, handy to check before calling it.</li>\n</ul>\n\n\n<figure class=\"learn-diagram dg\" data-dg=\"py-subprocess\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 200\" role=\"img\" aria-label=\"A Python script starts systemctl as a separate process with subprocess.run, waits for it, and gets back its return code and output\" style=\"--dgw:680px\"><defs><marker id=\"py-subprocess--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker><marker id=\"py-subprocess--ok\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk ok\" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"b hi\" x=\"10\" y=\"40\" width=\"230\" height=\"120\" rx=\"6\"/><text class=\"tb ta\" x=\"125\" y=\"81.7\" text-anchor=\"middle\" font-size=\"13\">your Python script</text><text class=\"t2\" x=\"125\" y=\"97.0\" text-anchor=\"middle\" font-size=\"11\">subprocess.run(</text><text class=\"t2\" x=\"125\" y=\"112.0\" text-anchor=\"middle\" font-size=\"11\">[&quot;systemctl&quot;,</text><text class=\"t2\" x=\"125\" y=\"127.0\" text-anchor=\"middle\" font-size=\"11\">&quot;is-active&quot;, &quot;nginx&quot;])</text><rect class=\"b\" x=\"440\" y=\"60\" width=\"230\" height=\"80\" rx=\"6\"/><text class=\"tb\" x=\"555\" y=\"96.7\" text-anchor=\"middle\" font-size=\"13\">a new process</text><text class=\"t2\" x=\"555\" y=\"112.0\" text-anchor=\"middle\" font-size=\"11\">systemctl is-active nginx</text><path class=\"ln\" d=\"M242,76 L438,76\" marker-end=\"url(#py-subprocess--n)\"/><text class=\"tl\" x=\"340\" y=\"68\" text-anchor=\"middle\" font-size=\"11\">starts and waits</text><path class=\"ln ok\" d=\"M438,124 L242,124\" marker-end=\"url(#py-subprocess--ok)\"/><text class=\"ok\" x=\"340\" y=\"146\" text-anchor=\"middle\" font-size=\"11\">returncode 0, stdout &quot;active&quot;</text></svg></div><figcaption>Pass the command as a list, one item per argument. You get back the same three things a shell gives you: an exit code, stdout and stderr.</figcaption></figure>\n<h4>shutil: copying, moving, archiving, disk space</h4>\n<pre><code>import shutil\n\nshutil.copy2(\"app.conf\", \"app.conf.bak\")                  # copy a file, keeping timestamps\nshutil.copytree(\"site\", \"site-backup\", dirs_exist_ok=True) # copy a whole folder\nshutil.move(\"report.txt\", \"archive/\")                     # move or rename\nshutil.make_archive(\"backup-2026-09-27\", \"gztar\", root_dir=\"app\")\n#   -&gt; backup-2026-09-27.tar.gz with the contents of app/\nusage = shutil.disk_usage(\"/\")                            # total, used, free (bytes)\nprint(f\"{usage.free / 1e9:.1f} GB free\")\nshutil.rmtree(\"build\")                                    # rm -r: no confirmation, no undo</code></pre>\n\n<h4>argparse: a real command-line interface</h4>\n<p><code>sys.argv</code> is the raw list of arguments; <code>argparse</code> turns it into named options with types, defaults, validation and an automatic <code>--help</code>. The full script at the end of this chapter uses it; the core is:</p>\n<pre><code>import argparse\nfrom pathlib import Path\n\np = argparse.ArgumentParser(description=\"Delete old log files.\")\np.add_argument(\"directory\", type=Path)                   # positional, required\np.add_argument(\"--days\", type=int, default=14)           # optional, converted to int\np.add_argument(\"--dry-run\", action=\"store_true\")         # flag: False unless given\nargs = p.parse_args()                                    # --dry-run becomes args.dry_run</code></pre>\n<p>Bad input is handled for you: <code>--days abc</code> prints <code>error: argument --days: invalid int value: 'abc'</code> and exits with code 2. One quirk: help texts are %-formatted, so a literal percent sign must be written <code>%%</code>.</p>\n\n<h4>logging instead of print</h4>\n<pre><code>import logging\n\nlogging.basicConfig(level=logging.INFO,\n                    format=\"%(asctime)s %(levelname)s %(message)s\")\nlog = logging.getLogger(\"backup\")\n\nlog.debug(\"hidden: DEBUG is below the INFO level\")\nlog.info(\"backing up %s\", \"/srv/app\")        # values passed separately, formatted by logging\nlog.warning(\"disk is %d%% full\", 85)\ntry:\n    1 / 0\nexcept ZeroDivisionError:\n    log.exception(\"backup failed\")           # ERROR level plus the full traceback</code></pre>\n<pre><code>2026-09-27 10:15:02,114 INFO backing up /srv/app\n2026-09-27 10:15:02,114 WARNING disk is 85% full\n2026-09-27 10:15:02,114 ERROR backup failed\nTraceback (most recent call last):\n  ...\nZeroDivisionError: division by zero</code></pre>\n<p>Levels from least to most serious: DEBUG, INFO, WARNING, ERROR, CRITICAL. Only messages at or above the configured level appear, so you can turn on detail with <code>level=logging.DEBUG</code> without touching the rest of the code. Without <code>basicConfig</code> only warnings and above are shown. Logging writes to <b>stderr</b> by default, which systemd captures into the journal and cron sends wherever you redirected <code>2&gt;&amp;1</code>; add <code>filename=\"app.log\"</code> to write to a file instead.</p>\n\n<h4>Exit codes with sys.exit</h4>\n<p>Like a shell script, a Python script tells the caller whether it worked through its exit code. <code>sys.exit(0)</code> is success, <code>sys.exit(1)</code> (or any other number) is failure, and <code>sys.exit(\"message\")</code> prints the message to stderr and exits with 1. An unhandled exception also exits with 1. The clean pattern is a <code>main()</code> that <i>returns</i> the code.</p>\n\n<h4>Putting it together: log cleanup with a disk alert</h4>\n<pre><code>#!/usr/bin/env python3\n\"\"\"Delete old rotated log files, then warn if the disk is still too full.\"\"\"\nimport argparse\nimport logging\nimport shutil\nimport sys\nimport time\nfrom pathlib import Path\n\nlog = logging.getLogger(\"cleanup\")\n\n\ndef parse_args():\n    p = argparse.ArgumentParser(description=__doc__)\n    p.add_argument(\"directory\", type=Path, help=\"folder to clean, e.g. /var/log/myapp\")\n    p.add_argument(\"--days\", type=int, default=14,\n                   help=\"delete files older than this many days (default: 14)\")\n    p.add_argument(\"--pattern\", default=\"*.gz\",\n                   help=\"which files may be deleted (default: *.gz)\")\n    p.add_argument(\"--threshold\", type=int, default=90,\n                   help=\"disk usage %% that counts as a problem (default: 90)\")\n    p.add_argument(\"--dry-run\", action=\"store_true\",\n                   help=\"only show what would be deleted\")\n    return p.parse_args()\n\n\ndef old_files(directory, pattern, days):\n    cutoff = time.time() - days * 24 * 60 * 60\n    for path in directory.glob(pattern):\n        if path.is_file() and path.stat().st_mtime &lt; cutoff:\n            yield path\n\n\ndef main():\n    args = parse_args()\n    logging.basicConfig(level=logging.INFO,\n                        format=\"%(asctime)s %(levelname)s %(message)s\")\n\n    if not args.directory.is_dir():\n        log.error(\"%s is not a directory\", args.directory)\n        return 2\n\n    freed = 0\n    for path in old_files(args.directory, args.pattern, args.days):\n        size = path.stat().st_size\n        if args.dry_run:\n            log.info(\"would delete %s (%d KB)\", path, size // 1024)\n        else:\n            try:\n                path.unlink()\n            except PermissionError:\n                log.warning(\"no permission to delete %s\", path)\n                continue\n            log.info(\"deleted %s\", path)\n        freed += size\n    log.info(\"%s %.1f MB\", \"would free\" if args.dry_run else \"freed\", freed / 1_000_000)\n\n    usage = shutil.disk_usage(args.directory)\n    percent = usage.used / (usage.used + usage.free) * 100   # same formula as df\n    if percent &gt;= args.threshold:\n        log.error(\"disk is %.0f%% full (threshold %d%%)\", percent, args.threshold)\n        return 1\n    log.info(\"disk is %.0f%% full, ok\", percent)\n    return 0\n\n\nif __name__ == \"__main__\":\n    sys.exit(main())</code></pre>\n<pre><code>$ python3 cleanup_logs.py /var/log/myapp --days 30 --dry-run\n2026-09-27 10:20:11,482 INFO would delete /var/log/myapp/app.log.5.gz (292 KB)\n2026-09-27 10:20:11,482 INFO would delete /var/log/myapp/app.log.6.gz (288 KB)\n2026-09-27 10:20:11,483 INFO would free 0.6 MB\n2026-09-27 10:20:11,483 INFO disk is 29% full, ok\n\n# happy with the list? schedule it (crontab -e) and keep its log:\n30 4 * * * /usr/bin/python3 /opt/scripts/cleanup_logs.py /var/log/myapp --days 30 &gt;&gt; /var/log/cleanup.log 2&gt;&amp;1</code></pre>\n<p>Design choices worth copying: a <code>--dry-run</code> flag for anything that deletes, one exit code per outcome (0 fine, 1 disk still full, 2 bad input, the same code argparse uses), a permission problem on one file logged instead of crashing the whole run, and only the standard library, so it runs with the system <code>python3</code> and needs no virtual environment on the server. The disk percentage uses <code>used / (used + free)</code> because that's how <code>df</code> computes <code>Use%</code>: part of the disk is reserved for root, so <code>used / total</code> would look lower than what <code>df</code> shows.</p>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=guCFLTU-XRM&amp;t=95s\" target=\"_blank\" rel=\"noopener noreferrer\">Cloud Champ · How I use Python as a DevOps Engineer <span class=\"learn-sources-part\">· Use case: scripting and automation (1:35)</span></a><a href=\"https://www.youtube.com/watch?v=guCFLTU-XRM&amp;t=305s\" target=\"_blank\" rel=\"noopener noreferrer\">Cloud Champ · How I use Python as a DevOps Engineer <span class=\"learn-sources-part\">· Use case: monitoring and alerting (5:05)</span></a><a href=\"https://www.youtube.com/watch?v=JJmcL1N2KQs&amp;t=5177s\" target=\"_blank\" rel=\"noopener noreferrer\">Traversy Media · Python Crash Course For Beginners <span class=\"learn-sources-part\">· Working with files (1:26:17)</span></a></div>","networking/models-addressing":"\n<p class=\"learn-lead\">Networking is how one machine finds and talks to another. Several of your videos follow one app as it grows from a single server into a cloud system; this first chapter covers the basics every step builds on: layers, addresses and how a packet leaves your local network.</p>\n\n<h4>Layers: the OSI and TCP/IP models</h4>\n<p>Sending data is split into layers, each solving one problem and relying on the layer below. The <b>OSI model</b> has 7:</p>\n<ol>\n<li><b>Physical</b>: cables, Wi-Fi radio, electrical signals.</li>\n<li><b>Data link</b>: getting a frame to the next device on the same local network, using MAC addresses (Ethernet, Wi-Fi, switches).</li>\n<li><b>Network</b>: getting packets across many networks using IP addresses and routers.</li>\n<li><b>Transport</b>: delivering data to the right program on the machine, reliably (TCP) or quickly (UDP), using ports.</li>\n<li><b>Session</b>: opening, managing and closing conversations.</li>\n<li><b>Presentation</b>: formatting, compression and encryption of the data.</li>\n<li><b>Application</b>: what the program actually speaks: HTTP, DNS, SSH, SMTP.</li>\n</ol>\n<p>In practice people use the simpler 4-layer <b>TCP/IP model</b> (Link, Internet, Transport, Application), which folds the top three OSI layers into one. The layer numbers are still used as shorthand: a \"layer 4 load balancer\" works with IPs and ports, a \"layer 7\" one understands HTTP.</p>\n<p>Each layer wraps the data from the layer above with its own header, like envelopes inside envelopes:</p>\n{{DIAG:TCPIP}}\n\n<h4>MAC addresses and switches</h4>\n<p>Every network card has a <b>MAC address</b> burned in (like <code>3c:22:fb:1a:9e:01</code>). It only matters on the local network. A <b>switch</b> connects the devices of one local network and learns which MAC address sits on which port, so it can pass frames only to the right device. <b>ARP</b> is how a machine finds the MAC address that belongs to a local IP address.</p>\n\n<h4>IP addresses</h4>\n<p>An <b>IP address</b> identifies a device across networks. <b>IPv4</b> addresses are 32 bits written as four numbers from 0 to 255 (<code>192.168.1.10</code>), about 4.3 billion in total, which isn't enough for the modern internet. <b>IPv6</b> uses 128 bits written in hex (<code>2001:db8::1</code>) and has practically unlimited addresses.</p>\n<p>Some ranges are reserved as <b>private</b> (RFC 1918): <code>10.0.0.0/8</code>, <code>172.16.0.0/12</code> and <code>192.168.0.0/16</code>. They're used inside homes, offices and cloud networks and are never routed on the public internet, so millions of networks can reuse them. A <b>public</b> IP is unique on the internet. <code>127.0.0.1</code> (<code>localhost</code>) always means \"this machine\".</p>\n<p>Addresses are handed out either by hand (<b>static</b>, typical for servers, so their address never changes) or automatically by a <b>DHCP</b> server, which is what your laptop gets when it joins Wi-Fi.</p>\n\n<h4>Subnets and CIDR</h4>\n<p>A <b>subnet</b> is a block of addresses that belong to one network. <b>CIDR</b> notation writes it as an address plus a slash number: the number says how many bits, from the left, are the network part. The rest are for hosts.</p>\n<figure class=\"learn-diagram dg\" data-dg=\"net-cidr\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 220\" role=\"img\" aria-label=\"192.168.1.0/24: the first three 8-bit octets are the fixed network part, the last 8 bits number the hosts, giving 256 addresses\" style=\"--dgw:680px\"><text class=\"tc tb\" x=\"340\" y=\"22\" text-anchor=\"middle\" font-size=\"16\">192.168.1.0/24</text><rect class=\"b hi\" x=\"20\" y=\"38\" width=\"150\" height=\"46\" rx=\"6\"/><text class=\"tb ta tm\" x=\"95\" y=\"59.1\" text-anchor=\"middle\" font-size=\"16\">192</text><text class=\"t2\" x=\"95\" y=\"74.2\" text-anchor=\"middle\" font-size=\"10\">8 bits</text><rect class=\"b hi\" x=\"182\" y=\"38\" width=\"150\" height=\"46\" rx=\"6\"/><text class=\"tb ta tm\" x=\"257\" y=\"59.1\" text-anchor=\"middle\" font-size=\"16\">168</text><text class=\"t2\" x=\"257\" y=\"74.2\" text-anchor=\"middle\" font-size=\"10\">8 bits</text><rect class=\"b hi\" x=\"344\" y=\"38\" width=\"150\" height=\"46\" rx=\"6\"/><text class=\"tb ta tm\" x=\"419\" y=\"59.1\" text-anchor=\"middle\" font-size=\"16\">1</text><text class=\"t2\" x=\"419\" y=\"74.2\" text-anchor=\"middle\" font-size=\"10\">8 bits</text><rect class=\"b ok\" x=\"506\" y=\"38\" width=\"150\" height=\"46\" rx=\"6\"/><text class=\"tb tm\" x=\"581\" y=\"59.1\" text-anchor=\"middle\" font-size=\"16\">0-255</text><text class=\"t2\" x=\"581\" y=\"74.2\" text-anchor=\"middle\" font-size=\"10\">8 bits</text><path class=\"ln hi\" d=\"M20,100 L494,100\"/><text class=\"ta tb\" x=\"257\" y=\"118\" text-anchor=\"middle\" font-size=\"12\">24 network bits: fixed</text><path class=\"ln ok\" d=\"M506,100 L656,100\"/><text class=\"ok tb\" x=\"581\" y=\"118\" text-anchor=\"middle\" font-size=\"12\">8 host bits</text><text class=\"tc tb\" x=\"40\" y=\"150\" text-anchor=\"start\" font-size=\"12\">/16</text><text class=\"tc\" x=\"100\" y=\"150\" text-anchor=\"start\" font-size=\"12\">65,536 addresses</text><text class=\"t2\" x=\"300\" y=\"150\" text-anchor=\"start\" font-size=\"12\">a whole cloud network (VPC)</text><text class=\"tc tb\" x=\"40\" y=\"172\" text-anchor=\"start\" font-size=\"12\">/24</text><text class=\"tc\" x=\"100\" y=\"172\" text-anchor=\"start\" font-size=\"12\">256 addresses</text><text class=\"t2\" x=\"300\" y=\"172\" text-anchor=\"start\" font-size=\"12\">a typical subnet</text><text class=\"tc tb\" x=\"40\" y=\"194\" text-anchor=\"start\" font-size=\"12\">/28</text><text class=\"tc\" x=\"100\" y=\"194\" text-anchor=\"start\" font-size=\"12\">16 addresses</text><text class=\"t2\" x=\"300\" y=\"194\" text-anchor=\"start\" font-size=\"12\">a tiny subnet</text></svg></div><figcaption>The slash number counts the fixed bits from the left. Every bit you take away from it doubles the number of addresses.</figcaption></figure>\n\n<ul>\n<li><code>192.168.1.0/24</code>: the first 24 bits (192.168.1) are fixed, the last 8 bits vary, so 2<sup>8</sup> = 256 addresses (192.168.1.0 to 192.168.1.255). The same as subnet mask <code>255.255.255.0</code>.</li>\n<li><code>10.0.0.0/16</code>: 16 bits vary, so 65,536 addresses. A typical size for a whole cloud network.</li>\n<li><code>10.0.1.0/28</code>: 4 bits vary, so 16 addresses. Bigger slash number, smaller network.</li>\n</ul>\n<p>Two addresses in each subnet are special (the network address and the broadcast address), and clouds reserve a few more, so a /24 gives you slightly fewer than 256 usable hosts.</p>\n\n<h4>Routers and the default gateway</h4>\n<p>If the destination is in your own subnet, your machine delivers directly. Otherwise it sends the packet to its <b>default gateway</b>, the router for its network. A <b>router</b> connects networks and forwards each packet one hop closer to its destination using its <b>routing table</b>. Small networks use static routes typed in by hand; large ones share routes automatically with routing protocols: <b>OSPF</b> inside an organisation, and <b>BGP</b> between the big networks that make up the internet.</p>\n<p>Your home router also does <b>NAT</b> (network address translation): all your private devices go out to the internet sharing its one public IP, and it remembers which reply belongs to which device.</p>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=bdeV_TjNfFA&amp;t=31s\" target=\"_blank\" rel=\"noopener noreferrer\">Tech With Diego · Every Networking Concept Explained (Networking 101) <span class=\"learn-sources-part\">· Ethernet, MAC, switch, IP, DHCP, subnet, router (0:31)</span></a><a href=\"https://www.youtube.com/watch?v=M9Kex1ID7GY&amp;t=56s\" target=\"_blank\" rel=\"noopener noreferrer\">Cloud Champ · Networking Fundamentals for DevOps Engineers <span class=\"learn-sources-part\">· OSI model (0:56)</span></a><a href=\"https://www.youtube.com/watch?v=M9Kex1ID7GY&amp;t=469s\" target=\"_blank\" rel=\"noopener noreferrer\">Cloud Champ · Networking Fundamentals for DevOps Engineers <span class=\"learn-sources-part\">· Subnetting and CIDR (7:49)</span></a><a href=\"https://www.youtube.com/watch?v=gyXfooY7MqU&amp;t=91s\" target=\"_blank\" rel=\"noopener noreferrer\">DevOps For Developers · The 20% of networking you'll use 80% of the time <span class=\"learn-sources-part\">· IP addresses, subnet masks, RFC 1918 (1:31)</span></a><a href=\"https://www.youtube.com/watch?v=bEFAFHIahXk&amp;t=86s\" target=\"_blank\" rel=\"noopener noreferrer\">Vishakha Sadhwani · Learn Networking In 25 Minutes <span class=\"learn-sources-part\">· Pillar 1: addressing (1:26)</span></a></div>","networking/protocols-ports-dns":"\n<p class=\"learn-lead\">An IP address gets data to the right machine. Ports get it to the right program on that machine, TCP or UDP decide how carefully it's delivered, and DNS turns names like <code>google.com</code> into addresses in the first place.</p>\n\n<h4>TCP: reliable, in order</h4>\n<p><b>TCP</b> sets up a connection before sending anything, with the <b>three-way handshake</b>: the client sends SYN (\"let's talk\"), the server answers SYN-ACK (\"OK\"), the client replies ACK (\"great\"). After that, every piece of data is numbered and acknowledged: lost pieces are sent again and everything arrives in the right order. That reliability costs a little speed. Web pages, SSH, email, database connections and file transfers all use TCP.</p>\n<figure class=\"learn-diagram dg\" data-dg=\"net-tcp\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 640 250\" role=\"img\" aria-label=\"TCP three-way handshake: the client sends SYN, the server answers SYN-ACK, the client sends ACK, then numbered data flows\" style=\"--dgw:640px\"><defs><marker id=\"net-tcp--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker><marker id=\"net-tcp--ok\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk ok\" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"b hi\" x=\"40\" y=\"10\" width=\"160\" height=\"40\" rx=\"6\"/><text class=\"tb ta\" x=\"120\" y=\"34.2\" text-anchor=\"middle\" font-size=\"13\">client</text><rect class=\"b\" x=\"440\" y=\"10\" width=\"160\" height=\"40\" rx=\"6\"/><text class=\"tb\" x=\"520\" y=\"34.2\" text-anchor=\"middle\" font-size=\"13\">server</text><path class=\"ln  dash\" d=\"M120,52 L120,240\"/><path class=\"ln  dash\" d=\"M520,52 L520,240\"/><path class=\"ln\" d=\"M122,80 L518,94\" marker-end=\"url(#net-tcp--n)\"/><text class=\"tl\" x=\"320\" y=\"78\" text-anchor=\"middle\" font-size=\"11\">SYN  &quot;let&#x27;s talk&quot;</text><path class=\"ln\" d=\"M518,118 L122,132\" marker-end=\"url(#net-tcp--n)\"/><text class=\"tl\" x=\"320\" y=\"116\" text-anchor=\"middle\" font-size=\"11\">SYN-ACK  &quot;OK&quot;</text><path class=\"ln\" d=\"M122,156 L518,170\" marker-end=\"url(#net-tcp--n)\"/><text class=\"tl\" x=\"320\" y=\"154\" text-anchor=\"middle\" font-size=\"11\">ACK  &quot;great&quot;</text><path class=\"ln ok\" d=\"M122,204 L518,218\" marker-end=\"url(#net-tcp--ok)\"/><text class=\"tl\" x=\"320\" y=\"202\" text-anchor=\"middle\" font-size=\"11\">data, numbered and acknowledged</text><text class=\"ok tb\" x=\"30\" y=\"172\" text-anchor=\"start\" font-size=\"11\">connected</text></svg></div><figcaption>Three messages before any data. That round trip is the price of TCP's guarantee: everything arrives, in order, or the connection reports an error.</figcaption></figure>\n\n\n<h4>UDP: fast, no guarantees</h4>\n<p><b>UDP</b> just fires packets at the destination: no handshake, no acknowledgements, no resending. Some may be lost or arrive out of order, but it has less delay and overhead. It fits cases where speed matters more than perfection: DNS lookups, video calls, live streaming and online games (a lost video frame is better than a frozen call).</p>\n<p><b>ICMP</b> is a third protocol used for control messages, not app data. <code>ping</code> uses it to ask \"are you there?\" and measure the round trip.</p>\n\n<h4>Ports</h4>\n<p>One server runs many programs, so each one listens on a numbered <b>port</b> (0 to 65535). An IP address plus a port, like <code>203.0.113.10:443</code>, names one specific service. Ports below 1024 are \"well-known\" and need root to open. The ones worth memorising:</p>\n<div class=\"learn-table-wrap\"><table class=\"learn-table\">\n<tr><th>Port</th><th>Service</th><th>Port</th><th>Service</th></tr>\n<tr><td>22</td><td>SSH</td><td>80</td><td>HTTP</td></tr>\n<tr><td>25</td><td>SMTP (sending email)</td><td>443</td><td>HTTPS</td></tr>\n<tr><td>53</td><td>DNS</td><td>3306</td><td>MySQL</td></tr>\n<tr><td>21</td><td>FTP</td><td>5432</td><td>PostgreSQL</td></tr>\n<tr><td>3389</td><td>Windows remote desktop</td><td>6379</td><td>Redis</td></tr>\n</table></div>\n<p>The program on your side of a connection gets a random high port for the reply to come back to. <code>ss -tulpn</code> lists which ports are listening on a Linux machine and which program owns each.</p>\n\n<h4>DNS: the internet's phone book</h4>\n<p>People remember names, computers need IP addresses. <b>DNS</b> translates one into the other. When you open <code>demee.cc</code>:</p>\n<ol>\n<li>Your computer checks its own cache and <code>/etc/hosts</code>.</li>\n<li>If it doesn't know, it asks a <b>resolver</b> (your ISP's, or a public one like 1.1.1.1 or 8.8.8.8).</li>\n<li>The resolver asks a <b>root server</b>, which points it to the servers for <code>.cc</code> (the TLD).</li>\n<li>Those point it to the domain's <b>authoritative</b> name servers (for your domain, Cloudflare's).</li>\n<li>The authoritative server gives the answer, and the resolver passes it back and caches it for the record's <b>TTL</b> (time to live).</li>\n</ol>\n{{DIAG:DNS}}\n<p>The record types you'll set up yourself:</p>\n<ul>\n<li><b>A</b>: name to IPv4 address. <b>AAAA</b>: name to IPv6 address.</li>\n<li><b>CNAME</b>: an alias pointing one name to another name (<code>www</code> to the main domain, or <code>study</code> to <code>devops-site-ao3.pages.dev</code>).</li>\n<li><b>MX</b>: which mail servers accept email for the domain.</li>\n<li><b>TXT</b>: free text, used to prove you own a domain and for email security (SPF, DKIM).</li>\n<li><b>NS</b>: which name servers are authoritative for the domain.</li>\n</ul>\n<div class=\"learn-callout\">DNS changes aren't instant everywhere: resolvers keep old answers until the TTL runs out. When a new record \"doesn't work yet\", that's usually why. <code>dig demee.cc</code> shows exactly what DNS is answering right now.</div>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=bdeV_TjNfFA&amp;t=255s\" target=\"_blank\" rel=\"noopener noreferrer\">Tech With Diego · Every Networking Concept Explained (Networking 101) <span class=\"learn-sources-part\">· Ping, ICMP, TCP, UDP, ports (4:15)</span></a><a href=\"https://www.youtube.com/watch?v=M9Kex1ID7GY&amp;t=180s\" target=\"_blank\" rel=\"noopener noreferrer\">Cloud Champ · Networking Fundamentals for DevOps Engineers <span class=\"learn-sources-part\">· TCP vs UDP vs IP, and ports (3:00)</span></a><a href=\"https://www.youtube.com/watch?v=M9Kex1ID7GY&amp;t=647s\" target=\"_blank\" rel=\"noopener noreferrer\">Cloud Champ · Networking Fundamentals for DevOps Engineers <span class=\"learn-sources-part\">· DNS and record types (10:47)</span></a><a href=\"https://www.youtube.com/watch?v=xj_GjnD4uyI&amp;t=46s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Every Networking Concept Explained In 20 Minutes <span class=\"learn-sources-part\">· IP, DNS and ports on a single server (0:46)</span></a></div>","networking/http-rest":"\n<p class=\"learn-lead\">HTTP is the language of the web and of almost every API you'll automate against. Once you can read a request and a response, debugging a website or a pipeline that calls an API becomes much easier.</p>\n\n<h4>Request and response</h4>\n<figure class=\"learn-diagram dg\" data-dg=\"net-http\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 230\" role=\"img\" aria-label=\"An HTTP request with a first line, headers and no body goes from client to server; the response comes back with a status line, headers and a JSON body\" style=\"--dgw:680px\"><defs><marker id=\"net-http--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker><marker id=\"net-http--ok\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk ok\" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"b hi\" x=\"10\" y=\"80\" width=\"130\" height=\"60\" rx=\"6\"/><text class=\"tb ta\" x=\"75\" y=\"106.7\" text-anchor=\"middle\" font-size=\"13\">client</text><text class=\"t2\" x=\"75\" y=\"122.0\" text-anchor=\"middle\" font-size=\"11\">browser, curl</text><rect class=\"b\" x=\"540\" y=\"80\" width=\"130\" height=\"60\" rx=\"6\"/><text class=\"tb\" x=\"605\" y=\"106.7\" text-anchor=\"middle\" font-size=\"13\">server</text><text class=\"t2\" x=\"605\" y=\"122.0\" text-anchor=\"middle\" font-size=\"11\">api.example.com</text><rect class=\"g\" x=\"170\" y=\"10\" width=\"340\" height=\"100\" rx=\"8\"/><text class=\"tg \" x=\"180\" y=\"26\" font-size=\"11\">request</text><text class=\"ta tb\" x=\"184\" y=\"46\" text-anchor=\"start\" font-size=\"12\">GET /api/users/42 HTTP/1.1</text><text class=\"tc\" x=\"184\" y=\"66\" text-anchor=\"start\" font-size=\"12\">Accept: application/json</text><text class=\"tc\" x=\"184\" y=\"86\" text-anchor=\"start\" font-size=\"12\">(no body for a GET)</text><rect class=\"g ok\" x=\"170\" y=\"122\" width=\"340\" height=\"100\" rx=\"8\"/><text class=\"tg ok\" x=\"180\" y=\"138\" font-size=\"11\">response</text><text class=\"ta tb\" x=\"184\" y=\"158\" text-anchor=\"start\" font-size=\"12\">HTTP/1.1 200 OK</text><text class=\"tc\" x=\"184\" y=\"178\" text-anchor=\"start\" font-size=\"12\">Content-Type: application/json</text><text class=\"tc\" x=\"184\" y=\"198\" text-anchor=\"start\" font-size=\"12\">{&quot;id&quot;: 42, &quot;name&quot;: &quot;Demee&quot;}</text><path class=\"ln\" d=\"M142,100 L168,60\" marker-end=\"url(#net-http--n)\"/><path class=\"ln\" d=\"M512,60 L538,100\" marker-end=\"url(#net-http--n)\"/><path class=\"ln ok\" d=\"M538,122 L512,172\" marker-end=\"url(#net-http--ok)\"/><path class=\"ln ok\" d=\"M168,172 L142,124\" marker-end=\"url(#net-http--ok)\"/></svg></div><figcaption>Both messages have the same shape: a first line, headers, then an optional body. The status code in the response's first line tells you how it went.</figcaption></figure>\n\n<p>HTTP is a simple conversation: the client (a browser, <code>curl</code>, a script) sends a <b>request</b>, the server sends back a <b>response</b>. Each has a first line, <b>headers</b> (key: value metadata) and an optional <b>body</b>.</p>\n<pre><code>GET /api/users/42 HTTP/1.1          ← method, path, version\nHost: api.example.com               ← headers\nAuthorization: Bearer eyJhbGciOi...\nAccept: application/json\n\nHTTP/1.1 200 OK                     ← status code\nContent-Type: application/json\nContent-Length: 58\n\n{\"id\": 42, \"name\": \"Demee\", \"role\": \"admin\"}   ← body</code></pre>\n<p>HTTP is <b>stateless</b>: the server doesn't remember you between requests. Anything that should carry over (being logged in) has to be sent again every time, usually as a <b>cookie</b> or an <code>Authorization</code> header with a token. That's exactly how this site's login works: after you sign in, the browser sends a session cookie with every request.</p>\n\n<h4>Methods</h4>\n<ul>\n<li><b>GET</b> reads data and shouldn't change anything.</li>\n<li><b>POST</b> creates something or submits data (a form, a new user).</li>\n<li><b>PUT</b> replaces a resource completely; <b>PATCH</b> changes part of it.</li>\n<li><b>DELETE</b> removes it.</li>\n</ul>\n<p>GET, PUT and DELETE are <b>idempotent</b>: doing them twice has the same effect as doing them once. POST isn't: sending it twice may create two records, which is why browsers warn before resubmitting a form.</p>\n\n<h4>Status codes</h4>\n<ul>\n<li><b>2xx success</b>: 200 OK, 201 Created, 204 No Content.</li>\n<li><b>3xx redirect</b>: 301 Moved Permanently, 302 Found (temporary), 304 Not Modified (use your cached copy).</li>\n<li><b>4xx the client's fault</b>: 400 Bad Request, 401 Unauthorized (you're not logged in), 403 Forbidden (logged in, but not allowed), 404 Not Found, 429 Too Many Requests (rate limited).</li>\n<li><b>5xx the server's fault</b>: 500 Internal Server Error (the app crashed), 502 Bad Gateway (a proxy got no valid answer from the app behind it), 503 Service Unavailable (overloaded or down for maintenance), 504 Gateway Timeout.</li>\n</ul>\n<div class=\"learn-callout\">A 502 from Nginx almost always means \"Nginx is fine, but the app it forwards to isn't running or crashed\". Check the app, not Nginx.</div>\n\n<h4>HTTPS and TLS</h4>\n<p>Plain HTTP travels as readable text. <b>HTTPS</b> is HTTP inside a <b>TLS</b> encrypted connection (TLS is the modern version of SSL). During the TLS handshake the server shows a <b>certificate</b> signed by a trusted certificate authority, proving it really is <code>demee.cc</code>; then both sides agree on keys and everything after that is encrypted. HTTPS uses port 443. Free certificates come from Let's Encrypt, or automatically from Cloudflare.</p>\n<p><b>HTTP/2</b> keeps the same methods and codes but sends many requests at once over a single connection, which makes pages with lots of files load faster.</p>\n\n<h4>REST APIs</h4>\n<p><b>REST</b> is a common style for web APIs: URLs name <b>resources</b> (nouns), and the HTTP method says what to do with them. The body is usually JSON.</p>\n<pre><code>GET    /users        # list users\nPOST   /users        # create a user (details in the JSON body)\nGET    /users/42     # one user\nPUT    /users/42     # replace user 42\nDELETE /users/42     # delete user 42</code></pre>\n<p>You can try any API from the terminal with <code>curl</code>, or with a GUI tool like Postman:</p>\n<pre><code>$ curl https://api.github.com/users/octocat          # GET\n$ curl -I https://demee.cc                            # headers only\n$ curl -v https://demee.cc                            # show the whole conversation\n$ curl -X POST https://api.example.com/users \\\n       -H \"Content-Type: application/json\" \\\n       -H \"Authorization: Bearer $TOKEN\" \\\n       -d '{\"name\": \"Demee\"}'</code></pre>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=iYM2zFP3Zn0&amp;t=85s\" target=\"_blank\" rel=\"noopener noreferrer\">Traversy Media · HTTP Crash Course & Exploration <span class=\"learn-sources-part\">· HTTP basics and statelessness (1:25)</span></a><a href=\"https://www.youtube.com/watch?v=iYM2zFP3Zn0&amp;t=218s\" target=\"_blank\" rel=\"noopener noreferrer\">Traversy Media · HTTP Crash Course & Exploration <span class=\"learn-sources-part\">· Methods, headers and status codes (3:38)</span></a><a href=\"https://www.youtube.com/watch?v=iYM2zFP3Zn0&amp;t=766s\" target=\"_blank\" rel=\"noopener noreferrer\">Traversy Media · HTTP Crash Course & Exploration <span class=\"learn-sources-part\">· Network tab and Postman (12:46)</span></a><a href=\"https://www.youtube.com/watch?v=iYM2zFP3Zn0&amp;t=1691s\" target=\"_blank\" rel=\"noopener noreferrer\">Traversy Media · HTTP Crash Course & Exploration <span class=\"learn-sources-part\">· Authentication via headers (28:11)</span></a></div>","networking/security-infrastructure":"\n<p class=\"learn-lead\">Once an app is on the internet you have to control who can reach it, keep private parts private, and spread traffic across several servers. The same building blocks appear in every data centre and every cloud; the cloud just gives them different names.</p>\n\n<h4>Firewalls</h4>\n<p>A <b>firewall</b> allows or blocks traffic by rules: source address, destination port, protocol. The safe default is \"deny everything inbound, then allow only what's needed\", for example ports 22, 80 and 443 on a web server. Modern firewalls are <b>stateful</b>: once they allow an outgoing request, they automatically let its reply back in. On a Linux server that's <code>ufw</code>; in the cloud it's security groups.</p>\n\n<h4>NAT</h4>\n<p><b>Network address translation</b> rewrites addresses as traffic passes through a router. Its main job is letting many machines with private IPs share one public IP to reach the internet. A useful side effect: machines behind NAT can start connections outward, but nobody on the internet can start a connection to them. That's why NAT is used for servers that need to download updates but shouldn't be reachable.</p>\n<figure class=\"learn-diagram dg\" data-dg=\"net-nat\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 230\" role=\"img\" aria-label=\"Three devices with private 192.168.1.x addresses share one public IP through a NAT router; they can connect out, but the internet cannot connect in\" style=\"--dgw:680px\"><defs><marker id=\"net-nat--bad\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk bad\" d=\"M0,0 L8,4 L0,8 z\"/></marker><marker id=\"net-nat--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker><marker id=\"net-nat--ok\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk ok\" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"g\" x=\"10\" y=\"10\" width=\"250\" height=\"210\" rx=\"8\"/><text class=\"tg \" x=\"20\" y=\"26\" font-size=\"11\">home or private network</text><rect class=\"b\" x=\"26\" y=\"40\" width=\"218\" height=\"48\" rx=\"6\"/><text class=\"tb\" x=\"135\" y=\"60.7\" text-anchor=\"middle\" font-size=\"13\">laptop</text><text class=\"t2\" x=\"135\" y=\"76.0\" text-anchor=\"middle\" font-size=\"11\">192.168.1.20</text><rect class=\"b\" x=\"26\" y=\"100\" width=\"218\" height=\"48\" rx=\"6\"/><text class=\"tb\" x=\"135\" y=\"120.7\" text-anchor=\"middle\" font-size=\"13\">phone</text><text class=\"t2\" x=\"135\" y=\"136.0\" text-anchor=\"middle\" font-size=\"11\">192.168.1.21</text><rect class=\"b\" x=\"26\" y=\"160\" width=\"218\" height=\"48\" rx=\"6\"/><text class=\"tb\" x=\"135\" y=\"180.7\" text-anchor=\"middle\" font-size=\"13\">server</text><text class=\"t2\" x=\"135\" y=\"196.0\" text-anchor=\"middle\" font-size=\"11\">192.168.1.30</text><rect class=\"b hi\" x=\"300\" y=\"84\" width=\"150\" height=\"62\" rx=\"6\"/><text class=\"tb ta\" x=\"375\" y=\"112.2\" text-anchor=\"middle\" font-size=\"13\">router + NAT</text><text class=\"t2\" x=\"375\" y=\"126.7\" text-anchor=\"middle\" font-size=\"10\">public 203.0.113.7</text><rect class=\"b\" x=\"520\" y=\"84\" width=\"150\" height=\"62\" rx=\"6\"/><text class=\"tb\" x=\"595\" y=\"119.2\" text-anchor=\"middle\" font-size=\"13\">the internet</text><path class=\"ln\" d=\"M246,115 L298,115\" marker-end=\"url(#net-nat--n)\"/><path class=\"ln ok\" d=\"M452,106 L518,106\" marker-end=\"url(#net-nat--ok)\"/><text class=\"ok\" x=\"485\" y=\"96\" text-anchor=\"middle\" font-size=\"11\">out: allowed</text><path class=\"ln bad dash\" d=\"M518,130 L452,130\" marker-end=\"url(#net-nat--bad)\"/><text class=\"bad\" x=\"485\" y=\"152\" text-anchor=\"middle\" font-size=\"11\">in: blocked</text></svg></div><figcaption>Everything inside shows up on the internet as <code>203.0.113.7</code>. Replies to connections you started come back in; new connections from outside have nowhere to go.</figcaption></figure>\n\n\n<h4>VPN</h4>\n<p>A <b>VPN</b> builds an encrypted tunnel across the public internet so a remote laptop (or a whole office) behaves as if it were inside the private network. Companies use VPNs to reach internal servers without exposing them to the internet.</p>\n\n<h4>Load balancers and reverse proxies</h4>\n<p>A <b>load balancer</b> sits in front of several identical servers and spreads incoming requests across them. It checks each server's health and stops sending traffic to one that fails, so the site stays up while a server is replaced. <b>Layer 4</b> load balancers route by IP and port only; <b>layer 7</b> ones understand HTTP and can route by URL path or hostname (<code>/api</code> to one group of servers, <code>/</code> to another).</p>\n<p>A <b>reverse proxy</b> such as Nginx is the same idea at a smaller scale: it receives requests for the backend app, forwards them, and often handles HTTPS, compression and caching on the way. A <b>CDN</b> (Cloudflare, CloudFront) puts cached copies of your site on servers all over the world, so users download from somewhere close to them.</p>\n\n<h4>Cloud networking: the VPC</h4>\n<p>In AWS (and similarly in Azure and GCP) your servers live inside a <b>VPC</b>, a Virtual Private Cloud: your own isolated private network, for example <code>10.0.0.0/16</code>, that no one else's traffic can enter. You divide it into subnets and decide how each one reaches the outside:</p>\n<ul>\n<li><b>Public subnet</b>: has a route to an <b>internet gateway</b>, so its machines can have public IPs and be reached from the internet. Load balancers and web servers go here.</li>\n<li><b>Private subnet</b>: no route from the internet. Databases and internal services go here. If they need to download updates, they go out through a <b>NAT gateway</b> in a public subnet.</li>\n<li><b>Route tables</b> decide where traffic from each subnet goes: stay in the VPC, to the internet gateway, or to the NAT gateway.</li>\n<li><b>Security groups</b> are firewalls around each instance: \"this database only accepts port 5432 from the web servers' security group\". They're stateful. <b>Network ACLs</b> are an extra, stateless filter on a whole subnet.</li>\n</ul>\n<pre><code>Internet\n   │\nInternet gateway\n   │\nPublic subnet 10.0.1.0/24 ── load balancer, web servers ── NAT gateway\n   │                                                          │\nPrivate subnet 10.0.2.0/24 ── app servers, database ──(outbound only)</code></pre>\n<p>A server's network card inside the machine usually shows up as <code>eth0</code>; <code>ip a</code> lists interfaces and their addresses, and <code>ip route</code> shows where traffic is sent.</p>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=xj_GjnD4uyI&amp;t=248s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Every Networking Concept Explained In 20 Minutes <span class=\"learn-sources-part\">· Subnets, routing, firewalls (4:08)</span></a><a href=\"https://www.youtube.com/watch?v=xj_GjnD4uyI&amp;t=450s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Every Networking Concept Explained In 20 Minutes <span class=\"learn-sources-part\">· NAT (7:30)</span></a><a href=\"https://www.youtube.com/watch?v=xj_GjnD4uyI&amp;t=611s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Every Networking Concept Explained In 20 Minutes <span class=\"learn-sources-part\">· Cloud networking: VPC, subnets, gateways (10:11)</span></a><a href=\"https://www.youtube.com/watch?v=w0SQGCt-6Ro&amp;t=1090s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Networking Concepts Every DevOps Engineer Must Know <span class=\"learn-sources-part\">· AWS VPC, subnets, security groups (18:10)</span></a><a href=\"https://www.youtube.com/watch?v=bdeV_TjNfFA&amp;t=346s\" target=\"_blank\" rel=\"noopener noreferrer\">Tech With Diego · Every Networking Concept Explained (Networking 101) <span class=\"learn-sources-part\">· Firewalls, TLS, VPN, load balancers (5:46)</span></a></div>","networking/docker-kubernetes-networking":"\n<p class=\"learn-lead\">Containers added another layer of networking on top of servers. Nana's networking video tells it as a story in phases (physical servers, then virtual machines, then cloud, then Docker, then Kubernetes), and each phase adds one idea you need to know.</p>\n\n<h4>From servers to VMs to containers</h4>\n<p>With physical servers, each machine had its own network card and IP. <b>Virtual machines</b> put several machines on one physical server; the <b>hypervisor</b> gives each VM a virtual network card and connects them through a virtual switch. <b>Containers</b> go one step further: many isolated apps share one operating system, and Docker gives each container its own small virtual network setup.</p>\n\n<h4>Docker networking</h4>\n<ul>\n<li><b>Bridge network</b> (the default): Docker creates a private virtual network on the host, usually <code>172.17.0.0/16</code>, and each container gets its own IP on it. Containers on the same user-created network can reach each other <b>by container name</b>, because Docker runs a small DNS for them. That's why a web container can connect to <code>db:5432</code>.</li>\n<li><b>Port mapping</b> makes a container reachable from outside the host: <code>docker run -p 8080:80 nginx</code> sends traffic arriving on the host's port 8080 to port 80 inside the container. Without <code>-p</code>, nothing outside the host can reach it.</li>\n<li><b>Host network</b> (<code>--network host</code>): the container uses the host's network directly, with no isolation and no mapping.</li>\n<li><b>Overlay network</b>: stretches one virtual network across several hosts, so containers on different machines can talk as if they were side by side (used by Docker Swarm).</li>\n</ul>\n<pre><code>$ docker network create appnet\n$ docker run -d --name db  --network appnet postgres\n$ docker run -d --name web --network appnet -p 8080:3000 myapp\n#   web reaches the database at \"db:5432\"; your browser reaches web at localhost:8080</code></pre>\n\n\n<figure class=\"learn-diagram dg\" data-dg=\"net-docker\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 240\" role=\"img\" aria-label=\"A visitor reaches host port 8080, which -p maps to the web container on port 80; web reaches the db container by name on the bridge network\" style=\"--dgw:680px\"><defs><marker id=\"net-docker--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"b\" x=\"10\" y=\"90\" width=\"120\" height=\"56\" rx=\"6\"/><text class=\"tb\" x=\"70\" y=\"114.7\" text-anchor=\"middle\" font-size=\"13\">visitor</text><text class=\"t2\" x=\"70\" y=\"130.0\" text-anchor=\"middle\" font-size=\"11\">outside</text><rect class=\"g\" x=\"170\" y=\"10\" width=\"500\" height=\"220\" rx=\"8\"/><text class=\"tg \" x=\"180\" y=\"26\" font-size=\"11\">host machine</text><rect class=\"b\" x=\"190\" y=\"90\" width=\"110\" height=\"56\" rx=\"6\"/><text class=\"tb tm\" x=\"245\" y=\"114.7\" text-anchor=\"middle\" font-size=\"13\">:8080</text><text class=\"t2\" x=\"245\" y=\"130.0\" text-anchor=\"middle\" font-size=\"11\">host port</text><rect class=\"g hi\" x=\"340\" y=\"40\" width=\"316\" height=\"176\" rx=\"8\"/><text class=\"tg hi\" x=\"350\" y=\"56\" font-size=\"11\">bridge network 172.17.0.0/16</text><rect class=\"b hi\" x=\"360\" y=\"74\" width=\"276\" height=\"52\" rx=\"6\"/><text class=\"tb ta tm\" x=\"498\" y=\"96.3\" text-anchor=\"middle\" font-size=\"12\">web  172.17.0.2:80</text><text class=\"t2\" x=\"498\" y=\"111.5\" text-anchor=\"middle\" font-size=\"11\">container</text><rect class=\"b\" x=\"360\" y=\"150\" width=\"276\" height=\"52\" rx=\"6\"/><text class=\"tb tm\" x=\"498\" y=\"172.3\" text-anchor=\"middle\" font-size=\"12\">db  172.17.0.3:5432</text><text class=\"t2\" x=\"498\" y=\"187.5\" text-anchor=\"middle\" font-size=\"11\">container</text><path class=\"ln\" d=\"M132,118 L188,118\" marker-end=\"url(#net-docker--n)\"/><path class=\"ln\" d=\"M302,118 L358,100\" marker-end=\"url(#net-docker--n)\"/><text class=\"tl\" x=\"322\" y=\"140\" text-anchor=\"middle\" font-size=\"10\">-p 8080:80</text><path class=\"ln\" d=\"M498,128 L498,148\" marker-end=\"url(#net-docker--n)\"/><text class=\"tl\" x=\"506\" y=\"142\" text-anchor=\"start\" font-size=\"11\">db:5432 by name</text></svg></div><figcaption>Containers get private IPs on a bridge network and find each other by name. Only ports you publish with <code>-p</code> are reachable from outside the host.</figcaption></figure>\n<h4>Kubernetes networking</h4>\n<p>Kubernetes runs containers in <b>pods</b> across many machines (nodes), and its networking follows a few simple rules:</p>\n<ul>\n<li><b>Every pod gets its own IP</b>, unique in the whole cluster, and any pod can reach any other pod directly, with no NAT or port mapping. The plugin that sets this up is the <b>CNI</b> (Container Network Interface), for example Calico or Flannel.</li>\n<li><b>Pods are temporary</b>: when one is replaced it gets a new IP. So you never connect to a pod's IP directly. Instead you use a <b>Service</b>: a stable virtual IP and DNS name (like <code>my-api.default.svc.cluster.local</code>, or simply <code>my-api</code>) that load-balances across all the healthy pods behind it.</li>\n<li><b>kube-proxy</b> runs on every node and programs the rules that make a Service's IP forward to the right pods.</li>\n<li>Service types: <b>ClusterIP</b> (default, reachable only inside the cluster), <b>NodePort</b> (opens the same port on every node), and <b>LoadBalancer</b> (asks the cloud for a real external load balancer).</li>\n<li>An <b>Ingress</b> handles incoming HTTP/HTTPS from outside and routes it to Services by hostname or path (<code>api.demee.cc</code> to the API service, <code>/</code> to the frontend). It needs an <b>ingress controller</b>, usually Nginx, running in the cluster to do the actual routing.</li>\n<li>By default every pod can talk to every other pod. <b>NetworkPolicies</b> are firewall rules between pods, for example \"only the API pods may connect to the database pods\".</li>\n</ul>\n<p>Big setups sometimes add a <b>service mesh</b> (Istio, Linkerd): a small proxy next to every pod that handles encryption between services, retries and traffic metrics without changing the app.</p>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=w0SQGCt-6Ro&amp;t=630s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Networking Concepts Every DevOps Engineer Must Know <span class=\"learn-sources-part\">· VMs and hypervisors (10:30)</span></a><a href=\"https://www.youtube.com/watch?v=w0SQGCt-6Ro&amp;t=1353s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Networking Concepts Every DevOps Engineer Must Know <span class=\"learn-sources-part\">· Docker networking (22:33)</span></a><a href=\"https://www.youtube.com/watch?v=w0SQGCt-6Ro&amp;t=1696s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Networking Concepts Every DevOps Engineer Must Know <span class=\"learn-sources-part\">· Kubernetes networking (28:16)</span></a><a href=\"https://www.youtube.com/watch?v=xj_GjnD4uyI&amp;t=850s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Every Networking Concept Explained In 20 Minutes <span class=\"learn-sources-part\">· Container and Kubernetes networking (14:10)</span></a><a href=\"https://www.youtube.com/watch?v=bEFAFHIahXk&amp;t=1010s\" target=\"_blank\" rel=\"noopener noreferrer\">Vishakha Sadhwani · Learn Networking In 25 Minutes <span class=\"learn-sources-part\">· Docker, Kubernetes and service mesh (16:50)</span></a></div>","networking/troubleshooting-the-network":"\n<p class=\"learn-lead\">\"The site is down\" can mean a dozen different things. The trick is to test one layer at a time, from \"can I reach the machine at all?\" up to \"is the app answering correctly?\", with a small set of tools.</p>\n\n<h4>A layer-by-layer routine</h4>\n<figure class=\"learn-diagram dg\" data-dg=\"net-ladder\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 660 330\" role=\"img\" aria-label=\"Network checks in order: DNS with dig, reachability with ping, path with traceroute, port with nc, listening with ss, then the app with curl\" style=\"--dgw:660px\"><defs><marker id=\"net-ladder--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"b\" x=\"10\" y=\"6\" width=\"290\" height=\"34\" rx=\"6\"/><text class=\"tb\" x=\"155\" y=\"27.2\" text-anchor=\"middle\" font-size=\"13\">1  Does the name resolve?</text><text class=\"tc\" x=\"320\" y=\"28\" text-anchor=\"start\" font-size=\"12\">dig demee.cc</text><rect class=\"b\" x=\"10\" y=\"60\" width=\"290\" height=\"34\" rx=\"6\"/><text class=\"tb\" x=\"155\" y=\"81.2\" text-anchor=\"middle\" font-size=\"13\">2  Can I reach the machine?</text><text class=\"tc\" x=\"320\" y=\"82\" text-anchor=\"start\" font-size=\"12\">ping 203.0.113.10</text><path class=\"ln\" d=\"M155,42 L155,58\" marker-end=\"url(#net-ladder--n)\"/><rect class=\"b\" x=\"10\" y=\"114\" width=\"290\" height=\"34\" rx=\"6\"/><text class=\"tb\" x=\"155\" y=\"135.2\" text-anchor=\"middle\" font-size=\"13\">3  Where does the path break?</text><text class=\"tc\" x=\"320\" y=\"136\" text-anchor=\"start\" font-size=\"12\">traceroute demee.cc</text><path class=\"ln\" d=\"M155,96 L155,112\" marker-end=\"url(#net-ladder--n)\"/><rect class=\"b\" x=\"10\" y=\"168\" width=\"290\" height=\"34\" rx=\"6\"/><text class=\"tb\" x=\"155\" y=\"189.2\" text-anchor=\"middle\" font-size=\"13\">4  Is the port open?</text><text class=\"tc\" x=\"320\" y=\"190\" text-anchor=\"start\" font-size=\"12\">nc -zv demee.cc 443</text><path class=\"ln\" d=\"M155,150 L155,166\" marker-end=\"url(#net-ladder--n)\"/><rect class=\"b\" x=\"10\" y=\"222\" width=\"290\" height=\"34\" rx=\"6\"/><text class=\"tb\" x=\"155\" y=\"243.2\" text-anchor=\"middle\" font-size=\"13\">5  Is the service listening?</text><text class=\"tc\" x=\"320\" y=\"244\" text-anchor=\"start\" font-size=\"12\">ss -tulpn  (on the server)</text><path class=\"ln\" d=\"M155,204 L155,220\" marker-end=\"url(#net-ladder--n)\"/><rect class=\"b\" x=\"10\" y=\"276\" width=\"290\" height=\"34\" rx=\"6\"/><text class=\"tb\" x=\"155\" y=\"297.2\" text-anchor=\"middle\" font-size=\"13\">6  Does the app answer?</text><text class=\"tc\" x=\"320\" y=\"298\" text-anchor=\"start\" font-size=\"12\">curl -v https://demee.cc</text><path class=\"ln\" d=\"M155,258 L155,274\" marker-end=\"url(#net-ladder--n)\"/></svg></div><figcaption>Each step only makes sense once the one above it works. Stop at the first \"no\": that's the layer to fix.</figcaption></figure>\n\n<ol>\n<li><b>Does the name resolve?</b> <code>dig demee.cc</code> or <code>nslookup demee.cc</code>. No answer, or an old IP, means it's a DNS problem.</li>\n<li><b>Can I reach the machine?</b> <code>ping 203.0.113.10</code>. No reply might mean it's down, or that a firewall blocks ICMP, so don't treat a failed ping as final.</li>\n<li><b>Where does the path break?</b> <code>traceroute demee.cc</code> (or <code>mtr</code>) lists every router hop on the way; the last hop that answers shows roughly where traffic stops.</li>\n<li><b>Is the port open?</b> <code>nc -zv demee.cc 443</code> tries to open a TCP connection. \"Connection refused\" means the machine answered but nothing is listening on that port; a timeout usually means a firewall is dropping the traffic.</li>\n<li><b>Is the service listening?</b> On the server itself, <code>ss -tulpn</code> (older: <code>netstat -tulpn</code>) shows listening ports and which program owns each. An app listening only on <code>127.0.0.1</code> can't be reached from outside.</li>\n<li><b>Does the app answer correctly?</b> <code>curl -v https://demee.cc</code> shows the TLS handshake, the request, the status code and the headers.</li>\n</ol>\n\n<h4>The tools</h4>\n<ul>\n<li><code>ip a</code> / <code>ip route</code>: this machine's addresses and where it sends traffic (old equivalents: <code>ifconfig</code>, <code>route</code>).</li>\n<li><code>ping</code>: reachability and round-trip time, using ICMP.</li>\n<li><code>traceroute</code> / <code>mtr</code>: the hop-by-hop path.</li>\n<li><code>dig</code> / <code>nslookup</code>: ask DNS directly (<code>dig +short demee.cc</code>, <code>dig MX demee.cc</code>).</li>\n<li><code>curl</code> / <code>wget</code>: make HTTP requests; <code>-v</code> for detail, <code>-I</code> for headers only.</li>\n<li><code>ss</code> / <code>netstat</code>: open connections and listening ports.</li>\n<li><code>nc</code> (netcat): open a raw connection to test a port.</li>\n<li><code>nmap</code>: scan a host to see which ports are open. Only scan machines you own or have permission to scan.</li>\n<li><code>tcpdump</code>: capture the actual packets on an interface, for when nothing else explains it.</li>\n</ul>\n<div class=\"learn-callout\">Most real outages turn out to be one of four things: DNS pointing at the wrong place, a firewall or security group blocking the port, the app not running (or listening only on localhost), or an expired TLS certificate. Check those first.</div>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=M9Kex1ID7GY&amp;t=880s\" target=\"_blank\" rel=\"noopener noreferrer\">Cloud Champ · Networking Fundamentals for DevOps Engineers <span class=\"learn-sources-part\">· Ping, traceroute, netstat, nmap (14:40)</span></a><a href=\"https://www.youtube.com/watch?v=gyXfooY7MqU&amp;t=181s\" target=\"_blank\" rel=\"noopener noreferrer\">DevOps For Developers · The 20% of networking you'll use 80% of the time <span class=\"learn-sources-part\">· Linux networking commands (3:01)</span></a><a href=\"https://www.youtube.com/watch?v=gyXfooY7MqU&amp;t=534s\" target=\"_blank\" rel=\"noopener noreferrer\">DevOps For Developers · The 20% of networking you'll use 80% of the time <span class=\"learn-sources-part\">· SSL (8:54)</span></a></div>","networking/tls-https-certificates":"\n<p class=\"learn-lead\">The HTTP chapter said HTTPS is \"HTTP inside TLS\". This chapter opens that box: what TLS protects, what happens in the handshake, how certificates prove who a server is, how to get free ones from Let's Encrypt, and how to debug the certificate errors you will definitely run into.</p>\n\n<h4>What TLS gives you</h4>\n<ul>\n<li><b>Confidentiality</b>: traffic is encrypted, so Wi-Fi owners and ISPs see only scrambled bytes. They can still see <i>which</i> server you connect to, just not what you send.</li>\n<li><b>Integrity</b>: every record carries a cryptographic check; if a byte is changed in transit, the connection fails.</li>\n<li><b>Authentication</b>: the server proves it really is <code>demee.cc</code> with a certificate a trusted authority signed. Without this, you could be talking, very privately, to an attacker.</li>\n</ul>\n<p>\"SSL\" is the old name. SSL and TLS 1.0/1.1 are deprecated and disabled in modern browsers; allow only <b>TLS 1.2 and 1.3</b>. \"SSL certificate\" and \"TLS certificate\" mean the same thing.</p>\n\n<h4>The handshake (TLS 1.3)</h4>\n<ol>\n<li><b>ClientHello</b>: the client lists the versions and ciphers it supports, sends its half of a key exchange (a <b>key share</b>), and names the site it wants in the <b>SNI</b> field. SNI is how one IP address can serve many HTTPS sites with different certificates.</li>\n<li><b>ServerHello</b>: the server picks a cipher and sends its own key share. Both sides combine the shares (an <b>ECDHE</b> exchange, commonly X25519) into the same secret, which never crossed the wire. Everything after this is encrypted.</li>\n<li><b>Certificate + CertificateVerify</b>: the server sends its certificate chain and a signature over the handshake made with the certificate's <b>private key</b>, proving it owns that certificate.</li>\n<li><b>Finished</b>: the client checks the certificate (trusted chain, right hostname, not expired), both sides confirm the handshake wasn't tampered with, and the HTTP request goes out encrypted with fast symmetric keys (AES-GCM or ChaCha20-Poly1305).</li>\n</ol>\n<p>TLS 1.3 needs one round trip for this, TLS 1.2 needed two. Because session keys come from throwaway key shares, stealing the server's private key later doesn't decrypt recorded traffic: <b>forward secrecy</b>.</p>\n\n<h4>Certificates, chains and CAs</h4>\n<p>A certificate (X.509, usually a <code>.pem</code> text file) binds a public key to names. What matters in it:</p>\n<ul>\n<li><b>Subject Alternative Name (SAN)</b>: the hostnames it's valid for. Browsers check this list, not the old Common Name. A wildcard <code>*.demee.cc</code> covers <code>study.demee.cc</code> but not <code>demee.cc</code> or <code>a.b.demee.cc</code>.</li>\n<li><b>Issuer</b>, <b>validity</b> (<code>notBefore</code>/<code>notAfter</code>), the <b>public key</b>, and the issuer's <b>signature</b> over all of it.</li>\n</ul>\n<p>Trust works as a <b>chain</b>: your <b>leaf</b> certificate is signed by an <b>intermediate</b>, which is signed by a <b>root</b>. Roots come pre-installed in the OS and browser (the <b>trust store</b>; on Ubuntu, the <code>ca-certificates</code> package). The server must send the leaf <i>and</i> the intermediates. Forgetting the intermediate is a classic mistake: browsers often cope, but <code>curl</code>, scripts and phones fail.</p>\n<p>A <b>Certificate Authority</b> (CA) checks that you control a domain before signing. Industry rules keep cutting lifetimes: since 15 March 2026 a public certificate can be valid for at most 200 days, dropping to 100 days in 2027 and 47 days in 2029. Renewal has to be automated.</p>\n\n\n<figure class=\"learn-diagram dg\" data-dg=\"net-tls-chain\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 240\" role=\"img\" aria-label=\"A root CA in the trust store signs an intermediate CA, which signs the leaf certificate for study.demee.cc; the server sends the leaf plus the intermediate\" style=\"--dgw:680px\"><defs><marker id=\"net-tls-chain--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"b ok\" x=\"10\" y=\"20\" width=\"190\" height=\"60\" rx=\"6\"/><text class=\"tb\" x=\"105\" y=\"46.7\" text-anchor=\"middle\" font-size=\"13\">root CA</text><text class=\"t2\" x=\"105\" y=\"62.0\" text-anchor=\"middle\" font-size=\"11\">in your OS / browser</text><rect class=\"g hi\" x=\"220\" y=\"10\" width=\"450\" height=\"222\" rx=\"8\"/><text class=\"tg hi\" x=\"230\" y=\"26\" font-size=\"11\">the server sends both (fullchain.pem)</text><rect class=\"b\" x=\"240\" y=\"50\" width=\"200\" height=\"60\" rx=\"6\"/><text class=\"tb\" x=\"340\" y=\"76.7\" text-anchor=\"middle\" font-size=\"13\">intermediate CA</text><text class=\"t2\" x=\"340\" y=\"92.0\" text-anchor=\"middle\" font-size=\"11\">e.g. Let&#x27;s Encrypt</text><rect class=\"b hi\" x=\"450\" y=\"150\" width=\"200\" height=\"60\" rx=\"6\"/><text class=\"tb ta tm\" x=\"550\" y=\"176.7\" text-anchor=\"middle\" font-size=\"13\">study.demee.cc</text><text class=\"t2\" x=\"550\" y=\"192.0\" text-anchor=\"middle\" font-size=\"11\">your leaf certificate</text><path class=\"ln\" d=\"M202,50 L238,80\" marker-end=\"url(#net-tls-chain--n)\"/><text class=\"tl\" x=\"214\" y=\"104\" text-anchor=\"middle\" font-size=\"11\">signs</text><path class=\"ln\" d=\"M340,112 L340,180 L448,180\" marker-end=\"url(#net-tls-chain--n)\"/><text class=\"tl\" x=\"370\" y=\"172\" text-anchor=\"middle\" font-size=\"11\">signs</text><text class=\"ok\" x=\"105\" y=\"108\" text-anchor=\"middle\" font-size=\"11\">the browser</text><text class=\"ok\" x=\"105\" y=\"124\" text-anchor=\"middle\" font-size=\"11\">already has it</text></svg></div><figcaption>The browser walks the chain up to a root it already trusts. Forget to send the intermediate and some clients fail with \"unable to get local issuer certificate\".</figcaption></figure>\n<h4>Let's Encrypt, ACME and certbot</h4>\n<p><b>Let's Encrypt</b> is a free, non-profit CA. Its certificates last 90 days by default (it plans 45 days by 2028) and everything runs over the <b>ACME</b> protocol. To prove control of a domain, the client passes a <b>challenge</b>:</p>\n<ul>\n<li><b>HTTP-01</b>: serve a token at <code>http://yourdomain/.well-known/acme-challenge/&lt;token&gt;</code>. Needs port 80 open and DNS already pointing at the server.</li>\n<li><b>DNS-01</b>: create a TXT record at <code>_acme-challenge.yourdomain</code>. Works for private servers, and is the only way to get a wildcard.</li>\n</ul>\n<pre><code>$ sudo apt install certbot python3-certbot-nginx\n$ sudo certbot --nginx -d example.com -d www.example.com\n#   passes HTTP-01, gets the cert, edits the Nginx config, reloads Nginx\n$ sudo certbot certificates             # names and expiry dates\n$ sudo certbot renew --dry-run          # test renewal against the staging server\n$ systemctl list-timers | grep certbot  # the timer that renews automatically</code></pre>\n<p>Files land in <code>/etc/letsencrypt/live/example.com/</code>: <code>fullchain.pem</code> (leaf plus intermediates: what the server should send) and <code>privkey.pem</code> (never share or commit it). Configured by hand, Nginx looks like this:</p>\n<pre><code>server {\n    listen 80;\n    server_name example.com www.example.com;\n    return 301 https://$host$request_uri;      # send all HTTP to HTTPS\n}\n\nserver {\n    listen 443 ssl;\n    server_name example.com www.example.com;\n    ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;\n    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;\n    ssl_protocols       TLSv1.2 TLSv1.3;\n\n    location / {\n        proxy_pass http://127.0.0.1:3000;       # the app, plain HTTP on localhost\n    }\n}</code></pre>\n<p>Caddy, Traefik and Kubernetes' cert-manager do the whole ACME dance automatically.</p>\n<div class=\"learn-callout\">Let's Encrypt stopped sending \"your certificate expires soon\" emails in June 2025. Check that renewal works (<code>renew --dry-run</code>) and monitor expiry yourself.</div>\n\n<h4>Checking a certificate</h4>\n<pre><code>$ echo | openssl s_client -connect example.com:443 -servername example.com 2&gt;/dev/null \\\n    | openssl x509 -noout -subject -issuer -dates -ext subjectAltName\nsubject=CN = example.com\nissuer=C = US, O = Let's Encrypt, CN = YR1\nnotBefore=Sep  1 08:14:02 2026 GMT\nnotAfter=Nov 30 08:14:01 2026 GMT\nX509v3 Subject Alternative Name:\n    DNS:example.com, DNS:www.example.com</code></pre>\n<ul>\n<li><code>-servername</code> sets SNI; without it a multi-site server may hand you its default certificate. Without the pipe, <code>s_client</code> prints the whole chain and ends with <code>Verify return code: 0 (ok)</code>; any other code names the problem.</li>\n<li><code>openssl x509 -noout -checkend 2592000</code> fails if the certificate expires within 30 days: handy in cron or CI.</li>\n</ul>\n<pre><code>$ curl -v https://example.com -o /dev/null\n* SSL connection using TLSv1.3 / TLS_AES_256_GCM_SHA384 / X25519 / RSASSA-PSS\n* Server certificate:\n*  subject: CN=example.com\n*  expire date: Nov 30 08:14:01 2026 GMT\n*  subjectAltName: host \"example.com\" matched cert's \"example.com\"\n*  issuer: C=US; O=Let's Encrypt; CN=YR1\n*  SSL certificate verify ok.</code></pre>\n<p>(Wording varies slightly between versions, and the issuer depends on which intermediate signed the certificate.) In production, let monitoring watch expiry: Prometheus's blackbox exporter exposes <code>probe_ssl_earliest_cert_expiry</code>.</p>\n\n<h4>Common errors and fixes</h4>\n<div class=\"learn-table-wrap\"><table class=\"learn-table\">\n<thead><tr><th>What you see</th><th>Cause</th><th>Fix</th></tr></thead>\n<tbody>\n<tr><td><code>certificate has expired</code><br>Chrome: <code>NET::ERR_CERT_DATE_INVALID</code></td><td>Renewal silently failed (rarely: the client's clock is wrong).</td><td><code>sudo certbot renew</code> and reload. Find out why: port 80 blocked, DNS moved, or no reload after renewal (<code>--deploy-hook \"systemctl reload nginx\"</code>).</td></tr>\n<tr><td><code>no alternative certificate subject name matches target host name</code><br>Chrome: <code>NET::ERR_CERT_COMMON_NAME_INVALID</code></td><td>Valid certificate, wrong name: e.g. it covers <code>example.com</code> but not <code>www</code>, or the wrong server block answered.</td><td>Reissue with every name (<code>-d example.com -d www.example.com</code>); check <code>server_name</code>.</td></tr>\n<tr><td><code>self-signed certificate</code><br>Chrome: <code>NET::ERR_CERT_AUTHORITY_INVALID</code></td><td>Signed by itself or by a private CA the client doesn't trust.</td><td>Use a public CA on public sites. Internally, trust your CA: <code>curl --cacert ca.crt</code> or <code>update-ca-certificates</code>.</td></tr>\n<tr><td><code>unable to get local issuer certificate</code></td><td>No chain to a trusted root: intermediate not sent, or an outdated CA bundle.</td><td>Use <code>fullchain.pem</code>, not <code>cert.pem</code>; update <code>ca-certificates</code>.</td></tr>\n<tr><td><code>wrong version number</code></td><td>TLS spoken to a plain-HTTP port.</td><td>Use <code>http://</code> there, or connect to the TLS port (443).</td></tr>\n</tbody>\n</table></div>\n<div class=\"learn-callout warn\"><code>curl -k</code> (<code>--insecure</code>) skips certificate checks. Fine for a quick test, never in scripts or pipelines: it throws away authentication, so anyone could impersonate the server.</div>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=bdeV_TjNfFA&amp;t=374s\" target=\"_blank\" rel=\"noopener noreferrer\">Tech With Diego · Every Networking Concept Explained (Networking 101) <span class=\"learn-sources-part\">· TLS and SSL (6:14)</span></a><a href=\"https://www.youtube.com/watch?v=iYM2zFP3Zn0&amp;t=161s\" target=\"_blank\" rel=\"noopener noreferrer\">Traversy Media · HTTP Crash Course & Exploration <span class=\"learn-sources-part\">· Understanding HTTPS (2:41)</span></a><a href=\"https://www.youtube.com/watch?v=gyXfooY7MqU&amp;t=534s\" target=\"_blank\" rel=\"noopener noreferrer\">DevOps For Developers · The 20% of networking you'll use 80% of the time <span class=\"learn-sources-part\">· SSL (8:54)</span></a><a href=\"https://www.youtube.com/watch?v=7aRjGIhwyQM&amp;t=2136s\" target=\"_blank\" rel=\"noopener noreferrer\">Traversy Media · Linux Server Setup & MERN Deployment <span class=\"learn-sources-part\">· Domain name and SSL on a real server (35:36)</span></a></div>","networking/load-balancers-proxies-cdns":"\n<p class=\"learn-lead\">Between a browser and your app there are usually several middlemen: a CDN edge, a cloud load balancer, a reverse proxy. The Security &amp; infrastructure chapter introduced them in a paragraph; here you'll see how each works, configure Nginx as a load balancer, and learn how caching headers decide what a CDN keeps.</p>\n\n<h4>Forward vs reverse proxy</h4>\n<ul>\n<li>A <b>forward proxy</b> works for <b>clients</b>: outgoing traffic from a company network goes through it, and websites see the proxy's IP. Used for filtering and controlling outbound access; tools that read <code>HTTPS_PROXY</code> use one.</li>\n<li>A <b>reverse proxy</b> works for <b>servers</b>: it sits in front of your apps, and clients never see the backends. Nginx, HAProxy, Traefik, Caddy and Envoy are common ones.</li>\n</ul>\n<p>The reverse proxy handles jobs you don't want in every app: <b>TLS termination</b>, routing by hostname or path, compression, caching, rate limiting. Since the app now sees the proxy as the client, the proxy passes the original details in headers: <code>X-Forwarded-For</code> (client IP plus each proxy on the way), <code>X-Forwarded-Proto</code> (http or https) and often <code>X-Real-IP</code>.</p>\n\n<h4>Layer 4 vs layer 7</h4>\n<div class=\"learn-table-wrap\"><table class=\"learn-table\">\n<thead><tr><th></th><th>Layer 4</th><th>Layer 7</th></tr></thead>\n<tbody>\n<tr><td>Sees</td><td>IPs and ports of TCP/UDP connections</td><td>The HTTP request: host, path, headers, cookies</td></tr>\n<tr><td>TLS</td><td>Usually passes encrypted bytes through</td><td>Terminates TLS to read the request</td></tr>\n<tr><td>Good for</td><td>Any protocol (databases, raw TCP), huge throughput</td><td>Websites and APIs, path routing, retries, headers</td></tr>\n<tr><td>Examples</td><td>AWS NLB, HAProxy TCP mode, Nginx <code>stream</code></td><td>AWS ALB, Nginx <code>http</code>, Kubernetes Ingress</td></tr>\n</tbody>\n</table></div>\n\n<h4>Algorithms, health checks, sticky sessions</h4>\n<ul>\n<li><b>Round robin</b> (the usual default): 1, 2, 3, 1, 2, 3… Fair when requests cost about the same. <b>Weighted</b>: <code>weight=3</code> gets three times the share.</li>\n<li><b>Least connections</b>: next request to the server with the fewest active connections. Better when some requests are slow.</li>\n<li><b>IP hash</b> / consistent hashing: the same client (or key) always lands on the same server.</li>\n</ul>\n<p><b>Active health checks</b> call an endpoint like <code>/healthz</code> every few seconds and remove a server after several failures in a row; <b>passive</b> checks watch real traffic for errors. AWS ALB, HAProxy and Kubernetes probes do active checks; open-source Nginx does passive only (active checks are an NGINX Plus feature). A good health endpoint returns 200 only when the app can really serve, e.g. it can reach its database.</p>\n<p><b>Sticky sessions</b> pin each user to one backend (by cookie or IP hash), a workaround for apps that keep sessions in memory. The cost: uneven load, and users are logged out when their server dies. The real fix is a <b>stateless</b> app with sessions in Redis or a database.</p>\n\n\n<figure class=\"learn-diagram dg\" data-dg=\"net-lb\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 230\" role=\"img\" aria-label=\"A load balancer spreads requests over app-1, app-2 and app-3, health-checks each one, and stops sending traffic to app-3 when it fails\" style=\"--dgw:680px\"><defs><marker id=\"net-lb--bad\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk bad\" d=\"M0,0 L8,4 L0,8 z\"/></marker><marker id=\"net-lb--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"b hi\" x=\"10\" y=\"88\" width=\"120\" height=\"56\" rx=\"6\"/><text class=\"tb ta\" x=\"70\" y=\"120.2\" text-anchor=\"middle\" font-size=\"13\">requests</text><rect class=\"b hi\" x=\"190\" y=\"80\" width=\"170\" height=\"72\" rx=\"6\"/><text class=\"tb ta\" x=\"275\" y=\"106.2\" text-anchor=\"middle\" font-size=\"13\">load balancer</text><text class=\"t2\" x=\"275\" y=\"120.7\" text-anchor=\"middle\" font-size=\"10\">round robin</text><text class=\"t2\" x=\"275\" y=\"134.7\" text-anchor=\"middle\" font-size=\"10\">checks /healthz</text><rect class=\"b ok\" x=\"470\" y=\"14\" width=\"190\" height=\"56\" rx=\"6\"/><text class=\"tb\" x=\"565\" y=\"38.7\" text-anchor=\"middle\" font-size=\"13\">app-1</text><text class=\"t2\" x=\"565\" y=\"54.0\" text-anchor=\"middle\" font-size=\"11\">200 OK</text><path class=\"ln\" d=\"M362,116 L430,116 L430,42 L468,42\" marker-end=\"url(#net-lb--n)\"/><rect class=\"b ok\" x=\"470\" y=\"88\" width=\"190\" height=\"56\" rx=\"6\"/><text class=\"tb\" x=\"565\" y=\"112.7\" text-anchor=\"middle\" font-size=\"13\">app-2</text><text class=\"t2\" x=\"565\" y=\"128.0\" text-anchor=\"middle\" font-size=\"11\">200 OK</text><path class=\"ln\" d=\"M362,116 L430,116 L430,116 L468,116\" marker-end=\"url(#net-lb--n)\"/><rect class=\"b bad\" x=\"470\" y=\"162\" width=\"190\" height=\"56\" rx=\"6\"/><text class=\"tb\" x=\"565\" y=\"186.7\" text-anchor=\"middle\" font-size=\"13\">app-3</text><text class=\"t2\" x=\"565\" y=\"202.0\" text-anchor=\"middle\" font-size=\"11\">failing: out</text><path class=\"ln bad dash\" d=\"M362,116 L430,116 L430,190 L468,190\" marker-end=\"url(#net-lb--bad)\"/><path class=\"ln\" d=\"M132,116 L188,116\" marker-end=\"url(#net-lb--n)\"/></svg></div><figcaption>Health checks are what make a load balancer safe: a broken server drops out of the rotation by itself and rejoins once it passes again.</figcaption></figure>\n<h4>Nginx as a load balancer</h4>\n<pre><code># /etc/nginx/conf.d/app.conf\nupstream app_backend {\n    least_conn;                                  # default would be round robin\n    server 10.0.2.11:3000 max_fails=3 fail_timeout=30s;\n    server 10.0.2.12:3000 max_fails=3 fail_timeout=30s;\n    server 10.0.2.13:3000 backup;                # only used if the others are down\n}\n\nserver {\n    listen 80;\n    server_name example.com;\n\n    location / {\n        proxy_pass http://app_backend;\n        proxy_set_header Host              $host;\n        proxy_set_header X-Real-IP         $remote_addr;\n        proxy_set_header X-Forwarded-For   $proxy_add_x_forwarded_for;\n        proxy_set_header X-Forwarded-Proto $scheme;\n        proxy_next_upstream error timeout http_502 http_503;   # retry on another server\n    }\n}</code></pre>\n<p><code>max_fails=3 fail_timeout=30s</code> is the passive check: 3 failures within 30 seconds and that server is skipped for 30 seconds. <code>ip_hash;</code> instead of <code>least_conn;</code> gives IP stickiness, but can't be combined with <code>backup</code>.</p>\n<pre><code>$ sudo nginx -t                  # syntax check first\n$ sudo systemctl reload nginx    # apply without dropping connections</code></pre>\n\n<h4>CDNs and Cache-Control</h4>\n<p>A <b>CDN</b> is a worldwide network of reverse proxies (<b>edge servers</b>). Users hit the nearest one; on a <b>hit</b> it answers from cache, on a <b>miss</b> it fetches from your <b>origin</b> and keeps a copy. Faster pages far away, less load on the origin, and a big front door that absorbs DDoS attacks. The origin controls caching with <code>Cache-Control</code>:</p>\n<div class=\"learn-table-wrap\"><table class=\"learn-table\">\n<thead><tr><th>Header value</th><th>Meaning / use</th></tr></thead>\n<tbody>\n<tr><td><code>public, max-age=31536000, immutable</code></td><td>Cache for a year, never changes. For fingerprinted files like <code>app.3f9a1c.js</code>.</td></tr>\n<tr><td><code>public, max-age=60, s-maxage=600</code></td><td>Browsers 1 minute, shared caches (CDNs) 10 minutes.</td></tr>\n<tr><td><code>no-cache</code></td><td>May be stored, but must be <b>revalidated</b> before each use. HTML that must be current.</td></tr>\n<tr><td><code>no-store</code></td><td>Never store anywhere. Sensitive pages.</td></tr>\n<tr><td><code>private</code></td><td>Browser only, never a CDN. Logged-in, personalised pages.</td></tr>\n</tbody>\n</table></div>\n<p>Despite the name, <code>no-cache</code> doesn't mean \"don't cache\"; <code>no-store</code> does. Revalidation uses <code>ETag</code>: the server answers <code>304 Not Modified</code> with no body if nothing changed. <code>Age</code> shows how long a response has sat in a cache.</p>\n\n<h4>Cloudflare as an example</h4>\n<p>Mark a DNS record <b>proxied</b> (orange cloud) and DNS returns Cloudflare's IPs, so every request passes their edge: TLS terminated, cache and firewall rules applied, then forwarded to your origin. By default it caches static files by extension, but <b>not HTML</b> unless you add a Cache Rule. <b>Purge</b> the cache after a deploy if needed.</p>\n<pre><code>$ curl -sI https://example.com/logo.png | grep -iE 'server|cf-cache-status|cache-control|age'\nserver: cloudflare\ncf-cache-status: HIT             # or MISS, EXPIRED, BYPASS, DYNAMIC (not cacheable)\ncache-control: public, max-age=14400\nage: 812</code></pre>\n<p>The <b>SSL/TLS mode</b> sets how Cloudflare reaches your origin: <b>Flexible</b> uses plain HTTP (the second half of the trip is unencrypted), <b>Full</b> uses HTTPS with any certificate, <b>Full (strict)</b> requires a valid one. Aim for Full (strict).</p>\n\n<h4>How one request travels</h4>\n<pre><code>Browser ── DNS: example.com → Cloudflare edge IP\n  ▼\nCDN edge         TLS #1 ends here; cache HIT answers immediately\n  ▼  (miss)      adds CF-Connecting-IP / X-Forwarded-For\nLoad balancer    TLS #2 ends here; picks a healthy target\n  ▼\nReverse proxy    routes /api to the API, / to the frontend\n  ▼\nApp              reads the real client IP from forwarded headers</code></pre>\n\n<h4>Errors and what they point to</h4>\n<ul>\n<li><b>502 Bad Gateway</b>: the proxy got no valid response from the backend: app down, crashed, wrong port, or listening only on <code>127.0.0.1</code>. Nginx's error log will show \"connect() failed (111: Connection refused)\".</li>\n<li><b>504 Gateway Timeout</b>: the backend answered too slowly. Find the slow query, or raise <code>proxy_read_timeout</code> if it's expected.</li>\n<li><b>AWS targets \"unhealthy\"</b>: the health check isn't getting a 200: wrong path, a redirect, or a security group blocking the load balancer.</li>\n<li>Cloudflare <b>521</b> origin refused the connection, <b>522</b> timed out (often a firewall), <b>525</b> TLS handshake with origin failed, <b>526</b> invalid origin certificate in Full (strict).</li>\n<li><b>ERR_TOO_MANY_REDIRECTS</b> behind Cloudflare: Flexible mode sends HTTP, the origin redirects to HTTPS, repeat forever. Use Full (strict).</li>\n<li><b>Every log line shows the same client IP</b>: the app sees the proxy. Use <code>X-Forwarded-For</code>, trusting it only from your own proxies.</li>\n<li><b>Old version still showing after a deploy</b>: a stale cache. Purge the CDN, and use fingerprinted file names.</li>\n</ul>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=ZaA0kNm18pE&amp;t=325s\" target=\"_blank\" rel=\"noopener noreferrer\">Be A Better Dev · Cloud Computing Explained <span class=\"learn-sources-part\">· Load balancing (5:25)</span></a><a href=\"https://www.youtube.com/watch?v=OGYEXGy8ca4&amp;t=223s\" target=\"_blank\" rel=\"noopener noreferrer\">Be A Better Dev · AWS Explained <span class=\"learn-sources-part\">· Content delivery (CDN) (3:43)</span></a><a href=\"https://www.youtube.com/watch?v=OGYEXGy8ca4&amp;t=324s\" target=\"_blank\" rel=\"noopener noreferrer\">Be A Better Dev · AWS Explained <span class=\"learn-sources-part\">· Load balancing on AWS (5:24)</span></a><a href=\"https://www.youtube.com/watch?v=7aRjGIhwyQM&amp;t=1906s\" target=\"_blank\" rel=\"noopener noreferrer\">Traversy Media · Linux Server Setup & MERN Deployment <span class=\"learn-sources-part\">· Nginx install and reverse proxy config (31:46)</span></a><a href=\"https://www.youtube.com/watch?v=bdeV_TjNfFA&amp;t=465s\" target=\"_blank\" rel=\"noopener noreferrer\">Tech With Diego · Every Networking Concept Explained (Networking 101) <span class=\"learn-sources-part\">· Load balancer (7:45)</span></a></div>","git/basics-concepts":"\n<p class=\"learn-lead\">Git records the history of a project so you can see who changed what, go back to any earlier version, and let many people work on the same code without overwriting each other. Every DevOps pipeline starts with a <code>git push</code>.</p>\n\n<h4>Why version control exists</h4>\n<p>Without it, projects end up as folders named <code>final</code>, <code>final2</code>, <code>final-really</code>, and nobody knows which change broke what. <b>Version control</b> keeps every saved state of the project with a message explaining it. Git was created by Linus Torvalds in 2005 to manage the Linux kernel, and today it's used for nearly all code.</p>\n\n<h4>Git versus GitHub</h4>\n<p><b>Git</b> is the tool: a program on your computer that tracks history and works completely offline. <b>GitHub</b> (like GitLab and Bitbucket) is a website that hosts Git repositories online, so a team can share them, plus extras like pull requests, issues and CI/CD. You can use Git without GitHub, but not GitHub without Git.</p>\n<p>Git is <b>distributed</b>: every copy (clone) of a repository contains the entire history, not just the latest files. You can commit, branch and look at old versions with no internet, and if the server disappeared, any clone could replace it.</p>\n\n<h4>Commits are snapshots</h4>\n<p>A <b>commit</b> is a saved snapshot of the whole project at one moment, plus the author, the time, a message, and a link to the commit before it. That chain of links is the history. Each commit is identified by a <b>hash</b>, a long ID like <code>3955422a1f…</code> calculated from its contents, which is why history can't be quietly altered: change anything and the hash changes.</p>\n<figure class=\"learn-diagram dg\" data-dg=\"git-snapshots\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 660 200\" role=\"img\" aria-label=\"Three commits, each identified by a hash and linked back to its parent; the main branch and HEAD point at the newest one\" style=\"--dgw:660px\"><defs><marker id=\"git-snapshots--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker><marker id=\"git-snapshots--ok\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk ok\" d=\"M0,0 L8,4 L0,8 z\"/></marker><marker id=\"git-snapshots--warn\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk warn\" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"b\" x=\"10\" y=\"60\" width=\"140\" height=\"56\" rx=\"6\"/><text class=\"tb tm\" x=\"80\" y=\"84.7\" text-anchor=\"middle\" font-size=\"13\">3a1f9c2</text><text class=\"t2\" x=\"80\" y=\"100.0\" text-anchor=\"middle\" font-size=\"11\">first commit</text><rect class=\"b\" x=\"180\" y=\"60\" width=\"140\" height=\"56\" rx=\"6\"/><text class=\"tb tm\" x=\"250\" y=\"84.7\" text-anchor=\"middle\" font-size=\"13\">8b07d41</text><text class=\"t2\" x=\"250\" y=\"100.0\" text-anchor=\"middle\" font-size=\"11\">add login</text><path class=\"ln\" d=\"M178,88 L152,88\" marker-end=\"url(#git-snapshots--n)\"/><text class=\"tl\" x=\"165\" y=\"106\" text-anchor=\"middle\" font-size=\"10\">parent</text><rect class=\"b hi\" x=\"350\" y=\"60\" width=\"140\" height=\"56\" rx=\"6\"/><text class=\"tb ta tm\" x=\"420\" y=\"84.7\" text-anchor=\"middle\" font-size=\"13\">c94e3b0</text><text class=\"t2\" x=\"420\" y=\"100.0\" text-anchor=\"middle\" font-size=\"11\">fix typo</text><path class=\"ln\" d=\"M348,88 L322,88\" marker-end=\"url(#git-snapshots--n)\"/><text class=\"tl\" x=\"335\" y=\"106\" text-anchor=\"middle\" font-size=\"10\">parent</text><rect class=\"b ok\" x=\"530\" y=\"20\" width=\"110\" height=\"34\" rx=\"6\"/><text class=\"tb tm\" x=\"585\" y=\"41.2\" text-anchor=\"middle\" font-size=\"13\">main</text><rect class=\"b warn\" x=\"530\" y=\"70\" width=\"110\" height=\"34\" rx=\"6\"/><text class=\"tb tm\" x=\"585\" y=\"91.2\" text-anchor=\"middle\" font-size=\"13\">HEAD</text><path class=\"ln ok\" d=\"M528,37 L492,70\" marker-end=\"url(#git-snapshots--ok)\"/><path class=\"ln warn\" d=\"M528,87 L492,88\" marker-end=\"url(#git-snapshots--warn)\"/><text class=\"t2\" x=\"330\" y=\"160\" text-anchor=\"middle\" font-size=\"12\">each commit: a full snapshot, author, time, message, parent link</text><text class=\"t2\" x=\"330\" y=\"182\" text-anchor=\"middle\" font-size=\"11\">change anything and the hash changes</text></svg></div><figcaption>History is a chain of snapshots that point backwards. A branch like <code>main</code> is just a name stuck on the newest commit.</figcaption></figure>\n\n\n<h4>The three areas</h4>\n<p>This is the idea that makes Git click. Every change passes through three places:</p>\n<ol>\n<li><b>Working directory</b>: the actual files on your disk that you edit.</li>\n<li><b>Staging area</b> (also called the index): the changes you've picked to go into the next commit. <code>git add</code> puts them there.</li>\n<li><b>Repository</b>: the committed history, stored in the hidden <code>.git</code> folder. <code>git commit</code> saves whatever is staged.</li>\n</ol>\n<p>Staging exists so a commit can contain exactly one logical change, even if you edited five things at once: you add only the files that belong together, commit, then add the next batch.</p>\n\n<h4>Setting Git up</h4>\n<pre><code>$ git --version\n$ git config --global user.name \"Demetre Topuria\"\n$ git config --global user.email \"you@example.com\"\n$ git config --global init.defaultBranch main</code></pre>\n<p>The name and email are stamped on every commit you make. <code>--global</code> saves them once for all your projects.</p>\n\n<h4>.gitignore</h4>\n<p>Some files should never be committed: dependencies you can reinstall (<code>node_modules/</code>, <code>.venv/</code>), build output, logs, OS junk (<code>desktop.ini</code>, <code>.DS_Store</code>) and above all <b>secrets</b> (<code>.env</code> files, keys). List them, or patterns like <code>*.log</code>, in a <code>.gitignore</code> file at the top of the repo and Git will pretend they don't exist.</p>\n<div class=\"learn-callout warn\">A password committed once stays in the history even after you delete the file. If a secret is ever pushed, treat it as leaked and change it.</div>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=mAFoROnOfHs&amp;t=64s\" target=\"_blank\" rel=\"noopener noreferrer\">freeCodeCamp.org · Git & GitHub Crash Course for Beginners <span class=\"learn-sources-part\">· What is Git and version control (1:04)</span></a><a href=\"https://www.youtube.com/watch?v=mAFoROnOfHs&amp;t=241s\" target=\"_blank\" rel=\"noopener noreferrer\">freeCodeCamp.org · Git & GitHub Crash Course for Beginners <span class=\"learn-sources-part\">· Git vs GitHub, local vs remote (4:01)</span></a><a href=\"https://www.youtube.com/watch?v=vA5TTz6BXhY&amp;t=456s\" target=\"_blank\" rel=\"noopener noreferrer\">Traversy Media · Git & GitHub Crash Course 2025 <span class=\"learn-sources-part\">· Git workflow overview (7:36)</span></a><a href=\"https://www.youtube.com/watch?v=SWYqp7iY_Tc&amp;t=25s\" target=\"_blank\" rel=\"noopener noreferrer\">Traversy Media · Git & GitHub Crash Course For Beginners <span class=\"learn-sources-part\">· Git concepts (0:25)</span></a></div>","git/core-workflow":"\n<p class=\"learn-lead\">Day to day, Git is a short loop: change files, check what changed, stage, commit, push. This chapter goes through that loop command by command.</p>\n\n<h4>Getting a repository</h4>\n<p>There are two ways to start:</p>\n<ul>\n<li><code>git init</code> turns the current folder into a new, empty repository. Use it for a brand-new project.</li>\n<li><code>git clone &lt;url&gt;</code> downloads a full copy of an existing repository, all of its history included, and sets it up to sync with where it came from.</li>\n</ul>\n<pre><code>$ mkdir devops-site &amp;&amp; cd devops-site\n$ git init\n\n$ git clone https://github.com/DemeeTP/Devops-site.git</code></pre>\n\n<h4>The everyday loop</h4>\n<pre><code>$ git status                    # what changed? what's staged?\n$ git diff                      # show the exact lines changed (not yet staged)\n$ git add index.html            # stage one file\n$ git add .                     # stage everything changed in this folder\n$ git diff --staged             # review what you're about to commit\n$ git commit -m \"Add logo to header\"\n$ git log --oneline             # the history, one line per commit\n$ git push                      # upload new commits to GitHub</code></pre>\n{{DIAG:GIT_FLOW}}\n<p><code>git status</code> is the command to run whenever you're unsure: it tells you which branch you're on, what's modified, what's staged and what Git isn't tracking yet, and it usually suggests the next command.</p>\n\n<h4>Writing good commits</h4>\n<p>A commit should be one logical change with a message that says <i>what</i> and <i>why</i> in a short line, like \"Fix login redirect loop\" rather than \"update\". Small, focused commits make history readable and make it easy to undo one change without undoing others. <code>git commit -am \"msg\"</code> stages and commits all tracked files in one step, but it skips new files.</p>\n\n<h4>Seeing history</h4>\n<pre><code>$ git log                       # full history, newest first\n$ git log --oneline --graph     # compact, with branch lines drawn\n$ git log -p app.py             # every change ever made to one file\n$ git show 3955422              # one commit in full</code></pre>\n\n<h4>Removing and untracking</h4>\n<p><code>git rm file</code> deletes a file and stages the deletion. <code>git rm --cached file</code> stops tracking a file but leaves it on disk, which is what you do when you realise you committed something that should have been in <code>.gitignore</code>.</p>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=mAFoROnOfHs&amp;t=881s\" target=\"_blank\" rel=\"noopener noreferrer\">freeCodeCamp.org · Git & GitHub Crash Course for Beginners <span class=\"learn-sources-part\">· init, clone, status, add, commit (14:41)</span></a><a href=\"https://www.youtube.com/watch?v=mAFoROnOfHs&amp;t=2390s\" target=\"_blank\" rel=\"noopener noreferrer\">freeCodeCamp.org · Git & GitHub Crash Course for Beginners <span class=\"learn-sources-part\">· git log (39:50)</span></a><a href=\"https://www.youtube.com/watch?v=vA5TTz6BXhY&amp;t=889s\" target=\"_blank\" rel=\"noopener noreferrer\">Traversy Media · Git & GitHub Crash Course 2025 <span class=\"learn-sources-part\">· init to push, step by step (14:49)</span></a><a href=\"https://www.youtube.com/watch?v=Ez8F0nW6S-w\" target=\"_blank\" rel=\"noopener noreferrer\">Apna College · Complete Git and GitHub Tutorial <span class=\"learn-sources-part\">· Complete tutorial (0:00)</span></a></div>","git/branching-merging":"\n<p class=\"learn-lead\">Branches let you work on a feature or a fix without touching the working version, then bring the work back in when it's ready. They're cheap in Git, so teams create one for almost every change.</p>\n\n<h4>What a branch really is</h4>\n<p>A branch is just a movable label pointing at a commit. When you commit on a branch, the label moves forward to the new commit. <b>HEAD</b> is Git's pointer to \"where you are now\", normally the branch you have checked out. <code>main</code> is simply the branch everyone agrees holds the official version.</p>\n<pre><code>$ git branch                    # list branches (* marks the current one)\n$ git switch -c feature/login   # create a branch and move onto it\n$ git switch main               # go back to main\n$ git branch -d feature/login   # delete a branch that's been merged\n# older equivalent of switch: git checkout -b feature/login / git checkout main</code></pre>\n\n<h4>Merging</h4>\n<p>To bring a branch's work into <code>main</code>, switch to main and merge:</p>\n<pre><code>$ git switch main\n$ git merge feature/login</code></pre>\n<p>There are two outcomes. If <code>main</code> hasn't moved since you branched, Git does a <b>fast-forward</b>: it just slides the main label up to your latest commit. If both branches have new commits, Git creates a <b>merge commit</b> that has two parents and combines both lines of work.</p>\n{{DIAG:GIT_BRANCH}}\n\n<h4>Merge conflicts</h4>\n<p>If both branches changed the <i>same lines</i> of the same file, Git can't know which version is right, so it stops and asks you. The file will contain both versions between markers:</p>\n<pre><code>&lt;&lt;&lt;&lt;&lt;&lt;&lt; HEAD\n&lt;h1&gt;DevOps practice&lt;/h1&gt;\n=======\n&lt;h1&gt;DevOps&lt;/h1&gt;\n&gt;&gt;&gt;&gt;&gt;&gt;&gt; feature/rename</code></pre>\n<ol>\n<li>Open the file and decide what the final version should be. Keep one side, the other, or a mix.</li>\n<li>Delete the <code>&lt;&lt;&lt;&lt;&lt;&lt;&lt;</code>, <code>=======</code> and <code>&gt;&gt;&gt;&gt;&gt;&gt;&gt;</code> lines.</li>\n<li><code>git add</code> the file to mark it resolved, then <code>git commit</code> to finish the merge.</li>\n</ol>\n<p>Conflicts aren't errors; they're Git being careful. Pulling often and keeping branches short-lived keeps them small.</p>\n\n<h4>Rebase</h4>\n<p><code>git rebase main</code> (run on your feature branch) takes your commits and replays them on top of the latest <code>main</code>, as if you'd started from there. The history stays in a straight line with no merge commits. Because it rewrites your commits into new ones, the rule is: <b>only rebase commits that you haven't shared yet</b>. Rebasing a branch other people have pulled causes a mess for them.</p>\n\n<h4>Detached HEAD</h4>\n<p><code>git switch --detach 3955422</code> (or <code>git checkout 3955422</code>) lets you look at an old commit. You're then in \"detached HEAD\" state: you aren't on any branch, so new commits made there aren't saved to one and can get lost. To keep them, create a branch right there with <code>git switch -c rescue</code>.</p>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=mAFoROnOfHs&amp;t=2458s\" target=\"_blank\" rel=\"noopener noreferrer\">freeCodeCamp.org · Git & GitHub Crash Course for Beginners <span class=\"learn-sources-part\">· Branching, checkout, merge, conflicts (40:58)</span></a><a href=\"https://www.youtube.com/watch?v=mAFoROnOfHs&amp;t=4338s\" target=\"_blank\" rel=\"noopener noreferrer\">freeCodeCamp.org · Git & GitHub Crash Course for Beginners <span class=\"learn-sources-part\">· git rebase (1:12:18)</span></a><a href=\"https://www.youtube.com/watch?v=vA5TTz6BXhY&amp;t=2340s\" target=\"_blank\" rel=\"noopener noreferrer\">Traversy Media · Git & GitHub Crash Course 2025 <span class=\"learn-sources-part\">· Branching and merging (39:00)</span></a><a href=\"https://www.youtube.com/watch?v=SWYqp7iY_Tc&amp;t=1307s\" target=\"_blank\" rel=\"noopener noreferrer\">Traversy Media · Git & GitHub Crash Course For Beginners <span class=\"learn-sources-part\">· Branching and merging (21:47)</span></a></div>","git/undoing-inspecting":"\n<p class=\"learn-lead\">Almost nothing in Git is truly lost once committed, and there's a safe way back from most mistakes. The skill is picking the right undo for where the change is: not yet staged, staged, committed locally, or already pushed.</p>\n\n<h4>Pick the undo by where the change is</h4>\n<div class=\"learn-table-wrap\"><table class=\"learn-table\">\n<tr><th>Situation</th><th>Command</th></tr>\n<tr><td>Throw away edits to a file (not staged)</td><td><code>git restore file</code></td></tr>\n<tr><td>Unstage a file, keep the edits</td><td><code>git restore --staged file</code></td></tr>\n<tr><td>Fix the message of the last commit, or add a forgotten file</td><td><code>git commit --amend</code></td></tr>\n<tr><td>Undo the last local commit, keep the changes</td><td><code>git reset --soft HEAD~1</code></td></tr>\n<tr><td>Undo a commit that's already pushed</td><td><code>git revert &lt;hash&gt;</code></td></tr>\n<tr><td>Park unfinished work for a moment</td><td><code>git stash</code></td></tr>\n</table></div>\n\n<h4>reset versus revert</h4>\n<p><code>git reset</code> moves your branch pointer backwards, so the commits after it drop out of the branch's history. It has three strengths:</p>\n<ul>\n<li><code>--soft</code>: undo the commit, keep the changes staged.</li>\n<li><code>--mixed</code> (the default): undo the commit and unstage, but keep the changes in your files.</li>\n<li><code>--hard</code>: undo the commit <i>and throw the changes away</i>. The dangerous one.</li>\n</ul>\n<p><code>git revert</code> does the opposite kind of undo: it creates a <b>new</b> commit that reverses an old one. History only grows, nothing is rewritten, so it's the safe choice on shared branches like <code>main</code>. Rule of thumb: <b>reset for local commits nobody else has, revert for anything already pushed.</b></p>\n<div class=\"learn-callout warn\">Resetting commits that were already pushed rewrites shared history. Pushing it needs <code>--force</code> and breaks everyone else's copy. On shared branches, use revert.</div>\n\n\n<figure class=\"learn-diagram dg\" data-dg=\"git-reset-revert\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 250\" role=\"img\" aria-label=\"Reset moves the main pointer back from C to B so C leaves the history; revert keeps C and adds a new commit C&#x27; that undoes it\" style=\"--dgw:680px\"><defs><marker id=\"git-reset-revert--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker><marker id=\"git-reset-revert--ok\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk ok\" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><text class=\"bad tb\" x=\"10\" y=\"24\" text-anchor=\"start\" font-size=\"12\">git reset --hard HEAD~1   rewrites history</text><circle class=\"c\" cx=\"60\" cy=\"64\" r=\"16\"/><text class=\"tm tb\" x=\"60\" y=\"68.0\" text-anchor=\"middle\" font-size=\"11\">A</text><circle class=\"c\" cx=\"170\" cy=\"64\" r=\"16\"/><text class=\"tm tb\" x=\"170\" y=\"68.0\" text-anchor=\"middle\" font-size=\"11\">B</text><path class=\"ln\" d=\"M153,64 L78,64\" marker-end=\"url(#git-reset-revert--n)\"/><circle class=\"c bad\" cx=\"280\" cy=\"64\" r=\"16\"/><text class=\"tm tb tw\" x=\"280\" y=\"68.0\" text-anchor=\"middle\" font-size=\"11\">C</text><path class=\"ln\" d=\"M263,64 L188,64\" marker-end=\"url(#git-reset-revert--n)\"/><rect class=\"b ok\" x=\"360\" y=\"47\" width=\"90\" height=\"34\" rx=\"6\"/><text class=\"tb tm\" x=\"405\" y=\"68.2\" text-anchor=\"middle\" font-size=\"13\">main</text><path class=\"ln ok\" d=\"M358,64 L190,50\" marker-end=\"url(#git-reset-revert--ok)\"/><text class=\"bad\" x=\"470\" y=\"70\" text-anchor=\"start\" font-size=\"11\">C drops out of the branch</text><text class=\"ok tb\" x=\"10\" y=\"140\" text-anchor=\"start\" font-size=\"12\">git revert C   adds a new commit, safe after a push</text><circle class=\"c\" cx=\"60\" cy=\"184\" r=\"16\"/><text class=\"tm tb\" x=\"60\" y=\"188.0\" text-anchor=\"middle\" font-size=\"11\">A</text><circle class=\"c\" cx=\"170\" cy=\"184\" r=\"16\"/><text class=\"tm tb\" x=\"170\" y=\"188.0\" text-anchor=\"middle\" font-size=\"11\">B</text><path class=\"ln\" d=\"M153,184 L78,184\" marker-end=\"url(#git-reset-revert--n)\"/><circle class=\"c\" cx=\"280\" cy=\"184\" r=\"16\"/><text class=\"tm tb\" x=\"280\" y=\"188.0\" text-anchor=\"middle\" font-size=\"11\">C</text><path class=\"ln\" d=\"M263,184 L188,184\" marker-end=\"url(#git-reset-revert--n)\"/><circle class=\"c ok\" cx=\"390\" cy=\"184\" r=\"16\"/><text class=\"tm tb tw\" x=\"390\" y=\"188.0\" text-anchor=\"middle\" font-size=\"11\">C&#x27;</text><path class=\"ln\" d=\"M373,184 L298,184\" marker-end=\"url(#git-reset-revert--n)\"/><rect class=\"b ok\" x=\"470\" y=\"167\" width=\"90\" height=\"34\" rx=\"6\"/><text class=\"tb tm\" x=\"515\" y=\"188.2\" text-anchor=\"middle\" font-size=\"13\">main</text><path class=\"ln ok\" d=\"M468,184 L408,184\" marker-end=\"url(#git-reset-revert--ok)\"/><text class=\"ok\" x=\"390\" y=\"228\" text-anchor=\"middle\" font-size=\"11\">C&#x27; undoes C&#x27;s changes</text></svg></div><figcaption><code>reset</code> moves the pointer back and rewrites history, fine for local commits. <code>revert</code> only adds, which is why it's the safe undo for anything already pushed.</figcaption></figure>\n<h4>Stash: a shelf for unfinished work</h4>\n<p>You're halfway through something and need to switch branches to fix a bug. <code>git stash</code> saves your uncommitted changes and gives you a clean working folder; <code>git stash pop</code> brings them back later. <code>git stash list</code> shows everything on the shelf.</p>\n\n<h4>Inspecting</h4>\n<ul>\n<li><code>git diff</code>: unstaged changes. <code>git diff --staged</code>: what's about to be committed. <code>git diff main..feature</code>: what a branch changes.</li>\n<li><code>git show &lt;hash&gt;</code>: one commit's message and full diff.</li>\n<li><code>git blame file</code>: who last changed each line, and in which commit.</li>\n<li><code>git reflog</code>: every place HEAD has pointed recently, even commits no branch points to any more. It's the safety net for \"I reset too far\".</li>\n</ul>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=mAFoROnOfHs&amp;t=3624s\" target=\"_blank\" rel=\"noopener noreferrer\">freeCodeCamp.org · Git & GitHub Crash Course for Beginners <span class=\"learn-sources-part\">· restore, stash, revert (1:00:24)</span></a><a href=\"https://www.youtube.com/watch?v=mAFoROnOfHs&amp;t=1470s\" target=\"_blank\" rel=\"noopener noreferrer\">freeCodeCamp.org · Git & GitHub Crash Course for Beginners <span class=\"learn-sources-part\">· reset: unstaging and undoing commits (24:30)</span></a><a href=\"https://www.youtube.com/watch?v=mAFoROnOfHs&amp;t=3266s\" target=\"_blank\" rel=\"noopener noreferrer\">freeCodeCamp.org · Git & GitHub Crash Course for Beginners <span class=\"learn-sources-part\">· git diff (54:26)</span></a></div>","git/remotes-collaboration":"\n<p class=\"learn-lead\">A remote is a copy of the repository somewhere else, usually GitHub. Working with a team is mostly keeping your local copy and the remote in sync, and proposing changes through pull requests.</p>\n\n<h4>Remotes, push, fetch and pull</h4>\n<p>When you clone, Git names the source <code>origin</code>. For a repo you created locally, you add it yourself:</p>\n<pre><code>$ git remote add origin https://github.com/DemeeTP/Devops-site.git\n$ git remote -v                    # list remotes\n$ git push -u origin main          # first push; -u remembers the pairing\n$ git push                         # afterwards, just this</code></pre>\n<ul>\n<li><code>git push</code> uploads your new commits. It's refused if the remote has commits you don't have yet, so you pull first.</li>\n<li><code>git fetch</code> downloads new commits from the remote but <b>doesn't change your files</b>. It's a safe way to look first.</li>\n<li><code>git pull</code> is <code>fetch</code> plus <code>merge</code>: download, then merge into your current branch.</li>\n</ul>\n\n\n<figure class=\"learn-diagram dg\" data-dg=\"git-remotes\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 230\" role=\"img\" aria-label=\"Push sends local commits to origin on GitHub; fetch downloads new commits into origin/main without touching your files; pull is fetch plus merge\" style=\"--dgw:680px\"><defs><marker id=\"git-remotes--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker><marker id=\"git-remotes--ok\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk ok\" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"g hi\" x=\"10\" y=\"10\" width=\"300\" height=\"210\" rx=\"8\"/><text class=\"tg hi\" x=\"20\" y=\"26\" font-size=\"11\">your laptop</text><rect class=\"b\" x=\"30\" y=\"40\" width=\"260\" height=\"44\" rx=\"6\"/><text class=\"tb\" x=\"160\" y=\"59.2\" text-anchor=\"middle\" font-size=\"13\">working files</text><text class=\"t2\" x=\"160\" y=\"73.7\" text-anchor=\"middle\" font-size=\"10\">what you edit</text><rect class=\"b hi\" x=\"30\" y=\"104\" width=\"260\" height=\"44\" rx=\"6\"/><text class=\"tb ta\" x=\"160\" y=\"123.2\" text-anchor=\"middle\" font-size=\"13\">local repo: main</text><text class=\"t2\" x=\"160\" y=\"137.7\" text-anchor=\"middle\" font-size=\"10\">your commits</text><rect class=\"b\" x=\"30\" y=\"164\" width=\"260\" height=\"44\" rx=\"6\"/><text class=\"tb tm\" x=\"160\" y=\"183.2\" text-anchor=\"middle\" font-size=\"13\">origin/main</text><text class=\"t2\" x=\"160\" y=\"197.7\" text-anchor=\"middle\" font-size=\"10\">last known state of GitHub</text><rect class=\"b ok\" x=\"470\" y=\"84\" width=\"200\" height=\"70\" rx=\"6\"/><text class=\"tb\" x=\"570\" y=\"115.7\" text-anchor=\"middle\" font-size=\"13\">origin</text><text class=\"t2\" x=\"570\" y=\"131.0\" text-anchor=\"middle\" font-size=\"11\">GitHub</text><path class=\"ln\" d=\"M292,120 L468,108\" marker-end=\"url(#git-remotes--n)\"/><text class=\"tl\" x=\"380\" y=\"104\" text-anchor=\"middle\" font-size=\"11\">push</text><path class=\"ln ok\" d=\"M468,132 L292,182\" marker-end=\"url(#git-remotes--ok)\"/><text class=\"ok\" x=\"390\" y=\"176\" text-anchor=\"middle\" font-size=\"11\">fetch</text><text class=\"ta tb\" x=\"520\" y=\"196\" text-anchor=\"middle\" font-size=\"12\">pull = fetch + merge</text><path class=\"ln\" d=\"M160,102 L160,86\" marker-end=\"url(#git-remotes--n)\"/></svg></div><figcaption>Only <code>push</code>, <code>fetch</code> and <code>pull</code> talk to the network. <code>fetch</code> is always safe: it updates <code>origin/main</code> and leaves your work alone.</figcaption></figure>\n<h4>Authentication</h4>\n<p>GitHub doesn't accept your account password for Git operations. Over HTTPS you sign in through a browser popup (Git Credential Manager) or use a personal access token; over SSH you add your <b>public key</b> to GitHub once and use URLs like <code>git@github.com:DemeeTP/Devops-site.git</code>. Same key pair idea as logging in to a server.</p>\n\n<h4>Pull requests</h4>\n<p>On a team you rarely push straight to <code>main</code>. Instead:</p>\n<figure class=\"learn-diagram dg\" data-dg=\"git-pr\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 170\" role=\"img\" aria-label=\"Pull request flow: work on a branch, push it, open a pull request, pass review and CI, then merge into main\" style=\"--dgw:680px\"><defs><marker id=\"git-pr--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"b\" x=\"10\" y=\"50\" width=\"120\" height=\"60\" rx=\"6\"/><text class=\"tb\" x=\"70\" y=\"77.2\" text-anchor=\"middle\" font-size=\"13\">branch</text><text class=\"t2\" x=\"70\" y=\"91.7\" text-anchor=\"middle\" font-size=\"10\">feature/login</text><rect class=\"b\" x=\"144\" y=\"50\" width=\"120\" height=\"60\" rx=\"6\"/><text class=\"tb\" x=\"204\" y=\"77.2\" text-anchor=\"middle\" font-size=\"13\">push</text><text class=\"t2\" x=\"204\" y=\"91.7\" text-anchor=\"middle\" font-size=\"10\">to GitHub</text><path class=\"ln\" d=\"M132,80 L142,80\" marker-end=\"url(#git-pr--n)\"/><rect class=\"b hi\" x=\"278\" y=\"50\" width=\"120\" height=\"60\" rx=\"6\"/><text class=\"tb ta\" x=\"338\" y=\"77.2\" text-anchor=\"middle\" font-size=\"13\">pull request</text><text class=\"t2\" x=\"338\" y=\"91.7\" text-anchor=\"middle\" font-size=\"10\">asks to merge</text><path class=\"ln\" d=\"M266,80 L276,80\" marker-end=\"url(#git-pr--n)\"/><rect class=\"b\" x=\"412\" y=\"50\" width=\"120\" height=\"60\" rx=\"6\"/><text class=\"tb\" x=\"472\" y=\"77.2\" text-anchor=\"middle\" font-size=\"13\">review + CI</text><text class=\"t2\" x=\"472\" y=\"91.7\" text-anchor=\"middle\" font-size=\"10\">must be green</text><path class=\"ln\" d=\"M400,80 L410,80\" marker-end=\"url(#git-pr--n)\"/><rect class=\"b ok\" x=\"546\" y=\"50\" width=\"120\" height=\"60\" rx=\"6\"/><text class=\"tb\" x=\"606\" y=\"77.2\" text-anchor=\"middle\" font-size=\"13\">merge</text><text class=\"t2\" x=\"606\" y=\"91.7\" text-anchor=\"middle\" font-size=\"10\">into main</text><path class=\"ln\" d=\"M534,80 L544,80\" marker-end=\"url(#git-pr--n)\"/><text class=\"t2\" x=\"340\" y=\"150\" text-anchor=\"middle\" font-size=\"12\">main only ever receives reviewed, tested changes</text></svg></div><figcaption>A pull request is a conversation about a branch. The merge button waits until reviewers and the CI checks are happy.</figcaption></figure>\n\n<ol>\n<li>Create a branch, commit your work, and push the branch.</li>\n<li>Open a <b>pull request</b> (GitLab calls it a <b>merge request</b>) asking to merge it into <code>main</code>.</li>\n<li>Teammates review the changes and comment, and automated CI checks run the tests.</li>\n<li>Once approved and green, it's merged, and the branch is deleted.</li>\n</ol>\n<p>Pull requests aren't a Git feature; they're a workflow the hosting platforms build on top. Many teams add <b>branch protection</b> so <code>main</code> can only change through a reviewed PR with passing checks.</p>\n\n<h4>Forks</h4>\n<p>A <b>clone</b> is a copy on your computer. A <b>fork</b> is a copy on GitHub under your own account. You fork projects you can't push to (open source), push to your fork, then open a pull request from your fork to the original.</p>\n\n<h4>Tags and releases</h4>\n<p><code>git tag v1.0</code> puts a permanent name on a commit, usually a release. Unlike a branch, a tag never moves. Push tags with <code>git push --tags</code>; CI pipelines often deploy to production only when a new tag appears.</p>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=mAFoROnOfHs&amp;t=3350s\" target=\"_blank\" rel=\"noopener noreferrer\">freeCodeCamp.org · Git & GitHub Crash Course for Beginners <span class=\"learn-sources-part\">· Push, fetch and pull (55:50)</span></a><a href=\"https://www.youtube.com/watch?v=mAFoROnOfHs&amp;t=4608s\" target=\"_blank\" rel=\"noopener noreferrer\">freeCodeCamp.org · Git & GitHub Crash Course for Beginners <span class=\"learn-sources-part\">· Pull requests and collaboration (1:16:48)</span></a><a href=\"https://www.youtube.com/watch?v=vA5TTz6BXhY&amp;t=2040s\" target=\"_blank\" rel=\"noopener noreferrer\">Traversy Media · Git & GitHub Crash Course 2025 <span class=\"learn-sources-part\">· SSH keys for GitHub (34:00)</span></a><a href=\"https://www.youtube.com/watch?v=SWYqp7iY_Tc&amp;t=1548s\" target=\"_blank\" rel=\"noopener noreferrer\">Traversy Media · Git & GitHub Crash Course For Beginners <span class=\"learn-sources-part\">· Remote repositories (25:48)</span></a></div>","git/automating-with-github-actions-gitlab-ci":"\n<p class=\"learn-lead\">Hosting platforms don't just store code, they can run it. Every push or pull request can automatically trigger tests, builds and deployments. Nana's two videos build the same kind of pipeline on GitHub Actions and on GitLab CI/CD; the ideas are identical, only the file names and keywords differ.</p>\n\n<h4>GitHub Actions: the pieces</h4>\n<figure class=\"learn-diagram dg\" data-dg=\"git-actions\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 250\" role=\"img\" aria-label=\"An event like push starts a workflow file, which runs jobs on runners; each job is a list of steps, and build waits for test\" style=\"--dgw:680px\"><defs><marker id=\"git-actions--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"b warn\" x=\"10\" y=\"90\" width=\"130\" height=\"60\" rx=\"6\"/><text class=\"tb\" x=\"75\" y=\"110.2\" text-anchor=\"middle\" font-size=\"13\">event</text><text class=\"t2\" x=\"75\" y=\"124.7\" text-anchor=\"middle\" font-size=\"10\">push,</text><text class=\"t2\" x=\"75\" y=\"138.7\" text-anchor=\"middle\" font-size=\"10\">pull_request</text><rect class=\"g hi\" x=\"170\" y=\"10\" width=\"500\" height=\"230\" rx=\"8\"/><text class=\"tg hi\" x=\"180\" y=\"26\" font-size=\"11\">workflow  .github/workflows/ci.yml</text><rect class=\"g\" x=\"186\" y=\"40\" width=\"212\" height=\"186\" rx=\"8\"/><text class=\"tg \" x=\"196\" y=\"56\" font-size=\"11\">job: test  (runner: ubuntu)</text><rect class=\"b\" x=\"200\" y=\"70\" width=\"184\" height=\"38\" rx=\"6\"/><text class=\"tm\" x=\"292\" y=\"92.8\" text-anchor=\"middle\" font-size=\"12\">step: checkout</text><rect class=\"b\" x=\"200\" y=\"120\" width=\"184\" height=\"38\" rx=\"6\"/><text class=\"tm\" x=\"292\" y=\"142.8\" text-anchor=\"middle\" font-size=\"12\">step: setup-python</text><rect class=\"b\" x=\"200\" y=\"170\" width=\"184\" height=\"38\" rx=\"6\"/><text class=\"tm\" x=\"292\" y=\"192.8\" text-anchor=\"middle\" font-size=\"12\">step: pytest</text><rect class=\"g\" x=\"448\" y=\"40\" width=\"212\" height=\"186\" rx=\"8\"/><text class=\"tg \" x=\"458\" y=\"56\" font-size=\"11\">job: build  (runner: ubuntu)</text><rect class=\"b\" x=\"462\" y=\"70\" width=\"184\" height=\"38\" rx=\"6\"/><text class=\"tm\" x=\"554\" y=\"92.8\" text-anchor=\"middle\" font-size=\"12\">step: checkout</text><rect class=\"b\" x=\"462\" y=\"120\" width=\"184\" height=\"38\" rx=\"6\"/><text class=\"tm\" x=\"554\" y=\"142.8\" text-anchor=\"middle\" font-size=\"12\">step: docker build</text><rect class=\"b\" x=\"462\" y=\"170\" width=\"184\" height=\"38\" rx=\"6\"/><text class=\"tm\" x=\"554\" y=\"192.8\" text-anchor=\"middle\" font-size=\"12\">step: push image</text><path class=\"ln\" d=\"M142,120 L168,120\" marker-end=\"url(#git-actions--n)\"/><path class=\"ln\" d=\"M400,133 L446,133\" marker-end=\"url(#git-actions--n)\"/><text class=\"tl\" x=\"423\" y=\"124\" text-anchor=\"middle\" font-size=\"10\">needs</text></svg></div><figcaption>Event, workflow, job, step: four levels. Jobs run in parallel on fresh machines unless one <code>needs</code> another.</figcaption></figure>\n\n<ul>\n<li>An <b>event</b> starts everything: a push, a pull request, a new tag, a schedule, or a manual button.</li>\n<li>A <b>workflow</b> is a YAML file in <code>.github/workflows/</code> describing what should happen for which events.</li>\n<li>A workflow has one or more <b>jobs</b>. Jobs run in parallel unless one <code>needs</code> another.</li>\n<li>Each job is a list of <b>steps</b>: either a shell command (<code>run:</code>) or a ready-made <b>action</b> from the marketplace (<code>uses:</code>), like checking out the code or logging in to Docker Hub.</li>\n<li>Jobs run on a <b>runner</b>: a fresh virtual machine GitHub starts for you (<code>ubuntu-latest</code>), or your own self-hosted server.</li>\n<li><b>Secrets</b> (passwords, tokens) are stored in the repo's settings and injected as <code>${{ secrets.NAME }}</code>, never written in the file.</li>\n</ul>\n<pre><code># .github/workflows/ci.yml\nname: CI\non:\n  push:\n    branches: [main]\n  pull_request:\n\njobs:\n  test-and-build:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v4            # get the code\n      - uses: actions/setup-python@v5\n        with:\n          python-version: \"3.12\"\n      - run: pip install -r requirements.txt\n      - run: pytest                          # a failing test stops the job here\n      - uses: docker/login-action@v3\n        with:\n          username: ${{ secrets.DOCKERHUB_USER }}\n          password: ${{ secrets.DOCKERHUB_TOKEN }}\n      - run: |\n          docker build -t demee/app:${{ github.sha }} .\n          docker push demee/app:${{ github.sha }}</code></pre>\n\n<h4>GitLab CI/CD: the same ideas</h4>\n<p>GitLab keeps the pipeline in one file at the top of the repo, <code>.gitlab-ci.yml</code>. Jobs are grouped into <b>stages</b> that run in order (all test jobs, then all build jobs, then deploy); a failure in one stage stops the later ones. Jobs are picked up by <b>GitLab Runners</b>, which use an <b>executor</b> (shell, Docker…) to run them. <b>CI/CD variables</b> in the project settings hold secrets, either as plain values or as files (handy for SSH keys).</p>\n<pre><code># .gitlab-ci.yml\nstages: [test, build, deploy]\n\nrun_tests:\n  stage: test\n  image: python:3.12\n  script:\n    - pip install -r requirements.txt\n    - pytest\n\nbuild_image:\n  stage: build\n  image: docker:24\n  services: [docker:24-dind]      # \"Docker in Docker\" so the job can build images\n  script:\n    - docker login -u $REGISTRY_USER -p $REGISTRY_PASS\n    - docker build -t demee/app:$CI_COMMIT_SHORT_SHA .\n    - docker push demee/app:$CI_COMMIT_SHORT_SHA\n\ndeploy:\n  stage: deploy\n  script:\n    - ssh -o StrictHostKeyChecking=no deploy@$SERVER_IP \"docker pull demee/app:$CI_COMMIT_SHORT_SHA &amp;&amp; docker compose up -d\"\n  only: [main]</code></pre>\n<p>Both pipelines follow the same shape: test the code, build it into a Docker image tagged with the commit ID, push the image to a registry, and deploy it to a server. The next topic, DevOps, explains why pipelines are organised that way.</p>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=R8_veQiYBjI&amp;t=290s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · GitHub Actions Tutorial <span class=\"learn-sources-part\">· Events, actions and workflows (4:50)</span></a><a href=\"https://www.youtube.com/watch?v=R8_veQiYBjI&amp;t=784s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · GitHub Actions Tutorial <span class=\"learn-sources-part\">· Workflow file syntax (13:04)</span></a><a href=\"https://www.youtube.com/watch?v=R8_veQiYBjI&amp;t=1240s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · GitHub Actions Tutorial <span class=\"learn-sources-part\">· Runners, then build and push a Docker image (20:40)</span></a><a href=\"https://www.youtube.com/watch?v=qP8kir2GUgo&amp;t=268s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · GitLab CI/CD Tutorial <span class=\"learn-sources-part\">· GitLab architecture (4:28)</span></a><a href=\"https://www.youtube.com/watch?v=qP8kir2GUgo&amp;t=767s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · GitLab CI/CD Tutorial <span class=\"learn-sources-part\">· The .gitlab-ci.yml pipeline (12:47)</span></a></div>","git/rebase-stash-cherry-pick":"\n<p class=\"learn-lead\">Earlier chapters mentioned rebase, stash and reflog in a line each. This one goes deeper: how rebase rewrites history, cleaning up commits before a pull request, handling conflicts mid-rebase, juggling several stashes, copying a single commit between branches, and using the reflog to get out of almost any mess.</p>\n\n<h4>Rebase vs merge</h4>\n<p>You branched <code>feature</code> off <code>main</code> and made commits A, B, C; meanwhile main got F and G. <code>git rebase main</code> <b>replays</b> your commits one by one on top of G:</p>\n<figure class=\"learn-diagram dg\" data-dg=\"git-rebase\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 270\" role=\"img\" aria-label=\"Merge joins the feature commits C and D with main&#x27;s E through a merge commit M; rebase replays C and D on top of E as new commits C&#x27; and D&#x27; in one straight line\" style=\"--dgw:680px\"><defs><marker id=\"git-rebase--hi\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk hi\" d=\"M0,0 L8,4 L0,8 z\"/></marker><marker id=\"git-rebase--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><text class=\"tb\" x=\"10\" y=\"20\" text-anchor=\"start\" font-size=\"12\">merge</text><circle class=\"c\" cx=\"60\" cy=\"60\" r=\"16\"/><text class=\"tm tb\" x=\"60\" y=\"64.0\" text-anchor=\"middle\" font-size=\"11\">A</text><circle class=\"c\" cx=\"150\" cy=\"60\" r=\"16\"/><text class=\"tm tb\" x=\"150\" y=\"64.0\" text-anchor=\"middle\" font-size=\"11\">B</text><path class=\"ln\" d=\"M133,60 L78,60\" marker-end=\"url(#git-rebase--n)\"/><circle class=\"c\" cx=\"240\" cy=\"60\" r=\"16\"/><text class=\"tm tb\" x=\"240\" y=\"64.0\" text-anchor=\"middle\" font-size=\"11\">E</text><path class=\"ln\" d=\"M223,60 L168,60\" marker-end=\"url(#git-rebase--n)\"/><circle class=\"c hi\" cx=\"195\" cy=\"120\" r=\"16\"/><text class=\"tm tb tw\" x=\"195\" y=\"124.0\" text-anchor=\"middle\" font-size=\"11\">C</text><circle class=\"c hi\" cx=\"285\" cy=\"120\" r=\"16\"/><text class=\"tm tb tw\" x=\"285\" y=\"124.0\" text-anchor=\"middle\" font-size=\"11\">D</text><path class=\"ln hi\" d=\"M178,112 L164,72\" marker-end=\"url(#git-rebase--hi)\"/><path class=\"ln hi\" d=\"M268,120 L212,120\" marker-end=\"url(#git-rebase--hi)\"/><circle class=\"c ok\" cx=\"370\" cy=\"60\" r=\"16\"/><text class=\"tm tb tw\" x=\"370\" y=\"64.0\" text-anchor=\"middle\" font-size=\"11\">M</text><path class=\"ln\" d=\"M353,60 L258,60\" marker-end=\"url(#git-rebase--n)\"/><path class=\"ln hi\" d=\"M356,72 L302,112\" marker-end=\"url(#git-rebase--hi)\"/><text class=\"t2\" x=\"430\" y=\"64\" text-anchor=\"start\" font-size=\"11\">a merge commit joins both lines</text><text class=\"tb\" x=\"10\" y=\"176\" text-anchor=\"start\" font-size=\"12\">rebase</text><circle class=\"c\" cx=\"60\" cy=\"220\" r=\"16\"/><text class=\"tm tb\" x=\"60\" y=\"224.0\" text-anchor=\"middle\" font-size=\"11\">A</text><circle class=\"c\" cx=\"150\" cy=\"220\" r=\"16\"/><text class=\"tm tb\" x=\"150\" y=\"224.0\" text-anchor=\"middle\" font-size=\"11\">B</text><path class=\"ln\" d=\"M133,220 L78,220\" marker-end=\"url(#git-rebase--n)\"/><circle class=\"c\" cx=\"240\" cy=\"220\" r=\"16\"/><text class=\"tm tb\" x=\"240\" y=\"224.0\" text-anchor=\"middle\" font-size=\"11\">E</text><path class=\"ln\" d=\"M223,220 L168,220\" marker-end=\"url(#git-rebase--n)\"/><circle class=\"c hi\" cx=\"330\" cy=\"220\" r=\"16\"/><text class=\"tm tb tw\" x=\"330\" y=\"224.0\" text-anchor=\"middle\" font-size=\"11\">C&#x27;</text><path class=\"ln\" d=\"M313,220 L258,220\" marker-end=\"url(#git-rebase--n)\"/><circle class=\"c hi\" cx=\"420\" cy=\"220\" r=\"16\"/><text class=\"tm tb tw\" x=\"420\" y=\"224.0\" text-anchor=\"middle\" font-size=\"11\">D&#x27;</text><path class=\"ln\" d=\"M403,220 L348,220\" marker-end=\"url(#git-rebase--n)\"/><text class=\"t2\" x=\"470\" y=\"224\" text-anchor=\"start\" font-size=\"11\">one straight line</text><text class=\"t2\" x=\"470\" y=\"242\" text-anchor=\"start\" font-size=\"11\">C&#x27;, D&#x27; are new copies</text></svg></div><figcaption>Same end result in your files, different history. Rebase rewrites the feature commits, so only rebase branches nobody else has pulled.</figcaption></figure>\n\n<pre><code>before:\n          A---B---C   feature\n         /\n    D---E---F---G     main\n\nafter git rebase main:\n                  A'--B'--C'   feature\n                 /\n    D---E---F---G              main</code></pre>\n<p>A', B', C' contain the same changes but are <b>new commits with new hashes</b>, because their parent changed. History becomes a straight line, and merging into main is a fast-forward. <b>Merge</b> never rewrites anything but adds merge commits; <b>rebase</b> gives clean, linear history but rewrites commits. Many teams rebase their own branch to keep it current, then merge (or squash-merge) the pull request.</p>\n<pre><code>$ git switch feature/login\n$ git fetch origin\n$ git rebase origin/main\nSuccessfully rebased and updated refs/heads/feature/login.\n$ git push --force-with-lease     # the branch was pushed before, and its history changed</code></pre>\n<p>A normal push is now rejected because the remote still has the old commits. <code>--force-with-lease</code> overwrites only if nobody else pushed since your last fetch; plain <code>--force</code> would silently delete their work. <code>git pull --rebase</code> (or <code>git config --global pull.rebase true</code>) makes pulls rebase instead of merge.</p>\n<div class=\"learn-callout warn\"><b>Golden rule:</b> never rebase commits others have based work on, like <code>main</code> or a shared branch. Their copies keep the old commits, and the next pull brings duplicates and confusing conflicts. Rebasing your own PR branch is fine as long as nobody else commits to it.</div>\n\n<h4>Interactive rebase: clean up before review</h4>\n<pre><code>$ git rebase -i HEAD~4        # the last 4 commits\n# or: git rebase -i main      # everything on this branch since it left main</code></pre>\n<p>Git opens a to-do list, <b>oldest first</b>. Change the command word on each line, then save and close:</p>\n<pre><code>pick 1a2b3c4 Add login form\npick 5d6e7f8 fix typo\npick 9a0b1c2 WIP\npick 3d4e5f6 Add password validaton\n\n# edited to:\npick 1a2b3c4 Add login form\nfixup 5d6e7f8 fix typo\nfixup 9a0b1c2 WIP\nreword 3d4e5f6 Add password validaton</code></pre>\n<ul>\n<li><code>pick</code>: keep as is. <code>reword</code>: keep, but edit the message (fixing \"validaton\").</li>\n<li><code>squash</code>: melt into the commit above and edit the combined message. <code>fixup</code>: same, but discard this commit's message.</li>\n<li><code>edit</code>: stop here to change the content (<code>git commit --amend</code>, then <code>git rebase --continue</code>). <code>drop</code> or deleting the line: remove the commit.</li>\n</ul>\n<p>Four messy commits become two clean ones; reordering lines reorders commits. Shortcut: commit a fix with <code>git commit --fixup=1a2b3c4</code>, and <code>git rebase -i --autosquash main</code> later puts it in place, already marked fixup.</p>\n\n<h4>Conflicts during a rebase</h4>\n<pre><code>$ git rebase main\nCONFLICT (content): Merge conflict in app.py\nerror: could not apply 6f700cc... Add login form\nhint: Resolve all conflicts manually, mark them as resolved with\nhint: \"git add/rm &lt;conflicted_files&gt;\", then run \"git rebase --continue\".</code></pre>\n<ol>\n<li>Fix the conflict markers in the file, exactly as for a merge conflict.</li>\n<li><code>git add app.py</code>. Don't run <code>git commit</code>: rebase commits for you.</li>\n<li><code>git rebase --continue</code>. The next commit may conflict too; repeat until \"Successfully rebased\".</li>\n</ol>\n<p><code>git rebase --abort</code> puts everything back as before you started, and is always safe. <code>--skip</code> drops the conflicting commit. <code>git status</code> shows where you are.</p>\n<div class=\"learn-callout\">During a rebase, \"ours\" and \"theirs\" are swapped compared with a merge: <b>ours</b> is the branch you're rebasing <i>onto</i> (main), <b>theirs</b> is your commit being replayed. Remember this with <code>git checkout --ours/--theirs</code> or VS Code's \"Accept Current / Incoming\".</div>\n\n<h4>Stash in depth</h4>\n<p>The stash is a stack: the newest entry is <code>stash@{0}</code>. Name your entries:</p>\n<pre><code>$ git stash push -m \"half-done navbar\"      # tracked changes, staged and unstaged\n$ git stash push -u -m \"with new files\"     # -u also takes untracked files\n$ git stash push -m \"just css\" -- style.css # only some paths\n$ git stash list\nstash@{0}: On feature/nav: just css\nstash@{1}: On feature/nav: with new files\nstash@{2}: On feature/nav: half-done navbar\n\n$ git stash show -p stash@{2}     # the diff inside an entry\n$ git stash apply stash@{2}       # apply, keep it in the list\n$ git stash pop                   # apply stash@{0} and remove it\n$ git stash drop stash@{1}        # delete one entry\n$ git stash branch fix-nav stash@{2}   # new branch from where you stashed, changes applied</code></pre>\n<ul>\n<li>If <code>pop</code> hits a conflict, the entry is <b>not</b> dropped: resolve, then <code>git stash drop</code> yourself.</li>\n<li>Without <code>-u</code>, new files aren't stashed and follow you to the other branch.</li>\n<li>Stashes are local and never pushed. For anything long-lived, commit to a WIP branch instead.</li>\n</ul>\n\n<h4>Cherry-pick: copy one commit</h4>\n<p>Classic case: a bug fix landed on <code>main</code>, and <code>release/1.4</code> needs it without everything else from main.</p>\n<pre><code>$ git switch release/1.4\n$ git cherry-pick -x 9f1c2ab     # -x adds \"(cherry picked from commit 9f1c2ab...)\" to the message\n$ git cherry-pick 4e5d6c7 9f1c2ab   # several, in that order\n$ git cherry-pick A..B              # commits after A, up to and including B\n$ git cherry-pick A^..B             # the same range including A</code></pre>\n<p>The copy gets a <b>new hash</b>. Conflicts work like in a rebase: fix, <code>git add</code>, <code>git cherry-pick --continue</code> (or <code>--abort</code>). If you're cherry-picking many commits, you probably want a merge or rebase instead.</p>\n\n<h4>The reflog: your undo history</h4>\n<p>Every time HEAD moves (commit, checkout, reset, rebase), Git logs it. Commits no branch points to are still reachable there. After an accidental <code>git reset --hard HEAD~2</code>:</p>\n<pre><code>$ git reflog\n6ee1bf6 (HEAD -&gt; feature/login) HEAD@{0}: reset: moving to HEAD~2\n8634d90 HEAD@{1}: commit: Add password validation\n6f700cc HEAD@{2}: commit: Add login form\n$ git reset --hard 8634d90      # jump back to before the reset\n$ git branch rescue 8634d90     # or: keep things as they are and save the commit on a branch</code></pre>\n<ul>\n<li><b>Undo a rebase you just finished</b>: <code>git reset --hard ORIG_HEAD</code> (Git saves the old tip there before rebases, merges and resets).</li>\n<li><b>Recover a deleted branch</b>: find its last commit in the reflog, then <code>git branch name &lt;hash&gt;</code>.</li>\n<li>The reflog is <b>local</b> and entries expire (by default 90 days, or 30 for commits no longer on any branch). It can't bring back changes that were never committed or stashed.</li>\n</ul>\n\n<h4>Common problems</h4>\n<ul>\n<li><b>\"Updates were rejected\" after rebasing</b>: expected. <code>git push --force-with-lease</code> on your own branch, never on main.</li>\n<li><b>Someone rebased a shared branch</b>: with no local work on it, <code>git fetch</code> then <code>git reset --hard origin/&lt;branch&gt;</code>.</li>\n<li><b>Stuck \"in the middle of a rebase\"</b>: <code>git status</code> explains; <code>git rebase --abort</code> gets you out.</li>\n<li><b>Squashed the wrong commits</b>: <code>git reset --hard ORIG_HEAD</code> and try again.</li>\n</ul>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=mAFoROnOfHs&amp;t=4338s\" target=\"_blank\" rel=\"noopener noreferrer\">freeCodeCamp.org · Git & GitHub Crash Course for Beginners <span class=\"learn-sources-part\">· git rebase: cleaning up history (1:12:18)</span></a><a href=\"https://www.youtube.com/watch?v=mAFoROnOfHs&amp;t=3796s\" target=\"_blank\" rel=\"noopener noreferrer\">freeCodeCamp.org · Git & GitHub Crash Course for Beginners <span class=\"learn-sources-part\">· git stash: saving unfinished work (1:03:16)</span></a><a href=\"https://www.youtube.com/watch?v=mAFoROnOfHs&amp;t=2863s\" target=\"_blank\" rel=\"noopener noreferrer\">freeCodeCamp.org · Git & GitHub Crash Course for Beginners <span class=\"learn-sources-part\">· Resolving conflicts (47:43)</span></a></div>","git/ignoring-files-tags-releases":"\n<p class=\"learn-lead\">Every real repository needs two things: keeping the wrong files out (build output, dependencies, secrets) and marking the commits that became releases. This chapter covers the <code>.gitignore</code> rules and traps, then how tags turn into versioned releases on GitHub.</p>\n\n<h4>.gitignore patterns</h4>\n<p>Patterns are matched relative to the folder the <code>.gitignore</code> is in:</p>\n<div class=\"learn-table-wrap\"><table class=\"learn-table\">\n<thead><tr><th>Pattern</th><th>Matches</th></tr></thead>\n<tbody>\n<tr><td><code>*.log</code></td><td>Any <code>.log</code> file, in any folder</td></tr>\n<tr><td><code>.env</code></td><td>A file or folder named <code>.env</code> anywhere</td></tr>\n<tr><td><code>build/</code></td><td>Folders named <code>build</code> anywhere (trailing slash = folders only)</td></tr>\n<tr><td><code>/build</code></td><td>Only <code>build</code> at the top level (leading slash anchors it)</td></tr>\n<tr><td><code>docs/*.pdf</code></td><td>PDFs directly in top-level <code>docs/</code>, not <code>docs/old/</code> (<code>*</code> never crosses a <code>/</code>)</td></tr>\n<tr><td><code>**/logs</code></td><td><code>logs</code> at any depth</td></tr>\n<tr><td><code>docs/**/*.pdf</code></td><td>PDFs anywhere under <code>docs/</code></td></tr>\n<tr><td><code>!keep.log</code></td><td>Negation: un-ignore what an earlier line ignored</td></tr>\n<tr><td><code># text</code></td><td>A comment (<code>\\#</code> for a name that really starts with #)</td></tr>\n</tbody>\n</table></div>\n<pre><code># dependencies and build output\nnode_modules/\n.venv/\n__pycache__/\ndist/\n\n# logs and OS junk\n*.log\n.DS_Store\n\n# secrets: ignore every .env variant, but share the template\n.env\n.env.*\n!.env.example</code></pre>\n<div class=\"learn-callout warn\">You can't un-ignore a file inside an ignored <b>folder</b>: with <code>logs/</code>, the line <code>!logs/keep.log</code> does nothing, because Git never looks inside. Use <code>logs/*</code> then <code>!logs/keep.log</code>.</div>\n\n<h4>Three places for ignore rules</h4>\n<ul>\n<li><code>.gitignore</code>: committed and shared. Rules about <b>the project</b>.</li>\n<li><code>.git/info/exclude</code>: same syntax, never committed. For <b>this clone only</b>.</li>\n<li>A <b>global</b> file for <b>your machine</b>: editor and OS files (<code>.idea/</code>, <code>.vscode/</code>, <code>.DS_Store</code>) that aren't the project's business.</li>\n</ul>\n<pre><code>$ git config --global core.excludesFile ~/.gitignore_global\n#   (if unset, Git already reads ~/.config/git/ignore)\n$ git check-ignore -v debug.log        # which rule ignores this file?\n.gitignore:8:*.log\tdebug.log\n$ git status --ignored                 # show ignored files too\n$ git add -f dist/keep-me.js           # force-add one ignored file</code></pre>\n\n<h4>Untracking an already committed file</h4>\n<p><code>.gitignore</code> only affects <b>untracked</b> files. If <code>.env</code> or <code>node_modules/</code> was committed before the rule existed, Git keeps tracking it. Remove it from the index but keep it on disk:</p>\n<pre><code>$ echo \".env\" &gt;&gt; .gitignore\n$ git rm --cached .env                 # stop tracking, keep the local file\n$ git rm -r --cached node_modules      # -r for a folder\n$ git commit -m \"Stop tracking .env and node_modules\"\n\n$ git rm -r --cached . &amp;&amp; git add .    # re-apply ALL ignore rules at once</code></pre>\n<ul>\n<li>When teammates pull this, Git <b>deletes</b> the file from their working folders. Warn them to back up their <code>.env</code>.</li>\n<li>The file is still in every old commit. If it held a secret, <b>rotate the secret</b>; scrubbing history needs <code>git filter-repo</code> and a force-push, and the secret should still be treated as leaked.</li>\n</ul>\n\n<h4>Empty folders and .gitkeep</h4>\n<p>Git tracks files, not folders, so an empty folder can't be committed. The convention is an empty <code>.gitkeep</code> file inside it; the name means nothing to Git. To keep a folder but ignore its future contents (<code>uploads/</code>, <code>logs/</code>), put a <code>.gitignore</code> in it containing <code>*</code> and <code>!.gitignore</code>.</p>\n\n<h4>Lightweight vs annotated tags</h4>\n<ul>\n<li><b>Lightweight</b>: just a name for a commit. <code>git tag v1.0.0</code></li>\n<li><b>Annotated</b>: a stored object with tagger, date and message, optionally signed (<code>-s</code>). <code>git tag -a v1.0.0 -m \"First stable release\"</code></li>\n</ul>\n<p>Use <b>annotated tags for releases</b>: they record who released what and when, and <code>git describe</code> and <code>--follow-tags</code> only consider annotated tags by default.</p>\n<pre><code>$ git tag -a v1.2.0 -m \"Release 1.2.0\"          # tag the current commit\n$ git tag -a v1.1.1 3955422 -m \"Hotfix 1.1.1\"   # tag an older commit\n$ git tag -l \"v1.*\"                             # list matching tags\n$ git show v1.2.0                               # tag details + the commit\n\n$ git push origin v1.2.0            # push one tag (plain git push sends none)\n$ git push --follow-tags            # commits + the annotated tags pointing at them\n$ git push --tags                   # every local tag, lightweight included\n$ git tag -d v1.2.0                 # delete locally...\n$ git push origin --delete v1.2.0   # ...and on GitHub</code></pre>\n<div class=\"learn-callout warn\">Never move or re-use a pushed tag: other clones and CI caches keep the old one, so \"v1.2.0\" would mean different code for different people. Release <code>v1.2.1</code> instead.</div>\n\n<h4>Semantic versioning</h4>\n<p><b>SemVer</b> versions look like <code>MAJOR.MINOR.PATCH</code>:</p>\n<figure class=\"learn-diagram dg\" data-dg=\"git-semver\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 640 200\" role=\"img\" aria-label=\"Semantic version 2.4.1: MAJOR 2 for breaking changes, MINOR 4 for new features, PATCH 1 for bug fixes\" style=\"--dgw:640px\"><rect class=\"b bad\" x=\"40\" y=\"20\" width=\"160\" height=\"64\" rx=\"6\"/><text class=\"tb tm\" x=\"120\" y=\"52.8\" text-anchor=\"middle\" font-size=\"26\">2</text><text class=\"t2\" x=\"120\" y=\"70.5\" text-anchor=\"middle\" font-size=\"11\">MAJOR</text><text class=\"bad tb\" x=\"120\" y=\"110\" text-anchor=\"middle\" font-size=\"12\">breaking change</text><rect class=\"b hi\" x=\"240\" y=\"20\" width=\"160\" height=\"64\" rx=\"6\"/><text class=\"tb ta tm\" x=\"320\" y=\"52.8\" text-anchor=\"middle\" font-size=\"26\">4</text><text class=\"t2\" x=\"320\" y=\"70.5\" text-anchor=\"middle\" font-size=\"11\">MINOR</text><text class=\"ta tb\" x=\"320\" y=\"110\" text-anchor=\"middle\" font-size=\"12\">new feature</text><text class=\"tb\" x=\"220\" y=\"62\" text-anchor=\"middle\" font-size=\"26\">.</text><rect class=\"b ok\" x=\"440\" y=\"20\" width=\"160\" height=\"64\" rx=\"6\"/><text class=\"tb tm\" x=\"520\" y=\"52.8\" text-anchor=\"middle\" font-size=\"26\">1</text><text class=\"t2\" x=\"520\" y=\"70.5\" text-anchor=\"middle\" font-size=\"11\">PATCH</text><text class=\"ok tb\" x=\"520\" y=\"110\" text-anchor=\"middle\" font-size=\"12\">bug fix</text><text class=\"tb\" x=\"420\" y=\"62\" text-anchor=\"middle\" font-size=\"26\">.</text><text class=\"tc\" x=\"320\" y=\"150\" text-anchor=\"middle\" font-size=\"12\">2.4.1 -&gt; 2.4.2 fix   2.4.1 -&gt; 2.5.0 feature   2.4.1 -&gt; 3.0.0 breaks</text><text class=\"t2\" x=\"320\" y=\"180\" text-anchor=\"middle\" font-size=\"11\">bumping one number resets the ones to its right to 0</text></svg></div><figcaption>The version number is a promise to whoever depends on you: same MAJOR means upgrading shouldn't break their code.</figcaption></figure>\n\n<ul>\n<li><b>MAJOR</b> for <b>breaking</b> changes (removed endpoint, renamed option): <code>2.4.1</code> → <code>3.0.0</code>.</li>\n<li><b>MINOR</b> for new, backwards-compatible features: <code>2.4.1</code> → <code>2.5.0</code>.</li>\n<li><b>PATCH</b> for backwards-compatible fixes: <code>2.4.1</code> → <code>2.4.2</code>.</li>\n</ul>\n<p>Bumping a number resets those to its right. <b>Pre-releases</b> like <code>3.0.0-rc.1</code> sort before <code>3.0.0</code>, and <code>0.y.z</code> means \"anything may change\". The <code>v</code> in <code>v2.4.1</code> is a tag-name convention, not part of the version. It lets users judge upgrades from the number alone, and ranges like npm's <code>^2.4.1</code> (any 2.x from 2.4.1 up) rely on it.</p>\n\n<h4>git describe</h4>\n<pre><code>$ git describe\nv1.2.0-5-g3f9a1c2          # 5 commits after v1.2.0; \"g\" + short hash of HEAD\n$ git describe --dirty\nv1.2.0-5-g3f9a1c2-dirty    # ...with uncommitted changes\n$ git describe --abbrev=0\nv1.2.0                     # just the latest tag</code></pre>\n<p>Exactly on a tagged commit it prints just <code>v1.2.0</code>, which makes it a cheap build version stamp. With no tags it fails with \"No names found, cannot describe anything\"; with only lightweight tags it says \"No annotated tags can describe…\" (add <code>--tags</code>, or <code>--always</code> to fall back to a hash).</p>\n\n<h4>GitHub Releases</h4>\n<p>A <b>release</b> is a GitHub page built on a tag, with a title, notes and downloadable files. GitHub adds source archives automatically and can <b>generate release notes</b> from the pull requests merged since the last release. On the website: Releases → Draft a new release. Or with <code>gh</code>:</p>\n<pre><code>$ gh release create v1.2.0 --generate-notes\n$ gh release create v1.2.0 dist/app-linux-amd64.tar.gz --title \"v1.2.0\" --notes-file CHANGELOG.md\n$ gh release create v2.0.0-rc.1 --prerelease --generate-notes</code></pre>\n<p>If the tag doesn't exist yet, <code>gh</code> creates it from the default branch's latest commit (<code>--verify-tag</code> refuses instead). In CI, pushing a version tag is a common release trigger:</p>\n<pre><code># .github/workflows/release.yml\nname: Release\non:\n  push:\n    tags: [\"v*.*.*\"]\n\npermissions:\n  contents: write            # needed to create the release\n\njobs:\n  release:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v4\n      - run: gh release create \"$GITHUB_REF_NAME\" --generate-notes\n        env:\n          GH_TOKEN: ${{ github.token }}</code></pre>\n<p>Releasing is then: merge to main, <code>git tag -a v1.3.0 -m \"Release 1.3.0\"</code>, <code>git push origin v1.3.0</code>, and the pipeline does the rest.</p>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=vA5TTz6BXhY&amp;t=1545s\" target=\"_blank\" rel=\"noopener noreferrer\">Traversy Media · Git & GitHub Crash Course 2025 <span class=\"learn-sources-part\">· .gitignore file (25:45)</span></a><a href=\"https://www.youtube.com/watch?v=SWYqp7iY_Tc&amp;t=1090s\" target=\"_blank\" rel=\"noopener noreferrer\">Traversy Media · Git & GitHub Crash Course For Beginners <span class=\"learn-sources-part\">· Using .gitignore (18:10)</span></a><a href=\"https://www.youtube.com/watch?v=mAFoROnOfHs&amp;t=2220s\" target=\"_blank\" rel=\"noopener noreferrer\">freeCodeCamp.org · Git & GitHub Crash Course for Beginners <span class=\"learn-sources-part\">· git rm --cached: stop tracking files (37:00)</span></a></div>","docker/containers-images":"\n<p class=\"learn-lead\">Docker solves \"it works on my machine\". It packages an app together with the exact runtime, libraries and settings it needs, so it runs identically on your laptop, a test server and production.</p>\n\n<h4>The problem it solves</h4>\n<p>Before containers, setting up an app meant installing the right language version, libraries and services on every machine, following long instructions, and hoping versions matched. Two apps needing different versions of the same library on one server was a constant headache. With Docker, all of that is baked into an <b>image</b> once; any machine with Docker can run it with one command.</p>\n\n<h4>Containers versus virtual machines</h4>\n<p>A <b>virtual machine</b> contains a whole guest operating system with its own kernel, running on a hypervisor. It's fully isolated but heavy: gigabytes in size and minutes to boot. A <b>container</b> shares the host's kernel and only packages the app and its libraries, so it's megabytes in size, starts in about a second, and you can run dozens on one machine. The trade-off is weaker isolation, and a Linux container needs a Linux kernel underneath (Docker Desktop on Windows and Mac quietly runs a small Linux VM for that).</p>\n{{DIAG:CONTAINER_VM}}\n\n<h4>Images, containers and registries</h4>\n<ul>\n<li>An <b>image</b> is the read-only package: a blueprint made of stacked <b>layers</b> (base OS files, then your dependencies, then your code).</li>\n<li>A <b>container</b> is a running instance of an image. You can start many containers from one image, like many objects from one class.</li>\n<li>A <b>registry</b> stores images: Docker Hub is the public one, and companies run private ones (AWS ECR, GitHub Container Registry). Inside a registry, a <b>repository</b> holds all versions of one image, and each version has a <b>tag</b>: <code>nginx:1.27</code>, <code>node:20-alpine</code>. No tag means <code>latest</code>.</li>\n</ul>\n\n<h4>What happens when you run a container</h4>\n<p>Docker has two halves: the <code>docker</code> command you type, and the <b>Docker engine</b> (a background service called <code>dockerd</code>) that does the work. When you run <code>docker run nginx</code>, the command sends a request to the engine. The engine checks whether the image is already on the machine; if not, it pulls the missing layers from the registry. It then adds a thin <b>writable layer</b> on top of the read-only image layers, gives the container its own isolated view of processes, files and network (Linux <b>namespaces</b>), limits how much CPU and memory it may use (<b>cgroups</b>), and starts the image's main command.</p>\n<p>A container lives exactly as long as that main process. When the process exits, the container stops; it moves through <b>created → running → stopped → removed</b>. Stopping keeps its writable layer, so <code>docker start</code> picks up where it left off; removing it throws that layer away, which is why real data belongs in volumes (next chapter).</p>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=pg19Z8LL06w&amp;t=231s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Docker Crash Course <span class=\"learn-sources-part\">· What problems Docker solves (3:51)</span></a><a href=\"https://www.youtube.com/watch?v=pg19Z8LL06w&amp;t=698s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Docker Crash Course <span class=\"learn-sources-part\">· Virtual machine vs Docker (11:38)</span></a><a href=\"https://www.youtube.com/watch?v=pg19Z8LL06w&amp;t=1296s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Docker Crash Course <span class=\"learn-sources-part\">· Images, containers, registries, tags (21:36)</span></a><a href=\"https://www.youtube.com/watch?v=H8Lyj2D_cWo\" target=\"_blank\" rel=\"noopener noreferrer\">Apna College · What is Docker? Simply Explained <span class=\"learn-sources-part\">· Docker simply explained (0:00)</span></a></div>","docker/working-with-docker":"\n<p class=\"learn-lead\">Day to day, working with Docker comes down to three things: running and inspecting containers, building your own images with a Dockerfile, and wiring several containers together with Compose. This chapter walks through each, in the order you'd meet them on a real project.</p>\n\n<h4>Everyday commands</h4>\n<pre><code>$ docker pull nginx:1.27                  # download an image\n$ docker run -d -p 8080:80 --name web nginx:1.27\n#   -d  run in the background\n#   -p  host port 8080 -> container port 80\n$ docker ps                               # running containers (-a = all)\n$ docker logs -f web                      # its output, live\n$ docker exec -it web sh                  # open a shell inside it\n$ docker stop web &amp;&amp; docker start web\n$ docker rm web                           # delete the container\n$ docker images                           # local images\n$ docker rmi nginx:1.27                   # delete an image</code></pre>\n\n<h4>Building your own image: the Dockerfile</h4>\n<p>A <b>Dockerfile</b> is the recipe for an image. Each instruction adds a layer:</p>\n<pre><code># Dockerfile for a Node.js app\nFROM node:20-alpine          # start from an official base image\nWORKDIR /app                 # all following commands run in /app\nCOPY package*.json ./        # copy dependency list first...\nRUN npm ci                   # ...and install (cached until package.json changes)\nCOPY . .                     # then the rest of the code\nENV NODE_ENV=production\nEXPOSE 3000                  # documents the port the app listens on\nCMD [\"node\", \"server.js\"]    # what runs when a container starts\n\n$ docker build -t demee/app:1.0 .\n$ docker run -d -p 3000:3000 demee/app:1.0\n$ docker push demee/app:1.0</code></pre>\n<p>Docker caches each layer and only rebuilds from the first one that changed. That's why dependency files are copied and installed <i>before</i> the rest of the code: editing your code doesn't trigger a slow reinstall.</p>\n\n\n<figure class=\"learn-diagram dg\" data-dg=\"dk-build\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 230\" role=\"img\" aria-label=\"docker build turns a Dockerfile into an image; docker run starts containers from it; docker push sends it to a registry so other machines can pull it\" style=\"--dgw:680px\"><defs><marker id=\"dk-build--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"b\" x=\"10\" y=\"30\" width=\"140\" height=\"56\" rx=\"6\"/><text class=\"tb tm\" x=\"80\" y=\"54.7\" text-anchor=\"middle\" font-size=\"13\">Dockerfile</text><text class=\"t2\" x=\"80\" y=\"70.0\" text-anchor=\"middle\" font-size=\"11\">the recipe</text><rect class=\"b hi\" x=\"260\" y=\"30\" width=\"160\" height=\"56\" rx=\"6\"/><text class=\"tb ta\" x=\"340\" y=\"54.7\" text-anchor=\"middle\" font-size=\"13\">image</text><text class=\"t2\" x=\"340\" y=\"70.0\" text-anchor=\"middle\" font-size=\"11\">demee/app:1.0</text><rect class=\"b ok\" x=\"530\" y=\"10\" width=\"140\" height=\"44\" rx=\"6\"/><text class=\"tb\" x=\"600\" y=\"29.2\" text-anchor=\"middle\" font-size=\"13\">container</text><text class=\"t2\" x=\"600\" y=\"43.7\" text-anchor=\"middle\" font-size=\"10\">running</text><rect class=\"b ok\" x=\"530\" y=\"64\" width=\"140\" height=\"44\" rx=\"6\"/><text class=\"tb\" x=\"600\" y=\"83.2\" text-anchor=\"middle\" font-size=\"13\">container</text><text class=\"t2\" x=\"600\" y=\"97.7\" text-anchor=\"middle\" font-size=\"10\">another copy</text><rect class=\"b warn\" x=\"260\" y=\"150\" width=\"160\" height=\"56\" rx=\"6\"/><text class=\"tb\" x=\"340\" y=\"174.7\" text-anchor=\"middle\" font-size=\"13\">registry</text><text class=\"t2\" x=\"340\" y=\"190.0\" text-anchor=\"middle\" font-size=\"11\">Docker Hub, GHCR</text><rect class=\"b\" x=\"530\" y=\"150\" width=\"140\" height=\"56\" rx=\"6\"/><text class=\"tb\" x=\"600\" y=\"174.7\" text-anchor=\"middle\" font-size=\"13\">other machine</text><text class=\"t2\" x=\"600\" y=\"190.0\" text-anchor=\"middle\" font-size=\"11\">CI, a server</text><path class=\"ln\" d=\"M152,58 L258,58\" marker-end=\"url(#dk-build--n)\"/><text class=\"tl\" x=\"205\" y=\"51\" text-anchor=\"middle\" font-size=\"11\">docker build</text><path class=\"ln\" d=\"M422,50 L528,32\" marker-end=\"url(#dk-build--n)\"/><text class=\"tl\" x=\"470\" y=\"30\" text-anchor=\"middle\" font-size=\"11\">docker run</text><path class=\"ln\" d=\"M422,66 L528,86\" marker-end=\"url(#dk-build--n)\"/><path class=\"ln\" d=\"M340,88 L340,148\" marker-end=\"url(#dk-build--n)\"/><text class=\"tl\" x=\"348\" y=\"122\" text-anchor=\"start\" font-size=\"11\">docker push</text><path class=\"ln\" d=\"M422,178 L528,178\" marker-end=\"url(#dk-build--n)\"/><text class=\"tl\" x=\"475\" y=\"171\" text-anchor=\"middle\" font-size=\"11\">docker pull</text></svg></div><figcaption>One image, many containers. The registry is how the same image gets from your laptop to CI and to the server, byte for byte.</figcaption></figure>\n<h4>Data and configuration</h4>\n<p>A container's own files disappear when the container is removed. Anything that must survive (a database's data) goes in a <b>volume</b>: <code>-v pgdata:/var/lib/postgresql/data</code>. Settings come in as environment variables: <code>-e DB_HOST=db</code>, so the same image runs in every environment with different config.</p>\n\n<h4>Docker Compose</h4>\n<p>Real apps are several containers: web, database, cache. <b>Docker Compose</b> describes them all in one <code>compose.yaml</code> file and starts them together, on a shared network where they find each other by service name:</p>\n<pre><code>services:\n  web:\n    build: .\n    ports: [\"3000:3000\"]\n    environment:\n      DB_HOST: db\n    depends_on: [db]\n  db:\n    image: postgres:16\n    environment:\n      POSTGRES_PASSWORD: example\n    volumes: [pgdata:/var/lib/postgresql/data]\nvolumes:\n  pgdata:\n\n$ docker compose up -d     # start everything\n$ docker compose down      # stop and remove it all</code></pre>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=pg19Z8LL06w&amp;t=2949s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Docker Crash Course <span class=\"learn-sources-part\">· Dockerfile and building an image (49:09)</span></a><a href=\"https://www.youtube.com/watch?v=DQdB7wFEygo&amp;t=500s\" target=\"_blank\" rel=\"noopener noreferrer\">The Coding Sloth · The Only Docker Tutorial You Need <span class=\"learn-sources-part\">· Docker Compose (8:20)</span></a><a href=\"https://www.youtube.com/watch?v=DQdB7wFEygo\" target=\"_blank\" rel=\"noopener noreferrer\">The Coding Sloth · The Only Docker Tutorial You Need <span class=\"learn-sources-part\">· The Coding Sloth: the whole Docker workflow (0:00)</span></a></div>","docker/writing-better-dockerfiles":"\n<p class=\"learn-lead\">A Dockerfile that works is easy; a good one takes a little more thought. Good images are small, rebuild fast, run as an ordinary user, stop cleanly and always build the same way. This chapter builds on the basic Dockerfile from \"Working with Docker\" and fixes the things that bite in production.</p>\n\n<h4>Pick a small base image</h4>\n<p>Your <code>FROM</code> line decides most of the image's size and how many packages (and therefore possible vulnerabilities) come along. Most official images come in several variants:</p>\n<div class=\"learn-table-wrap\"><table class=\"learn-table\"><thead><tr><th>Variant</th><th>What it is</th><th>Trade-off</th></tr></thead><tbody>\n<tr><td><code>node:22</code></td><td>Full Debian with compilers and common tools</td><td>Most compatible, by far the largest</td></tr>\n<tr><td><code>node:22-slim</code></td><td>Debian with the extras stripped out</td><td>Uses glibc like most Linux software, so prebuilt binaries just work. A good default</td></tr>\n<tr><td><code>node:22-alpine</code></td><td>Alpine Linux, installs packages with <code>apk</code></td><td>Very small, but uses <b>musl</b> libc instead of glibc: some native modules and prebuilt binaries fail or must be compiled from source</td></tr>\n<tr><td><code>gcr.io/distroless/...</code>, <code>scratch</code></td><td>Only your app and its runtime; no shell, no package manager</td><td>Smallest and safest, but harder to debug. Best for the final stage of a multi-stage build</td></tr>\n</tbody></table></div>\n<p>Rule of thumb: start with <code>-slim</code>; use <code>-alpine</code> when you've tested that everything works on musl.</p>\n\n<h4>Keep secrets and junk out: .dockerignore</h4>\n<p><code>docker build .</code> sends the whole folder (the <b>build context</b>) to the builder, and <code>COPY . .</code> copies all of it into the image. A <code>.dockerignore</code> file next to the Dockerfile excludes things, just like <code>.gitignore</code>:</p>\n<pre><code># .dockerignore  (comments must be on their own line)\n.git\n# reinstalled inside the image anyway\nnode_modules\nnpm-debug.log\n# never bake secrets into an image\n.env\ndist\ncompose.yaml</code></pre>\n<p>This makes builds faster, images smaller, and stops your local <code>node_modules</code> (built for your OS) from overwriting the one installed in the image.</p>\n\n<h4>Order layers for the cache</h4>\n<p>Docker rebuilds from the first changed layer onward, so put what changes least at the top: base image, system packages, dependency files, dependency install, and your source code last. When installing system packages, update and install in the <i>same</i> <code>RUN</code> and clean up in it too, because files deleted in a later layer still take up space in the earlier one:</p>\n<figure class=\"learn-diagram dg\" data-dg=\"dk-cache\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 274\" role=\"img\" aria-label=\"Six Dockerfile layers: the base image, workdir, dependency files and npm ci come from cache; COPY . . and CMD are rebuilt because the code changed\" style=\"--dgw:680px\"><rect class=\"b ok\" x=\"10\" y=\"10\" width=\"300\" height=\"32\" rx=\"6\"/><text class=\"tm\" x=\"160\" y=\"29.8\" text-anchor=\"middle\" font-size=\"12\">FROM node:20-alpine</text><text class=\"ok\" x=\"330\" y=\"31\" text-anchor=\"start\" font-size=\"12\">cached</text><rect class=\"b ok\" x=\"10\" y=\"50\" width=\"300\" height=\"32\" rx=\"6\"/><text class=\"tm\" x=\"160\" y=\"69.8\" text-anchor=\"middle\" font-size=\"12\">WORKDIR /app</text><text class=\"ok\" x=\"330\" y=\"71\" text-anchor=\"start\" font-size=\"12\">cached</text><rect class=\"b ok\" x=\"10\" y=\"90\" width=\"300\" height=\"32\" rx=\"6\"/><text class=\"tm\" x=\"160\" y=\"109.8\" text-anchor=\"middle\" font-size=\"12\">COPY package*.json ./</text><text class=\"ok\" x=\"330\" y=\"111\" text-anchor=\"start\" font-size=\"12\">cached</text><rect class=\"b ok\" x=\"10\" y=\"130\" width=\"300\" height=\"32\" rx=\"6\"/><text class=\"tm\" x=\"160\" y=\"149.8\" text-anchor=\"middle\" font-size=\"12\">RUN npm ci</text><text class=\"ok\" x=\"330\" y=\"151\" text-anchor=\"start\" font-size=\"12\">cached (slow step skipped)</text><rect class=\"b warn\" x=\"10\" y=\"170\" width=\"300\" height=\"32\" rx=\"6\"/><text class=\"tm\" x=\"160\" y=\"189.8\" text-anchor=\"middle\" font-size=\"12\">COPY . .</text><text class=\"warn tb\" x=\"330\" y=\"191\" text-anchor=\"start\" font-size=\"12\">rebuilt: you changed code</text><rect class=\"b warn\" x=\"10\" y=\"210\" width=\"300\" height=\"32\" rx=\"6\"/><text class=\"tm\" x=\"160\" y=\"229.8\" text-anchor=\"middle\" font-size=\"12\">CMD [&quot;node&quot;, &quot;server.js&quot;]</text><text class=\"warn tb\" x=\"330\" y=\"231\" text-anchor=\"start\" font-size=\"12\">rebuilt</text><text class=\"t2\" x=\"340\" y=\"266\" text-anchor=\"middle\" font-size=\"11\">everything after the first changed layer is rebuilt; everything before it comes from cache</text></svg></div><figcaption>Put what changes least at the top. Copying <code>package*.json</code> and installing before <code>COPY . .</code> means a code change doesn't reinstall every dependency.</figcaption></figure>\n\n<pre><code>RUN apt-get update \\\n &amp;&amp; apt-get install -y --no-install-recommends ca-certificates \\\n &amp;&amp; rm -rf /var/lib/apt/lists/*</code></pre>\n\n<h4>Multi-stage builds</h4>\n<p>Compilers and build tools are needed to <i>build</i> the app, not to <i>run</i> it. A multi-stage build uses one stage to compile and copies only the result into a clean final stage. Everything else is thrown away. Here's a Go web service:</p>\n<figure class=\"learn-diagram dg\" data-dg=\"dk-multistage\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 230\" role=\"img\" aria-label=\"A multi-stage build: stage 1 has the compiler, source and modules and produces a binary; only that binary is copied into a small stage 2 image\" style=\"--dgw:680px\"><defs><marker id=\"dk-multistage--hi\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk hi\" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"g warn\" x=\"10\" y=\"10\" width=\"300\" height=\"210\" rx=\"8\"/><text class=\"tg warn\" x=\"20\" y=\"26\" font-size=\"11\">stage 1: build  (golang:1.26)</text><rect class=\"b\" x=\"26\" y=\"44\" width=\"268\" height=\"34\" rx=\"6\"/><text class=\"\" x=\"160\" y=\"64.8\" text-anchor=\"middle\" font-size=\"12\">Go compiler + tools</text><rect class=\"b\" x=\"26\" y=\"86\" width=\"268\" height=\"34\" rx=\"6\"/><text class=\"\" x=\"160\" y=\"106.8\" text-anchor=\"middle\" font-size=\"12\">your source code</text><rect class=\"b\" x=\"26\" y=\"128\" width=\"268\" height=\"34\" rx=\"6\"/><text class=\"\" x=\"160\" y=\"148.8\" text-anchor=\"middle\" font-size=\"12\">downloaded modules</text><rect class=\"b hi\" x=\"26\" y=\"170\" width=\"268\" height=\"34\" rx=\"6\"/><text class=\"tb ta tm\" x=\"160\" y=\"190.8\" text-anchor=\"middle\" font-size=\"12\">/out/server  (the binary)</text><rect class=\"g ok\" x=\"410\" y=\"60\" width=\"260\" height=\"110\" rx=\"8\"/><text class=\"tg ok\" x=\"420\" y=\"76\" font-size=\"11\">stage 2: run  (distroless)</text><rect class=\"b ok\" x=\"426\" y=\"96\" width=\"228\" height=\"50\" rx=\"6\"/><text class=\"tb tm\" x=\"540\" y=\"117.7\" text-anchor=\"middle\" font-size=\"13\">/server</text><text class=\"t2\" x=\"540\" y=\"133.0\" text-anchor=\"middle\" font-size=\"11\">the only thing copied</text><path class=\"ln hi\" d=\"M296,170 L360,170 L360,121 L424,121\" marker-end=\"url(#dk-multistage--hi)\"/><text class=\"ta\" x=\"360\" y=\"196\" text-anchor=\"middle\" font-size=\"11\">COPY --from=build</text><text class=\"ok\" x=\"540\" y=\"196\" text-anchor=\"middle\" font-size=\"11\">final image: small, no compiler</text></svg></div><figcaption>The heavy build stage is thrown away. What ships is just the app, which means a smaller image, faster pulls and less for an attacker to use.</figcaption></figure>\n\n<pre><code># ---- stage 1: build ----\nFROM golang:1.26 AS build\nWORKDIR /src\nCOPY go.mod go.sum ./                # dependencies first, for the cache\nRUN go mod download\nCOPY . .\nRUN CGO_ENABLED=0 go build -o /out/server .   # static binary, no libc needed\n\n# ---- stage 2: run ----\nFROM gcr.io/distroless/static-debian12:nonroot\nCOPY --from=build /out/server /server\nEXPOSE 8080\nENTRYPOINT [\"/server\"]               # the :nonroot image already runs as UID 65532</code></pre>\n<p>The final image contains the binary and almost nothing else: no Go toolchain, no shell. <code>CGO_ENABLED=0</code> matters: without it the binary may be linked against glibc, and in a distroless-static or <code>scratch</code> image it fails with a confusing <code>exec /server: no such file or directory</code>. (If your module has no dependencies there's no <code>go.sum</code>; copy just <code>go.mod</code>.)</p>\n\n<h4>Don't run as root</h4>\n<p>By default the process inside a container runs as <code>root</code>. If the app gets compromised, that makes escaping or doing damage easier. Switch to an unprivileged user with <code>USER</code>. The official Node images already include a user called <code>node</code>:</p>\n<pre><code>FROM node:22-alpine\nWORKDIR /app\nCOPY package*.json ./\nRUN npm ci --omit=dev                # production dependencies only\nCOPY . .\nRUN mkdir -p /app/uploads &amp;&amp; chown node:node /app/uploads   # the one place it may write\nUSER node                            # everything from here on runs as \"node\"\nEXPOSE 3000\nCMD [\"node\", \"server.js\"]</code></pre>\n<p>The code stays owned by root and read-only for the app; only <code>uploads</code> is writable. On images without a ready-made user, create one: <code>RUN addgroup -S app &amp;&amp; adduser -S app -G app</code> (Alpine) or <code>RUN useradd --system --no-create-home app</code> (Debian).</p>\n\n<h4>CMD vs ENTRYPOINT, and why exec form matters</h4>\n<ul>\n<li><code>CMD</code> is the <b>default</b> command. Anything you type after the image name in <code>docker run</code> replaces it.</li>\n<li><code>ENTRYPOINT</code> is the <b>fixed</b> executable. Arguments from <code>docker run</code> (or <code>CMD</code>) are appended to it. Override it only with <code>--entrypoint</code>.</li>\n</ul>\n<pre><code>ENTRYPOINT [\"python\", \"app.py\"]\nCMD [\"--port\", \"8080\"]\n\n$ docker run myapp                   # runs: python app.py --port 8080\n$ docker run myapp --port 9000       # runs: python app.py --port 9000</code></pre>\n<p>Always use the <b>exec form</b> (JSON array). The shell form, <code>CMD node server.js</code>, runs your app as a child of <code>/bin/sh -c</code>. The shell becomes PID 1 and may not pass <code>SIGTERM</code> on to your app, so <code>docker stop</code> waits its 10-second timeout and then kills it with <code>SIGKILL</code>: no graceful shutdown, no finished requests.</p>\n\n<h4>HEALTHCHECK</h4>\n<p>A running process isn't necessarily a working app. <code>HEALTHCHECK</code> tells Docker how to test it:</p>\n<pre><code>HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \\\n  CMD wget -qO- http://127.0.0.1:3000/health || exit 1</code></pre>\n<p><code>docker ps</code> then shows <code>(healthy)</code>, <code>(unhealthy)</code> or <code>(health: starting)</code>, and Compose can wait for it (next chapter). Two catches: the tool must exist in the image (Alpine has BusyBox <code>wget</code>; slim images have neither curl nor wget), and plain Docker only <i>reports</i> unhealthy, it doesn't restart the container. Kubernetes ignores <code>HEALTHCHECK</code> entirely and uses its own probes.</p>\n\n<h4>Pin your versions</h4>\n<p><code>FROM node:latest</code> means your build can change underneath you any day. Pin at least the major version (<code>node:22-alpine</code>). For fully repeatable builds, pin the <b>digest</b>, the image's content hash, which can never change:</p>\n<pre><code>$ docker buildx imagetools inspect node:22-alpine   # shows \"Digest: sha256:...\"\nFROM node:22-alpine@sha256:&lt;digest&gt;</code></pre>\n<p>The catch: a pinned digest also never gets security fixes, so let a tool such as Dependabot or Renovate open pull requests to bump it.</p>\n\n<h4>Check the result</h4>\n<pre><code>$ docker build -t demee/app:1.1 .\n$ docker images demee/app            # SIZE column: compare before and after\n$ docker history demee/app:1.1       # every layer, its size, the instruction that made it</code></pre>\n<p><code>docker history</code> shows exactly which instruction added the weight: a surprise 300 MB layer usually means a missing <code>.dockerignore</code> entry or an install that didn't clean up after itself.</p>\n\n<h4>Common build errors</h4>\n<ul>\n<li><b>COPY fails with \"not found\"</b>: the file is outside the build context or excluded by <code>.dockerignore</code>.</li>\n<li><b><code>npm ci</code> fails</b>: it needs a <code>package-lock.json</code>; copy it together with <code>package.json</code>.</li>\n<li><b><code>exec format error</code></b> when running: the image was built for another CPU architecture (e.g. arm64 on a Mac, run on an amd64 server). Build with <code>--platform linux/amd64</code>.</li>\n</ul>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=DQdB7wFEygo&amp;t=172s\" target=\"_blank\" rel=\"noopener noreferrer\">The Coding Sloth · The Only Docker Tutorial You Need <span class=\"learn-sources-part\">· Creating a Dockerfile (2:52)</span></a><a href=\"https://www.youtube.com/watch?v=DQdB7wFEygo&amp;t=654s\" target=\"_blank\" rel=\"noopener noreferrer\">The Coding Sloth · The Only Docker Tutorial You Need <span class=\"learn-sources-part\">· Faster builds (10:54)</span></a><a href=\"https://www.youtube.com/watch?v=pg19Z8LL06w&amp;t=2949s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Docker Crash Course <span class=\"learn-sources-part\">· Dockerfile: dockerize a Node.js app (49:09)</span></a><a href=\"https://www.youtube.com/watch?v=pg19Z8LL06w&amp;t=3510s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Docker Crash Course <span class=\"learn-sources-part\">· Build image (58:30)</span></a></div>","docker/volumes-networks-compose-in-practice":"\n<p class=\"learn-lead\">Containers are meant to be thrown away, but your data isn't, and your containers need to find each other. This chapter covers the three ways to store data, how Docker networks and container DNS work, and a realistic Compose setup you can copy for your own projects.</p>\n\n<h4>Three kinds of mounts</h4>\n<figure class=\"learn-diagram dg\" data-dg=\"dk-mounts\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 260\" role=\"img\" aria-label=\"Three mount types: a named volume for database files, a bind mount of a host folder for code, and tmpfs in RAM for scratch files\" style=\"--dgw:680px\"><defs><marker id=\"dk-mounts--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker><marker id=\"dk-mounts--ok\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk ok\" d=\"M0,0 L8,4 L0,8 z\"/></marker><marker id=\"dk-mounts--warn\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk warn\" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"g hi\" x=\"226\" y=\"10\" width=\"248\" height=\"240\" rx=\"8\"/><text class=\"tg hi\" x=\"236\" y=\"26\" font-size=\"11\">container</text><rect class=\"b\" x=\"238\" y=\"28\" width=\"224\" height=\"40\" rx=\"6\"/><text class=\"tm\" x=\"350\" y=\"51.5\" text-anchor=\"middle\" font-size=\"11\">/var/lib/postgresql/data</text><rect class=\"b\" x=\"238\" y=\"108\" width=\"224\" height=\"40\" rx=\"6\"/><text class=\"tm\" x=\"350\" y=\"131.5\" text-anchor=\"middle\" font-size=\"11\">/app</text><rect class=\"b\" x=\"238\" y=\"188\" width=\"224\" height=\"40\" rx=\"6\"/><text class=\"tm\" x=\"350\" y=\"211.5\" text-anchor=\"middle\" font-size=\"11\">/tmp</text><rect class=\"b ok\" x=\"500\" y=\"20\" width=\"170\" height=\"56\" rx=\"6\"/><text class=\"tb\" x=\"585\" y=\"45.2\" text-anchor=\"middle\" font-size=\"13\">named volume</text><text class=\"t2\" x=\"585\" y=\"59.7\" text-anchor=\"middle\" font-size=\"10\">pgdata, Docker-managed</text><path class=\"ln ok\" d=\"M498,48 L464,48\" marker-end=\"url(#dk-mounts--ok)\"/><rect class=\"b warn\" x=\"500\" y=\"100\" width=\"170\" height=\"56\" rx=\"6\"/><text class=\"tb\" x=\"585\" y=\"125.2\" text-anchor=\"middle\" font-size=\"13\">bind mount</text><text class=\"t2\" x=\"585\" y=\"139.7\" text-anchor=\"middle\" font-size=\"10\">a host folder you pick</text><path class=\"ln warn\" d=\"M498,128 L464,128\" marker-end=\"url(#dk-mounts--warn)\"/><rect class=\"b\" x=\"500\" y=\"180\" width=\"170\" height=\"56\" rx=\"6\"/><text class=\"tb\" x=\"585\" y=\"205.2\" text-anchor=\"middle\" font-size=\"13\">tmpfs</text><text class=\"t2\" x=\"585\" y=\"219.7\" text-anchor=\"middle\" font-size=\"10\">RAM only, gone on stop</text><path class=\"ln\" d=\"M498,208 L464,208\" marker-end=\"url(#dk-mounts--n)\"/><text class=\"t2\" x=\"112\" y=\"50\" text-anchor=\"middle\" font-size=\"12\">database files</text><text class=\"t2\" x=\"112\" y=\"130\" text-anchor=\"middle\" font-size=\"12\">code in development</text><text class=\"t2\" x=\"112\" y=\"210\" text-anchor=\"middle\" font-size=\"12\">scratch files</text></svg></div><figcaption>Anything written inside a container without a mount disappears with the container. Pick the mount by who owns the data and how long it must live.</figcaption></figure>\n\n<div class=\"learn-table-wrap\"><table class=\"learn-table\"><thead><tr><th>Type</th><th>Example</th><th>Lives</th><th>Use it for</th></tr></thead><tbody>\n<tr><td><b>Named volume</b></td><td><code>-v pgdata:/var/lib/postgresql/data</code></td><td>Managed by Docker (under <code>/var/lib/docker/volumes</code> on Linux)</td><td>Database files, anything the app owns</td></tr>\n<tr><td><b>Bind mount</b></td><td><code>-v \"$(pwd)\":/app</code></td><td>A folder you choose on the host</td><td>Live-editing code in development, config files</td></tr>\n<tr><td><b>tmpfs</b></td><td><code>--tmpfs /tmp</code></td><td>RAM only (Linux), gone on stop</td><td>Scratch files, things that must never hit disk</td></tr>\n</tbody></table></div>\n<p>Two differences worth knowing. An <i>empty</i> named volume is first filled with whatever the image has at that path; a bind mount simply hides it. And with <code>-v</code>, a host path that doesn't exist is silently created as an empty root-owned folder, while the longer <code>--mount type=bind,src=...,dst=...</code> syntax fails with an error instead. Add <code>:ro</code> to mount read-only: <code>-v \"$(pwd)/nginx.conf\":/etc/nginx/nginx.conf:ro</code>.</p>\n<pre><code>$ docker volume create pgdata\n$ docker volume ls\n$ docker volume inspect pgdata      # shows the Mountpoint on the host\n$ docker volume rm pgdata           # only if no container uses it</code></pre>\n\n<h4>Backing up a volume</h4>\n<p>Start a throwaway container that mounts the volume and your current folder, and tar one into the other:</p>\n<pre><code># backup\n$ docker run --rm -v pgdata:/data:ro -v \"$(pwd)\":/backup alpine \\\n    tar czf /backup/pgdata.tar.gz -C /data .\n# restore into a (new, empty) volume\n$ docker run --rm -v pgdata:/data -v \"$(pwd)\":/backup alpine \\\n    tar xzf /backup/pgdata.tar.gz -C /data</code></pre>\n<div class=\"learn-callout\">Copying a live database's files can give you a broken backup. Stop the database first, or use the database's own dump tool: <code>docker exec db pg_dump -U app app &gt; app.sql</code>.</div>\n\n<h4>Networks and DNS by container name</h4>\n<p>Containers on the default network (called <code>bridge</code>) can only reach each other by IP. On a network <i>you create</i>, Docker runs a built-in DNS server, so containers find each other by name:</p>\n<pre><code>$ docker network create appnet\n$ docker run -d --name db --network appnet -e POSTGRES_PASSWORD=example postgres:16\n$ docker run --rm --network appnet alpine ping -c 2 db     # \"db\" resolves\n$ docker network ls                   # bridge, host, none + yours\n$ docker network inspect appnet       # subnet and the containers attached\n$ docker network connect appnet web   # attach an already-running container</code></pre>\n<p>Other drivers: <code>host</code> shares the host's network directly (no isolation, no <code>-p</code> needed; Linux only) and <code>none</code> gives no network at all.</p>\n\n<h4>Publishing ports</h4>\n<p>Containers on the same network talk to each other on the <i>container</i> port directly (<code>db:5432</code>); no publishing needed. <code>-p</code> is only for traffic from outside Docker:</p>\n<pre><code>$ docker run -d -p 8080:80 nginx:1.27             # host 8080 -&gt; container 80, all interfaces\n$ docker run -d -p 127.0.0.1:8080:80 nginx:1.27   # only reachable from this machine\n$ docker port &lt;container&gt;                          # show what is published</code></pre>\n<div class=\"learn-callout\">On Linux, a plain <code>-p 8080:80</code> listens on every interface, and Docker writes its own firewall rules, so the port can be reachable from outside even if <code>ufw</code> seems to block it. Never publish a database port to the world; bind it to <code>127.0.0.1</code> or don't publish it at all.</div>\n\n<h4>A realistic compose.yaml</h4>\n<p>A web app and PostgreSQL, where the web container waits until the database actually accepts connections:</p>\n<pre><code>services:\n  web:\n    build: .\n    ports:\n      - \"127.0.0.1:3000:3000\"\n    env_file:\n      - web.env                        # vars injected into the container\n    environment:\n      DATABASE_URL: postgres://app:${POSTGRES_PASSWORD}@db:5432/app\n    depends_on:\n      db:\n        condition: service_healthy     # wait for the healthcheck, not just \"started\"\n    restart: unless-stopped\n\n  db:\n    image: postgres:16\n    environment:\n      POSTGRES_USER: app\n      POSTGRES_DB: app\n      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}\n    volumes:\n      - pgdata:/var/lib/postgresql/data\n    healthcheck:\n      test: [\"CMD-SHELL\", \"pg_isready -U app -d app\"]\n      interval: 5s\n      timeout: 3s\n      retries: 5\n      start_period: 10s\n\nvolumes:\n  pgdata:</code></pre>\n<p>Things to notice:</p>\n<ul>\n<li>No <code>version:</code> line. It's obsolete in current Compose (v2 and later), which only prints a warning if you include it.</li>\n<li>Compose creates a network called <code>&lt;project&gt;_default</code> automatically, so <code>web</code> reaches the database at host <code>db</code>. The database port isn't published at all.</li>\n<li><code>depends_on</code> conditions are <code>service_started</code> (the default), <code>service_healthy</code> and <code>service_completed_successfully</code>. It only controls startup order; your app should still retry if the database restarts later.</li>\n</ul>\n\n<h4>Two kinds of env files</h4>\n<ul>\n<li>A file named <code>.env</code> next to <code>compose.yaml</code> is read by Compose itself to fill in <code>${POSTGRES_PASSWORD}</code> in the YAML.</li>\n<li><code>env_file: web.env</code> passes every line of that file into the container as environment variables.</li>\n</ul>\n<pre><code># .env  (keep out of git and out of the image)\nPOSTGRES_PASSWORD=change-me\n\n# web.env\nLOG_LEVEL=info</code></pre>\n<p><code>docker compose config</code> prints the final file with every variable filled in, which is the quickest way to spot a missing one.</p>\n\n<h4>Everyday Compose commands</h4>\n<pre><code>$ docker compose up -d --build      # build if needed, start in the background\n$ docker compose ps                 # state and health of each service\n$ docker compose logs -f web        # follow one service's logs\n$ docker compose exec db psql -U app -d app\n$ docker compose restart web\n$ docker compose down               # remove containers and network, KEEP volumes\n$ docker compose down -v            # also delete volumes: the database is wiped</code></pre>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=pg19Z8LL06w&amp;t=2346s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Docker Crash Course <span class=\"learn-sources-part\">· Port binding (39:06)</span></a><a href=\"https://www.youtube.com/watch?v=DQdB7wFEygo&amp;t=501s\" target=\"_blank\" rel=\"noopener noreferrer\">The Coding Sloth · The Only Docker Tutorial You Need <span class=\"learn-sources-part\">· Multi-container apps (8:21)</span></a></div>","docker/debugging-containers":"\n<p class=\"learn-lead\">Sooner or later a container exits the moment it starts, a page won't load, or the disk fills up. Debugging containers follows a short routine: find out what state it's in, read what it said, look at how it was configured, then get inside if you need to.</p>\n\n<h4>Step 1: what state is it in?</h4>\n<pre><code>$ docker ps -a\nCONTAINER ID   IMAGE           STATUS                     NAMES\n3f2a9c1b7d4e   demee/app:1.1   Exited (1) 4 seconds ago   web</code></pre>\n<p><code>docker ps</code> only lists running containers; <code>-a</code> shows stopped ones too. The number in <code>Exited (1)</code> is the exit code, your first clue.</p>\n\n\n<figure class=\"learn-diagram dg\" data-dg=\"dk-lifecycle\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 210\" role=\"img\" aria-label=\"Container states: created, then running after start, then exited after a stop or crash; a restart policy can loop it between running and exited\" style=\"--dgw:680px\"><defs><marker id=\"dk-lifecycle--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker><marker id=\"dk-lifecycle--ok\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk ok\" d=\"M0,0 L8,4 L0,8 z\"/></marker><marker id=\"dk-lifecycle--warn\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk warn\" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"b\" x=\"10\" y=\"70\" width=\"130\" height=\"56\" rx=\"6\"/><text class=\"tb\" x=\"75\" y=\"94.7\" text-anchor=\"middle\" font-size=\"13\">created</text><text class=\"t2\" x=\"75\" y=\"110.0\" text-anchor=\"middle\" font-size=\"11\">docker create</text><rect class=\"b ok\" x=\"250\" y=\"70\" width=\"150\" height=\"56\" rx=\"6\"/><text class=\"tb\" x=\"325\" y=\"94.7\" text-anchor=\"middle\" font-size=\"13\">running</text><text class=\"t2\" x=\"325\" y=\"110.0\" text-anchor=\"middle\" font-size=\"11\">Up 3 minutes</text><rect class=\"b bad\" x=\"520\" y=\"70\" width=\"150\" height=\"56\" rx=\"6\"/><text class=\"tb\" x=\"595\" y=\"94.7\" text-anchor=\"middle\" font-size=\"13\">exited</text><text class=\"t2\" x=\"595\" y=\"110.0\" text-anchor=\"middle\" font-size=\"11\">Exited (1)</text><path class=\"ln\" d=\"M142,98 L248,98\" marker-end=\"url(#dk-lifecycle--n)\"/><text class=\"tl\" x=\"195\" y=\"91\" text-anchor=\"middle\" font-size=\"11\">start</text><path class=\"ln\" d=\"M402,88 L518,88\" marker-end=\"url(#dk-lifecycle--n)\"/><text class=\"tl\" x=\"460\" y=\"80\" text-anchor=\"middle\" font-size=\"11\">stop or crash</text><path class=\"ln ok\" d=\"M518,112 L402,112\" marker-end=\"url(#dk-lifecycle--ok)\"/><text class=\"ok\" x=\"460\" y=\"130\" text-anchor=\"middle\" font-size=\"11\">docker start</text><path class=\"ln warn dash\" d=\"M595,128 L595,170 L325,170 L325,128\" marker-end=\"url(#dk-lifecycle--warn)\"/><text class=\"warn\" x=\"460\" y=\"190\" text-anchor=\"middle\" font-size=\"11\">restart policy: crash, start, crash...</text><text class=\"tb\" x=\"340\" y=\"30\" text-anchor=\"middle\" font-size=\"12\">docker ps -a shows the state and the exit code</text></svg></div><figcaption>The exit code in <code>Exited (1)</code> is your first clue. A container that keeps flipping between running and exited is crashing on start: read its logs.</figcaption></figure>\n<h4>Step 2: read the logs</h4>\n<pre><code>$ docker logs web                  # works on stopped containers too\n$ docker logs --tail 50 -t web     # last 50 lines, with timestamps\n$ docker logs --since 10m -f web   # last 10 minutes, then follow</code></pre>\n<p>Docker only captures what the main process writes to <b>stdout and stderr</b>. If your app logs to a file inside the container, <code>docker logs</code> stays empty; configure the app to log to the console instead.</p>\n\n<h4>Container exits immediately</h4>\n<p>A container lives exactly as long as its main process. Common reasons it ends straight away:</p>\n<ul>\n<li><b>The app crashed</b> on startup: missing environment variable, bad config, can't reach the database. The logs say so.</li>\n<li><b>The command finished</b>: <code>docker run ubuntu</code> starts <code>bash</code>, which exits at once because no input is attached (no <code>-it</code>). That's normal, not a bug.</li>\n<li><b>The process went to the background</b>: a start script runs a daemon that forks and returns (e.g. <code>service nginx start</code>). The main process must stay in the foreground: <code>nginx -g 'daemon off;'</code>.</li>\n</ul>\n<p>To poke around in an image that won't stay up, replace its command with a shell:</p>\n<pre><code>$ docker run --rm -it --entrypoint sh demee/app:1.1</code></pre>\n\n<h4>What the exit code means</h4>\n<div class=\"learn-table-wrap\"><table class=\"learn-table\"><thead><tr><th>Code</th><th>Meaning</th><th>Typical cause</th></tr></thead><tbody>\n<tr><td><b>0</b></td><td>Finished successfully</td><td>A one-off job completed, or the command simply ended</td></tr>\n<tr><td><b>1</b></td><td>General application error</td><td>Uncaught exception, failed config check: read the logs</td></tr>\n<tr><td><b>125 / 126 / 127</b></td><td>Docker couldn't start it / command not executable / command not found</td><td>Wrong <code>docker run</code> flags, missing execute permission, typo or missing binary in <code>CMD</code></td></tr>\n<tr><td><b>137</b></td><td>128 + 9: killed with <code>SIGKILL</code></td><td>Out of memory, <code>docker kill</code>, or <code>docker stop</code> timed out</td></tr>\n<tr><td><b>139</b></td><td>128 + 11: segmentation fault</td><td>A crash in native code: a C library, a native module, a bug or incompatibility below your app</td></tr>\n<tr><td><b>143</b></td><td>128 + 15: stopped by <code>SIGTERM</code></td><td>A normal <code>docker stop</code> that the app handled</td></tr>\n</tbody></table></div>\n\n<h4>docker inspect: the full picture</h4>\n<p><code>docker inspect web</code> prints everything Docker knows about a container as JSON. Use <code>--format</code> to pick out fields:</p>\n<pre><code>$ docker inspect --format '{{.State.Status}} exit={{.State.ExitCode}} oom={{.State.OOMKilled}}' web\nexited exit=137 oom=true           # 137 + OOMKilled: it ran out of memory\n$ docker inspect --format '{{json .Mounts}}' web          # what is mounted where\n$ docker inspect --format '{{json .Config.Env}}' web      # env vars it got\n$ docker inspect --format '{{json .State.Health}}' web    # healthcheck results</code></pre>\n\n<h4>Getting inside, even without a shell</h4>\n<pre><code>$ docker exec -it web sh           # or bash, if the image has it\n$ docker exec web env              # run a single command, no shell needed\nOCI runtime exec failed: ... exec: \"sh\": executable file not found in $PATH</code></pre>\n<p>That error means a minimal image (distroless, <code>scratch</code>) with no shell. You can still debug from outside:</p>\n<pre><code>$ docker top web                          # processes running in it\n$ docker cp web:/etc/app/config.yaml .    # copy a file out (works on stopped containers too)\n$ docker diff web                         # files changed since it started\n$ docker run --rm -it --network container:web nicolaka/netshoot\n#   a toolbox container sharing web's network: curl, dig, ss, tcpdump...</code></pre>\n\n<h4>Resource usage: docker stats</h4>\n<pre><code>$ docker stats                 # live CPU %, MEM USAGE / LIMIT, NET I/O, PIDS\n$ docker stats --no-stream     # one snapshot\n$ docker run -d -m 512m --cpus 1.5 demee/app:1.1   # set limits</code></pre>\n<p>Memory creeping toward the limit ends in an exit code 137 with <code>OOMKilled</code> true.</p>\n\n<h4>\"Port not reachable\"</h4>\n<p>Work through it in order:</p>\n<ol>\n<li><b>Is it published?</b> <code>docker port web</code>. No output means you forgot <code>-p</code>.</li>\n<li><b>Right container port?</b> <code>-p 8080:3000</code> only works if the app really listens on 3000.</li>\n<li><b>Is the app listening on 127.0.0.1?</b> This is the classic one. Inside a container, <code>127.0.0.1</code> is the container's <i>own</i> loopback. Published traffic arrives on the container's network interface, so an app bound to 127.0.0.1 never sees it. Make it listen on <code>0.0.0.0</code>: <code>flask run --host=0.0.0.0</code>, <code>python manage.py runserver 0.0.0.0:8000</code>, <code>vite --host</code>.</li>\n</ol>\n<pre><code>$ docker run --rm --network container:web nicolaka/netshoot ss -tln\nLISTEN 0  128  127.0.0.1:5000  0.0.0.0:*    # bad: loopback only\nLISTEN 0  128    0.0.0.0:5000  0.0.0.0:*    # good: all interfaces</code></pre>\n\n<h4>Permission denied on a bind mount</h4>\n<p>A bind mount keeps the host's file owners as plain numbers (UID/GID). If the container runs as user <code>node</code> (UID 1000) and the host folder belongs to UID 1001 or to root, writes fail with <code>EACCES: permission denied</code>.</p>\n<pre><code>$ docker exec web id                  # which UID the app runs as\n$ ls -ln ./data                        # which UID owns the host folder\n# fixes, pick one:\n$ docker run --user \"$(id -u):$(id -g)\" -v \"$(pwd)/data\":/app/data ...   # run as you\n$ sudo chown -R 1000:1000 ./data       # give the folder to the container's UID\n# ...or use a named volume instead of a bind mount</code></pre>\n<p>On Fedora/RHEL with SELinux, you may also need to add <code>:z</code> to the mount (<code>-v \"$(pwd)/data\":/app/data:z</code>) so the container is allowed to access it.</p>\n\n<h4>Disk full: cleaning up</h4>\n<pre><code>$ docker system df            # space used by images, containers, volumes, build cache\n$ docker system df -v         # the same, item by item\n$ docker system prune         # stopped containers, unused networks,\n                              # dangling images, unused build cache\n$ docker system prune -a      # also every image not used by a container\n$ docker image prune -a       # just images\n$ docker builder prune        # just build cache</code></pre>\n<div class=\"learn-callout\">Volumes are left alone by default because they hold data. <code>docker system prune --volumes</code> adds anonymous volumes; named volumes are only removed with <code>docker volume prune -a</code> or <code>docker volume rm</code>. Read the confirmation prompt before you type <code>y</code>.</div>\n\n<h4>Quick error lookup</h4>\n<div class=\"learn-table-wrap\"><table class=\"learn-table\"><thead><tr><th>Error</th><th>Fix</th></tr></thead><tbody>\n<tr><td><code>Bind for 0.0.0.0:8080 failed: port is already allocated</code></td><td>Another container or program uses that host port: pick another or stop it</td></tr>\n<tr><td><code>Conflict. The container name \"/web\" is already in use</code></td><td><code>docker rm web</code> first, or run with <code>--rm</code> so it's removed on exit</td></tr>\n<tr><td><code>pull access denied ... may require 'docker login'</code></td><td>Typo in the image name, or a private image: <code>docker login</code></td></tr>\n<tr><td><code>manifest unknown</code></td><td>That tag doesn't exist: check the tag list on the registry</td></tr>\n<tr><td><code>exec format error</code></td><td>Wrong CPU architecture: rebuild with <code>--platform</code></td></tr>\n<tr><td><code>no space left on device</code></td><td><code>docker system df</code>, then prune</td></tr>\n</tbody></table></div>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=DQdB7wFEygo&amp;t=437s\" target=\"_blank\" rel=\"noopener noreferrer\">The Coding Sloth · The Only Docker Tutorial You Need <span class=\"learn-sources-part\">· Debugging and security (7:17)</span></a><a href=\"https://www.youtube.com/watch?v=pg19Z8LL06w&amp;t=2570s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Docker Crash Course <span class=\"learn-sources-part\">· Start and stop containers (42:50)</span></a></div>","docker/registries-and-image-security":"\n<p class=\"learn-lead\">Building an image is half the job. It has to live somewhere every machine can pull it from, you need to know exactly which version is running, and it shouldn't ship with known holes or secrets baked in. This chapter covers registries, tags versus digests, scanning, and the habits that make an image hard to attack.</p>\n\n<h4>What a registry holds</h4>\n<p>A <b>registry</b> is a server that stores images: Docker Hub, GitHub Container Registry (<b>GHCR</b>), Amazon <b>ECR</b>, Google Artifact Registry, or one you run yourself. Inside it, each <b>repository</b> holds the versions of one image. The full name of an image tells Docker where to find it:</p>\n<pre><code>ghcr.io/demee/shop-api:1.4.0\n└──┬──┘ └─┬─┘ └──┬───┘ └─┬─┘\nregistry  owner  repository  tag\n\nnginx:1.27          # no registry part means Docker Hub, and the owner \"library\" (official images)</code></pre>\n<p>Every image also has a <b>digest</b>: <code>sha256:</code> followed by a hash of its contents. The tag is a name you choose; the digest is calculated from what's inside.</p>\n\n<h4>Tags move, digests don't</h4>\n<p>A tag is just a label pointing at a digest, and anyone who can push can move it. <code>nginx:1.27</code> today and <code>nginx:1.27</code> next month are usually different images, because the maintainers rebuild it with security fixes. <code>latest</code> moves all the time. A digest can never point at anything else.</p>\n<figure class=\"learn-diagram dg\" data-dg=\"dk-digest\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 230\" role=\"img\" aria-label=\"An image name splits into registry ghcr.io, owner demee, repository shop-api and tag 1.4.0; tags like 1.4.0 and latest point at a digest and can be moved, while a digest is computed from the contents and never changes\" style=\"--dgw:680px\"><defs><marker id=\"dk-digest--warn\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk warn\" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"b\" x=\"10\" y=\"14\" width=\"120\" height=\"52\" rx=\"6\"/><text class=\"tb tm\" x=\"70\" y=\"37.2\" text-anchor=\"middle\" font-size=\"13\">ghcr.io</text><text class=\"t2\" x=\"70\" y=\"51.7\" text-anchor=\"middle\" font-size=\"10\">registry</text><rect class=\"b\" x=\"140\" y=\"14\" width=\"100\" height=\"52\" rx=\"6\"/><text class=\"tb tm\" x=\"190\" y=\"37.2\" text-anchor=\"middle\" font-size=\"13\">demee</text><text class=\"t2\" x=\"190\" y=\"51.7\" text-anchor=\"middle\" font-size=\"10\">owner</text><rect class=\"b\" x=\"250\" y=\"14\" width=\"130\" height=\"52\" rx=\"6\"/><text class=\"tb tm\" x=\"315\" y=\"37.2\" text-anchor=\"middle\" font-size=\"13\">shop-api</text><text class=\"t2\" x=\"315\" y=\"51.7\" text-anchor=\"middle\" font-size=\"10\">repository</text><rect class=\"b hi\" x=\"390\" y=\"14\" width=\"100\" height=\"52\" rx=\"6\"/><text class=\"tb ta tm\" x=\"440\" y=\"37.2\" text-anchor=\"middle\" font-size=\"13\">:1.4.0</text><text class=\"t2\" x=\"440\" y=\"51.7\" text-anchor=\"middle\" font-size=\"10\">tag</text><text class=\"t2\" x=\"560\" y=\"44\" text-anchor=\"middle\" font-size=\"12\">one image name</text><rect class=\"b warn\" x=\"10\" y=\"120\" width=\"170\" height=\"52\" rx=\"6\"/><text class=\"tb tm\" x=\"95\" y=\"143.2\" text-anchor=\"middle\" font-size=\"13\">:1.4.0</text><text class=\"t2\" x=\"95\" y=\"157.7\" text-anchor=\"middle\" font-size=\"10\">today</text><rect class=\"b warn\" x=\"10\" y=\"176\" width=\"170\" height=\"44\" rx=\"6\"/><text class=\"tb tm\" x=\"95\" y=\"202.2\" text-anchor=\"middle\" font-size=\"13\">:latest</text><rect class=\"b ok\" x=\"330\" y=\"110\" width=\"340\" height=\"48\" rx=\"6\"/><text class=\"tb tm\" x=\"500\" y=\"131.2\" text-anchor=\"middle\" font-size=\"13\">sha256:4ff1...c39e</text><text class=\"t2\" x=\"500\" y=\"145.7\" text-anchor=\"middle\" font-size=\"10\">fixed: computed from the contents</text><rect class=\"b\" x=\"330\" y=\"170\" width=\"340\" height=\"48\" rx=\"6\"/><text class=\"tb tm\" x=\"500\" y=\"191.2\" text-anchor=\"middle\" font-size=\"13\">sha256:9a07...51d2</text><text class=\"t2\" x=\"500\" y=\"205.7\" text-anchor=\"middle\" font-size=\"10\">next month&#x27;s rebuild</text><path class=\"ln warn\" d=\"M182,146 L328,134\" marker-end=\"url(#dk-digest--warn)\"/><text class=\"tl\" x=\"255\" y=\"130\" text-anchor=\"middle\" font-size=\"11\">points at</text><path class=\"ln warn dash\" d=\"M182,198 L328,194\" marker-end=\"url(#dk-digest--warn)\"/><text class=\"tl\" x=\"255\" y=\"214\" text-anchor=\"middle\" font-size=\"11\">can move to</text></svg></div><figcaption>A tag is a sticky note you can move. A digest is the image's fingerprint. Deploy by SHA or version tag, and pin digests when you need the exact same bytes every time.</figcaption></figure>\n\n<pre><code>$ docker buildx imagetools inspect nginx:1.27      # shows the digest the tag points at right now\nName:      docker.io/library/nginx:1.27\nDigest:    sha256:4ff1...c39e\n$ docker pull nginx@sha256:4ff1...c39e             # pull exactly that image, forever\n$ docker images --digests                          # digests of what you already have</code></pre>\n<p>In a <code>FROM</code> line you can pin both, so the file stays readable and the build stays repeatable: <code>FROM python:3.12-slim@sha256:...</code>. Tools like Dependabot can bump the digest for you when a new base image comes out.</p>\n\n<h4>Pushing to a registry</h4>\n<p>Tag the image with the registry's name, log in, push. The three you'll meet most:</p>\n<pre><code># Docker Hub\n$ docker login                                     # opens a browser or asks for an access token\n$ docker tag shop-api:dev demee/shop-api:1.4.0\n$ docker push demee/shop-api:1.4.0\n\n# GitHub Container Registry: log in with a personal access token that has write:packages\n$ echo \"$GHCR_TOKEN\" | docker login ghcr.io -u demee --password-stdin\n$ docker tag shop-api:dev ghcr.io/demee/shop-api:1.4.0\n$ docker push ghcr.io/demee/shop-api:1.4.0\n\n# Amazon ECR: the repository must exist, and the password comes from the AWS CLI\n$ aws ecr create-repository --repository-name shop-api\n$ aws ecr get-login-password --region eu-central-1 \\\n    | docker login --username AWS --password-stdin 123456789012.dkr.ecr.eu-central-1.amazonaws.com\n$ docker tag shop-api:dev 123456789012.dkr.ecr.eu-central-1.amazonaws.com/shop-api:1.4.0\n$ docker push 123456789012.dkr.ecr.eu-central-1.amazonaws.com/shop-api:1.4.0</code></pre>\n<p>Use <code>--password-stdin</code> so the token never lands in your shell history. In GitHub Actions you don't need a personal token for GHCR at all: the built-in <code>GITHUB_TOKEN</code> works once the workflow has <code>permissions: packages: write</code> (the CI/CD pipeline chapter shows the whole job). Docker Hub limits how often anonymous users can pull, so log in on CI machines and servers too.</p>\n\n<h4>A tagging scheme that tells you what's running</h4>\n<ul>\n<li><b>The commit SHA</b> on every image CI builds: <code>shop-api:3f9c2a1</code>. You can always trace a running container back to the exact code.</li>\n<li><b>A version</b> for releases: <code>shop-api:1.4.0</code>, plus <code>1.4</code> and <code>1</code> if people pull you by major version.</li>\n<li><b>Never deploy <code>latest</code></b>. It says nothing about what's inside, two servers can end up running different things under the same name, and rolling back to \"the previous latest\" is impossible.</li>\n</ul>\n\n<h4>Scanning for known vulnerabilities</h4>\n<p>Every package in an image (the OS packages from the base image and your app's libraries) might have published security holes, called <b>CVEs</b>. A scanner reads what's installed and checks it against vulnerability databases. Two common ones are <b>Trivy</b> (open source) and <b>Docker Scout</b> (built into Docker Desktop and the CLI):</p>\n<pre><code>$ trivy image shop-api:1.4.0\nshop-api:1.4.0 (debian 12.7)\nTotal: 23 (UNKNOWN: 0, LOW: 14, MEDIUM: 6, HIGH: 3, CRITICAL: 0)\n\n│ Library  │ Vulnerability  │ Severity │ Installed │ Fixed Version │\n│ libssl3  │ CVE-2024-XXXXX │ HIGH     │ 3.0.14-1  │ 3.0.15-1      │\n\n$ docker scout cves shop-api:1.4.0                 # the same idea with Docker Scout\n\n# No Trivy installed? Run it as a container:\n$ docker run --rm -v /var/run/docker.sock:/var/run/docker.sock aquasec/trivy image shop-api:1.4.0</code></pre>\n<p>Read the report by the <b>Fixed Version</b> column. A HIGH with a fix available usually just means \"rebuild on a newer base image\"; one with no fix yet is something to know about, not something you can patch today. In CI, fail the build only on what you can act on:</p>\n<pre><code>$ trivy image --severity HIGH,CRITICAL --ignore-unfixed --exit-code 1 shop-api:1.4.0</code></pre>\n<p>Scan again on a schedule too. An image that was clean when you built it collects new CVEs as they're discovered, even though nothing in it changed.</p>\n\n<h4>Give attackers less to work with</h4>\n<ul>\n<li><b>Small base images.</b> <code>-slim</code>, <code>alpine</code> or distroless images contain fewer packages, so fewer CVEs and fewer tools an attacker can use after breaking in. Multi-stage builds (Docker chapter 3) keep compilers out of the final image.</li>\n<li><b>Don't run as root.</b> Add a user and switch to it with <code>USER</code>, as in Docker chapter 3.</li>\n<li><b>Lock the container down at run time</b> when the app allows it:\n<pre><code>$ docker run --read-only --tmpfs /tmp \\\n    --cap-drop ALL --security-opt no-new-privileges:true \\\n    shop-api:1.4.0</code></pre>\nA read-only filesystem means a break-in can't drop files; dropping Linux capabilities and blocking privilege escalation stops root-only tricks.</li>\n<li><b>Never put secrets in an image.</b> Anything you <code>COPY</code> or <code>ENV</code> into a layer can be read by anyone who can pull the image, even if a later layer deletes it. Pass secrets at run time (environment variables, mounted files, a secrets manager). If the build itself needs one, for example a token for a private package registry, use a BuildKit secret, which is never stored in a layer:\n<pre><code># Dockerfile\nRUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm ci\n\n$ docker build --secret id=npmrc,src=$HOME/.npmrc -t shop-api:dev .</code></pre></li>\n</ul>\n\n<h4>SBOMs and signatures, briefly</h4>\n<p>A <b>software bill of materials</b> (SBOM) is a list of every package in an image, so that when the next big vulnerability is announced you can search your SBOMs instead of rescanning everything: <code>docker scout sbom shop-api:1.4.0</code> or <code>trivy image --format cyclonedx --output sbom.json shop-api:1.4.0</code>.</p>\n<p><b>Signing</b> proves an image came from your pipeline and wasn't swapped. <b>Cosign</b> (from the Sigstore project) can sign images in CI using the workflow's own identity, with no long-lived key to guard, and a cluster can be set up to refuse unsigned images. You won't need it on day one, but you'll hear about it in interviews.</p>\n\n<h4>Common mistakes</h4>\n<ul>\n<li><b>\"denied: requested access to the resource is denied\"</b> on push: not logged in to that registry, the image isn't tagged with your namespace (<code>docker push shop-api:1.4.0</code> tries Docker Hub's <code>library</code>), or the token lacks write permission.</li>\n<li><b>\"no basic auth credentials\"</b> with ECR: the login expired. ECR passwords last 12 hours, so log in again.</li>\n<li><b>Pulled an old image without noticing</b>: a server already had <code>app:latest</code> cached. Deploy by SHA or version tag, or pass <code>--pull always</code> / <code>docker compose pull</code> first.</li>\n<li><b>A secret in an old layer</b>: deleting the file in a later layer doesn't help. Remove it from the build, rebuild, and rotate the secret, because it's already out.</li>\n<li><b>Ignoring the scanner because the list is long</b>: filter to HIGH and CRITICAL with a fix available, fix those by updating the base image, and work down from there.</li>\n</ul>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=pg19Z8LL06w&amp;t=1592s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Docker Crash Course <span class=\"learn-sources-part\">· Docker registries (26:32)</span></a><a href=\"https://www.youtube.com/watch?v=pg19Z8LL06w&amp;t=1778s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Docker Crash Course <span class=\"learn-sources-part\">· Image versions and tags (29:38)</span></a><a href=\"https://www.youtube.com/watch?v=pg19Z8LL06w&amp;t=2814s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Docker Crash Course <span class=\"learn-sources-part\">· Private registries (46:54)</span></a></div>\n","kubernetes/how-kubernetes-works":"\n<p class=\"learn-lead\">Docker runs containers on one machine. Kubernetes (K8s) runs them across a whole cluster of machines and keeps them healthy: you describe what you want running, and it works continuously to make reality match.</p>\n\n<h4>Why it exists</h4>\n<p>Once an app is split into many containers across many servers, doing it by hand breaks down: which server has room? What happens when a container crashes at 3 a.m., or a whole server dies? How do you roll out a new version without downtime, or add copies when traffic spikes? Kubernetes is a <b>container orchestrator</b> that handles all of this automatically: scheduling, self-healing, scaling, rolling updates and service discovery.</p>\n<p>The core idea is <b>desired state</b>. You tell Kubernetes \"I want 3 copies of this app running\"; controllers constantly compare that with what's actually running and fix any difference. Kill a pod and a new one appears.</p>\n\n<h4>Architecture: control plane and worker nodes</h4>\n<p>A <b>cluster</b> is a set of machines called <b>nodes</b>. The <b>control plane</b> is the brain:</p>\n<ul>\n<li><b>API server</b>: the front door. Everything, including <code>kubectl</code> and the other components, talks to the cluster through it.</li>\n<li><b>etcd</b>: a key-value database holding the whole cluster's state and configuration.</li>\n<li><b>Scheduler</b>: decides which node each new pod should run on, based on free CPU and memory.</li>\n<li><b>Controller manager</b>: runs the control loops that keep actual state matching desired state.</li>\n</ul>\n<p><b>Worker nodes</b> run your apps, and each one has:</p>\n<ul>\n<li><b>kubelet</b>: the agent that starts and watches the pods assigned to its node;</li>\n<li>a <b>container runtime</b> (containerd) that actually runs the containers;</li>\n<li><b>kube-proxy</b>: the networking rules that make Services work.</li>\n</ul>\n<p>You can run Kubernetes locally with <b>minikube</b> or <b>kind</b> for learning, or use a managed service (<b>EKS</b> on AWS, <b>GKE</b> on Google, <b>AKS</b> on Azure) where the cloud runs the control plane for you.</p>\n\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=H_a5DTKSEjY&amp;t=108s\" target=\"_blank\" rel=\"noopener noreferrer\">Vishakha Sadhwani · The ONLY Kubernetes Course You'll Ever Need <span class=\"learn-sources-part\">· Why Kubernetes exists (1:48)</span></a><a href=\"https://www.youtube.com/watch?v=H_a5DTKSEjY&amp;t=330s\" target=\"_blank\" rel=\"noopener noreferrer\">Vishakha Sadhwani · The ONLY Kubernetes Course You'll Ever Need <span class=\"learn-sources-part\">· Architecture: control plane vs data plane (5:30)</span></a><a href=\"https://www.youtube.com/watch?v=s_o8dwzRlu4\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Kubernetes Crash Course <span class=\"learn-sources-part\">· Kubernetes crash course (0:00)</span></a></div>\n<figure class=\"learn-diagram dg\" data-dg=\"k8s-arch\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 330\" role=\"img\" aria-label=\"A Kubernetes cluster: kubectl talks to the API server in the control plane, next to etcd, the scheduler and the controller manager; worker nodes run kubelet, kube-proxy, containerd and pods\" style=\"--dgw:680px\"><defs><marker id=\"k8s-arch--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"b warn\" x=\"10\" y=\"20\" width=\"120\" height=\"50\" rx=\"6\"/><text class=\"tb tm\" x=\"70\" y=\"41.7\" text-anchor=\"middle\" font-size=\"13\">kubectl</text><text class=\"t2\" x=\"70\" y=\"57.0\" text-anchor=\"middle\" font-size=\"11\">you</text><rect class=\"g hi\" x=\"150\" y=\"10\" width=\"520\" height=\"120\" rx=\"8\"/><text class=\"tg hi\" x=\"160\" y=\"26\" font-size=\"11\">control plane: the brain</text><rect class=\"b hi\" x=\"166\" y=\"40\" width=\"130\" height=\"70\" rx=\"6\"/><text class=\"tb ta\" x=\"231\" y=\"72.2\" text-anchor=\"middle\" font-size=\"13\">API server</text><text class=\"t2\" x=\"231\" y=\"86.7\" text-anchor=\"middle\" font-size=\"10\">the front door</text><rect class=\"b\" x=\"312\" y=\"40\" width=\"104\" height=\"70\" rx=\"6\"/><text class=\"tb\" x=\"364\" y=\"72.2\" text-anchor=\"middle\" font-size=\"13\">etcd</text><text class=\"t2\" x=\"364\" y=\"86.7\" text-anchor=\"middle\" font-size=\"10\">all state</text><rect class=\"b\" x=\"428\" y=\"40\" width=\"110\" height=\"70\" rx=\"6\"/><text class=\"tb\" x=\"483\" y=\"72.2\" text-anchor=\"middle\" font-size=\"13\">scheduler</text><text class=\"t2\" x=\"483\" y=\"86.7\" text-anchor=\"middle\" font-size=\"10\">picks nodes</text><rect class=\"b\" x=\"550\" y=\"40\" width=\"106\" height=\"70\" rx=\"6\"/><text class=\"tb\" x=\"603\" y=\"65.2\" text-anchor=\"middle\" font-size=\"13\">controller</text><text class=\"t2\" x=\"603\" y=\"79.7\" text-anchor=\"middle\" font-size=\"10\">manager</text><text class=\"t2\" x=\"603\" y=\"93.7\" text-anchor=\"middle\" font-size=\"10\">keeps it so</text><path class=\"ln\" d=\"M132,55 L164,55\" marker-end=\"url(#k8s-arch--n)\"/><rect class=\"g\" x=\"150\" y=\"160\" width=\"254\" height=\"160\" rx=\"8\"/><text class=\"tg \" x=\"160\" y=\"176\" font-size=\"11\">worker node 1</text><rect class=\"b\" x=\"162\" y=\"188\" width=\"112\" height=\"40\" rx=\"6\"/><text class=\"tb\" x=\"218\" y=\"211.8\" text-anchor=\"middle\" font-size=\"12\">kubelet</text><rect class=\"b\" x=\"280\" y=\"188\" width=\"112\" height=\"40\" rx=\"6\"/><text class=\"tb\" x=\"336\" y=\"211.8\" text-anchor=\"middle\" font-size=\"12\">kube-proxy</text><rect class=\"b\" x=\"162\" y=\"236\" width=\"230\" height=\"32\" rx=\"6\"/><text class=\"\" x=\"277\" y=\"255.5\" text-anchor=\"middle\" font-size=\"11\">containerd (runtime)</text><rect class=\"b ok\" x=\"162\" y=\"276\" width=\"70\" height=\"34\" rx=\"6\"/><text class=\"tb\" x=\"197\" y=\"296.8\" text-anchor=\"middle\" font-size=\"12\">pod</text><rect class=\"b ok\" x=\"240\" y=\"276\" width=\"70\" height=\"34\" rx=\"6\"/><text class=\"tb\" x=\"275\" y=\"296.8\" text-anchor=\"middle\" font-size=\"12\">pod</text><rect class=\"b ok\" x=\"318\" y=\"276\" width=\"70\" height=\"34\" rx=\"6\"/><text class=\"tb\" x=\"353\" y=\"296.8\" text-anchor=\"middle\" font-size=\"12\">pod</text><path class=\"ln  dash\" d=\"M231,112 L218,186\" marker-end=\"url(#k8s-arch--n)\"/><rect class=\"g\" x=\"416\" y=\"160\" width=\"254\" height=\"160\" rx=\"8\"/><text class=\"tg \" x=\"426\" y=\"176\" font-size=\"11\">worker node 2</text><rect class=\"b\" x=\"428\" y=\"188\" width=\"112\" height=\"40\" rx=\"6\"/><text class=\"tb\" x=\"484\" y=\"211.8\" text-anchor=\"middle\" font-size=\"12\">kubelet</text><rect class=\"b\" x=\"546\" y=\"188\" width=\"112\" height=\"40\" rx=\"6\"/><text class=\"tb\" x=\"602\" y=\"211.8\" text-anchor=\"middle\" font-size=\"12\">kube-proxy</text><rect class=\"b\" x=\"428\" y=\"236\" width=\"230\" height=\"32\" rx=\"6\"/><text class=\"\" x=\"543\" y=\"255.5\" text-anchor=\"middle\" font-size=\"11\">containerd (runtime)</text><rect class=\"b ok\" x=\"428\" y=\"276\" width=\"70\" height=\"34\" rx=\"6\"/><text class=\"tb\" x=\"463\" y=\"296.8\" text-anchor=\"middle\" font-size=\"12\">pod</text><rect class=\"b ok\" x=\"506\" y=\"276\" width=\"70\" height=\"34\" rx=\"6\"/><text class=\"tb\" x=\"541\" y=\"296.8\" text-anchor=\"middle\" font-size=\"12\">pod</text><rect class=\"b ok\" x=\"584\" y=\"276\" width=\"70\" height=\"34\" rx=\"6\"/><text class=\"tb\" x=\"619\" y=\"296.8\" text-anchor=\"middle\" font-size=\"12\">pod</text><path class=\"ln  dash\" d=\"M231,112 L484,186\" marker-end=\"url(#k8s-arch--n)\"/></svg></div><figcaption>Everything goes through the API server, kubectl included. The control plane decides; the kubelet on each worker node makes it happen.</figcaption></figure>\n","kubernetes/objects-manifests-kubectl":"\n<p class=\"learn-lead\">You never tell Kubernetes \"start this container on that server\". You describe objects (a Deployment with 3 replicas, a Service in front of it) in YAML files, hand them to the cluster, and let the control plane work out the rest.</p>\n\n<h4>The main objects</h4>\n<ul>\n<li><b>Pod</b>: the smallest unit, one (sometimes a few tightly coupled) containers sharing an IP. Pods are disposable and get replaced, never repaired.</li>\n<li><b>Deployment</b>: manages identical pods for a stateless app: how many replicas, which image, how to roll out updates. You almost never create pods directly; you create a Deployment.</li>\n<li><b>StatefulSet</b>: like a Deployment, but for databases and other stateful apps, giving each pod a stable name and its own storage.</li>\n<li><b>Service</b>: a stable name and IP in front of a changing set of pods, load-balancing between them.</li>\n<li><b>Ingress</b>: routes outside HTTP/HTTPS traffic to Services by hostname or path.</li>\n<li><b>ConfigMap</b> and <b>Secret</b>: configuration and sensitive values kept outside the image and passed to pods as environment variables or files. Secrets are only base64-encoded by default, not encrypted, so access to them must be restricted.</li>\n<li><b>Volume / PersistentVolumeClaim</b>: storage that outlives a pod.</li>\n<li><b>Namespace</b>: a way to divide one cluster into separate areas (per team or per environment).</li>\n</ul>\n\n<h4>Manifests: describing what you want</h4>\n<p>Objects are written as YAML files with four parts: <code>apiVersion</code>, <code>kind</code>, <code>metadata</code> (name, labels) and <code>spec</code> (the desired state). <b>Labels</b> and <b>selectors</b> connect things: the Service finds its pods because they carry the label it selects.</p>\n<pre><code>apiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: web\nspec:\n  replicas: 3                        # keep 3 pods running\n  selector:\n    matchLabels: {app: web}\n  template:                          # the pod blueprint\n    metadata:\n      labels: {app: web}\n    spec:\n      containers:\n        - name: web\n          image: demee/app:1.0\n          ports: [{containerPort: 3000}]\n          envFrom: [{configMapRef: {name: web-config}}]\n---\napiVersion: v1\nkind: Service\nmetadata:\n  name: web\nspec:\n  selector: {app: web}               # send traffic to pods labelled app=web\n  ports: [{port: 80, targetPort: 3000}]</code></pre>\n\n<h4>kubectl: talking to the cluster</h4>\n<pre><code>$ kubectl apply -f web.yaml          # create/update to match the file\n$ kubectl get pods                   # also: deployments, services, nodes, all\n$ kubectl describe pod web-6d9f...   # details and recent events (why it's failing)\n$ kubectl logs -f web-6d9f...        # container output\n$ kubectl exec -it web-6d9f... -- sh # shell inside the pod\n$ kubectl scale deployment web --replicas=5\n$ kubectl set image deployment/web web=demee/app:1.1   # rolling update\n$ kubectl rollout undo deployment/web                   # roll back\n$ kubectl delete -f web.yaml</code></pre>\n<h4>What happens when you apply a file</h4>\n<figure class=\"learn-diagram dg\" data-dg=\"k8s-apply\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 200\" role=\"img\" aria-label=\"What kubectl apply sets off: the API server saves the manifest, controllers create pods, the scheduler places them, kubelets start them and the Service starts sending traffic\" style=\"--dgw:680px\"><defs><marker id=\"k8s-apply--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"b warn\" x=\"10\" y=\"20\" width=\"200\" height=\"60\" rx=\"6\"/><text class=\"tb\" x=\"110\" y=\"46.7\" text-anchor=\"middle\" font-size=\"13\">1 kubectl apply</text><text class=\"t2\" x=\"110\" y=\"62.0\" text-anchor=\"middle\" font-size=\"11\">sends the manifest</text><rect class=\"b hi\" x=\"240\" y=\"20\" width=\"200\" height=\"60\" rx=\"6\"/><text class=\"tb ta\" x=\"340\" y=\"46.7\" text-anchor=\"middle\" font-size=\"13\">2 API server</text><text class=\"t2\" x=\"340\" y=\"62.0\" text-anchor=\"middle\" font-size=\"11\">checks, saves to etcd</text><rect class=\"b\" x=\"470\" y=\"20\" width=\"200\" height=\"60\" rx=\"6\"/><text class=\"tb\" x=\"570\" y=\"46.7\" text-anchor=\"middle\" font-size=\"13\">3 controllers</text><text class=\"t2\" x=\"570\" y=\"62.0\" text-anchor=\"middle\" font-size=\"11\">Deployment -&gt; 3 pods</text><rect class=\"b\" x=\"470\" y=\"130\" width=\"200\" height=\"60\" rx=\"6\"/><text class=\"tb\" x=\"570\" y=\"156.7\" text-anchor=\"middle\" font-size=\"13\">4 scheduler</text><text class=\"t2\" x=\"570\" y=\"172.0\" text-anchor=\"middle\" font-size=\"11\">picks a node each</text><rect class=\"b\" x=\"240\" y=\"130\" width=\"200\" height=\"60\" rx=\"6\"/><text class=\"tb\" x=\"340\" y=\"156.7\" text-anchor=\"middle\" font-size=\"13\">5 kubelet</text><text class=\"t2\" x=\"340\" y=\"172.0\" text-anchor=\"middle\" font-size=\"11\">pulls image, starts</text><rect class=\"b ok\" x=\"10\" y=\"130\" width=\"200\" height=\"60\" rx=\"6\"/><text class=\"tb\" x=\"110\" y=\"156.7\" text-anchor=\"middle\" font-size=\"13\">6 Service</text><text class=\"t2\" x=\"110\" y=\"172.0\" text-anchor=\"middle\" font-size=\"11\">endpoints updated</text><path class=\"ln\" d=\"M212,50 L238,50\" marker-end=\"url(#k8s-apply--n)\"/><path class=\"ln\" d=\"M442,50 L468,50\" marker-end=\"url(#k8s-apply--n)\"/><path class=\"ln\" d=\"M570,82 L570,128\" marker-end=\"url(#k8s-apply--n)\"/><path class=\"ln\" d=\"M468,160 L442,160\" marker-end=\"url(#k8s-apply--n)\"/><path class=\"ln\" d=\"M238,160 L212,160\" marker-end=\"url(#k8s-apply--n)\"/></svg></div><figcaption>Six components, one shared source of truth. Each one watches the API server for work and writes its result back there.</figcaption></figure>\n\n<p><code>kubectl apply</code> sends the manifest to the <b>API server</b>, which checks it and saves it in <b>etcd</b>. The Deployment controller notices the new desired state and creates a ReplicaSet, which creates 3 pod objects. The <b>scheduler</b> sees pods with no node yet and assigns each one to a node with room. On those nodes the <b>kubelet</b> sees its new pods, tells the container runtime to pull the image and start the containers, and reports back. Finally the Service's endpoint list is updated so traffic reaches the new pods. Nothing talks to a node directly: every step goes through the API server.</p>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=s_o8dwzRlu4&amp;t=569s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Kubernetes Crash Course <span class=\"learn-sources-part\">· Main components: pod, service, ingress, configmap, secret, volume (9:29)</span></a><a href=\"https://www.youtube.com/watch?v=s_o8dwzRlu4&amp;t=1588s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Kubernetes Crash Course <span class=\"learn-sources-part\">· Configuration files (26:28)</span></a><a href=\"https://www.youtube.com/watch?v=s_o8dwzRlu4&amp;t=1959s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Kubernetes Crash Course <span class=\"learn-sources-part\">· minikube and kubectl (32:39)</span></a><a href=\"https://www.youtube.com/watch?v=s_o8dwzRlu4&amp;t=2477s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Kubernetes Crash Course <span class=\"learn-sources-part\">· Demo: web app with MongoDB (41:17)</span></a></div>","kubernetes/deployments-rollouts-scaling":"\n<p class=\"learn-lead\">A Deployment is how you run a stateless app on Kubernetes: it keeps the right number of pods alive, replaces them one by one when you ship a new version, and lets you roll back in one command. This chapter shows a production-shaped Deployment and everything you do with it after the first <code>kubectl apply</code>.</p>\n\n<h4>Deployment, ReplicaSet, Pod</h4>\n<p>A Deployment doesn't create pods itself. It creates a <b>ReplicaSet</b>, whose only job is \"keep exactly N pods matching this template running\". The pod names show the chain:</p>\n<figure class=\"learn-diagram dg\" data-dg=\"k8s-hierarchy\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 220\" role=\"img\" aria-label=\"A Deployment owns a ReplicaSet with three replicas, which owns three pods; the old ReplicaSet from the previous version is kept at zero for rollbacks\" style=\"--dgw:680px\"><defs><marker id=\"k8s-hierarchy--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker><marker id=\"k8s-hierarchy--ok\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk ok\" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"b hi\" x=\"250\" y=\"10\" width=\"180\" height=\"52\" rx=\"6\"/><text class=\"tb ta\" x=\"340\" y=\"32.7\" text-anchor=\"middle\" font-size=\"13\">Deployment: web</text><text class=\"t2\" x=\"340\" y=\"48.0\" text-anchor=\"middle\" font-size=\"11\">image: web:1.1</text><rect class=\"b ok\" x=\"150\" y=\"92\" width=\"200\" height=\"52\" rx=\"6\"/><text class=\"tb\" x=\"250\" y=\"114.3\" text-anchor=\"middle\" font-size=\"12\">ReplicaSet web-7d9f</text><text class=\"t2\" x=\"250\" y=\"129.5\" text-anchor=\"middle\" font-size=\"11\">replicas: 3</text><rect class=\"b mut\" x=\"400\" y=\"92\" width=\"200\" height=\"52\" rx=\"6\"/><text class=\"tb\" x=\"500\" y=\"114.8\" text-anchor=\"middle\" font-size=\"12\">ReplicaSet web-5c4b</text><text class=\"t2\" x=\"500\" y=\"129.2\" text-anchor=\"middle\" font-size=\"10\">replicas: 0 (web:1.0)</text><path class=\"ln\" d=\"M300,64 L300,90\" marker-end=\"url(#k8s-hierarchy--n)\"/><path class=\"ln  dash\" d=\"M380,64 L500,90\" marker-end=\"url(#k8s-hierarchy--n)\"/><text class=\"tl\" x=\"480\" y=\"74\" text-anchor=\"middle\" font-size=\"10\">kept for rollback</text><rect class=\"b ok\" x=\"40\" y=\"170\" width=\"120\" height=\"40\" rx=\"6\"/><text class=\"tb\" x=\"100\" y=\"194.2\" text-anchor=\"middle\" font-size=\"13\">pod 1</text><path class=\"ln ok\" d=\"M250,146 L100,168\" marker-end=\"url(#k8s-hierarchy--ok)\"/><rect class=\"b ok\" x=\"180\" y=\"170\" width=\"120\" height=\"40\" rx=\"6\"/><text class=\"tb\" x=\"240\" y=\"194.2\" text-anchor=\"middle\" font-size=\"13\">pod 2</text><path class=\"ln ok\" d=\"M250,146 L240,168\" marker-end=\"url(#k8s-hierarchy--ok)\"/><rect class=\"b ok\" x=\"320\" y=\"170\" width=\"120\" height=\"40\" rx=\"6\"/><text class=\"tb\" x=\"380\" y=\"194.2\" text-anchor=\"middle\" font-size=\"13\">pod 3</text><path class=\"ln ok\" d=\"M250,146 L380,168\" marker-end=\"url(#k8s-hierarchy--ok)\"/></svg></div><figcaption>You edit the Deployment. It makes a ReplicaSet per version, and each ReplicaSet keeps its pod count right. Rolling back just scales the old one up again.</figcaption></figure>\n\n<pre><code>$ kubectl get deploy,rs,pods -l app=web\ndeployment.apps/web              3/3\nreplicaset.apps/web-7c9d8f6b5    3         # deployment name + template hash\npod/web-7c9d8f6b5-x2kq9          Running   # replicaset name + random suffix</code></pre>\n<p>Every time you change the pod <b>template</b> (image, env vars, resources...), the Deployment creates a <i>new</i> ReplicaSet and shifts pods from the old one to the new one. Old ReplicaSets are kept, scaled to 0, which is what makes rollback possible. Changing only <code>replicas</code> doesn't start a rollout.</p>\n\n<h4>A production-shaped Deployment</h4>\n<pre><code>apiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: web\n  labels:\n    app: web\nspec:\n  replicas: 3\n  revisionHistoryLimit: 5            # old ReplicaSets kept for rollback (default 10)\n  selector:\n    matchLabels:\n      app: web                       # can't be changed after creation\n  strategy:\n    type: RollingUpdate\n    rollingUpdate:\n      maxSurge: 1                    # at most 1 extra pod during a rollout\n      maxUnavailable: 0              # never go below 3 ready pods\n  template:\n    metadata:\n      labels:\n        app: web\n    spec:\n      containers:\n        - name: web\n          image: demee/app:1.1\n          ports:\n            - containerPort: 3000\n          resources:\n            requests:                # what the scheduler reserves on a node\n              cpu: 100m              # 0.1 of a CPU core\n              memory: 128Mi\n            limits:                  # hard ceiling\n              cpu: 500m              # above this: throttled (slowed down)\n              memory: 256Mi          # above this: container is OOMKilled\n          startupProbe:              # allows up to 30 x 5s = 150s to start\n            httpGet:\n              path: /healthz\n              port: 3000\n            periodSeconds: 5\n            failureThreshold: 30\n          readinessProbe:            # ready to receive traffic?\n            httpGet:\n              path: /ready\n              port: 3000\n            periodSeconds: 5\n          livenessProbe:             # still alive, or stuck?\n            httpGet:\n              path: /healthz\n              port: 3000\n            periodSeconds: 10\n            failureThreshold: 3</code></pre>\n<p><b>Requests</b> are used for scheduling: a pod only goes to a node with that much unreserved CPU and memory. <b>Limits</b> are enforced while it runs. CPU is measured in cores or millicores (<code>500m</code> = half a core), memory in <code>Mi</code>/<code>Gi</code> (mebibytes/gibibytes).</p>\n\n<h4>Liveness vs readiness vs startup probes</h4>\n<div class=\"learn-table-wrap\"><table class=\"learn-table\"><thead><tr><th>Probe</th><th>Question it asks</th><th>When it fails</th></tr></thead><tbody>\n<tr><td><b>startup</b></td><td>Has the app finished starting?</td><td>The other two probes wait until it succeeds. If it never does, the container is restarted</td></tr>\n<tr><td><b>readiness</b></td><td>Can it handle requests right now?</td><td>The pod is taken out of the Service's endpoints (gets no traffic). <i>Not</i> restarted</td></tr>\n<tr><td><b>liveness</b></td><td>Is it alive, or hung?</td><td>The kubelet kills and restarts the container</td></tr>\n</tbody></table></div>\n<p>A probe can be <code>httpGet</code> (any 200-399 status passes), <code>tcpSocket</code>, <code>exec</code> (a command must exit 0) or <code>grpc</code>. Defaults if you don't set them: every 10 s, 1 s timeout, 3 failures in a row. Two classic mistakes: a liveness probe that checks the database (the database blips and every pod restarts at once), and a liveness probe with no startup probe on a slow-starting app (it gets killed before it's up, forever: CrashLoopBackOff).</p>\n\n<h4>Rolling updates</h4>\n<p>With <code>RollingUpdate</code>, Kubernetes starts new pods and removes old ones gradually, only moving on as new pods become <b>ready</b>. Two knobs control the pace:</p>\n<figure class=\"learn-diagram dg\" data-dg=\"k8s-rolling\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 250\" role=\"img\" aria-label=\"A rolling update with maxSurge 1 and maxUnavailable 0: one v2 pod starts, and only once it is ready is one v1 pod removed, until all three run v2\" style=\"--dgw:680px\"><text class=\"t2\" x=\"10\" y=\"37\" text-anchor=\"start\" font-size=\"11\">step 0</text><rect class=\"b\" x=\"80\" y=\"14\" width=\"76\" height=\"34\" rx=\"6\"/><text class=\"tb\" x=\"118\" y=\"34.8\" text-anchor=\"middle\" font-size=\"12\">v1</text><rect class=\"b\" x=\"166\" y=\"14\" width=\"76\" height=\"34\" rx=\"6\"/><text class=\"tb\" x=\"204\" y=\"34.8\" text-anchor=\"middle\" font-size=\"12\">v1</text><rect class=\"b\" x=\"252\" y=\"14\" width=\"76\" height=\"34\" rx=\"6\"/><text class=\"tb\" x=\"290\" y=\"34.8\" text-anchor=\"middle\" font-size=\"12\">v1</text><text class=\"t2\" x=\"440\" y=\"36\" text-anchor=\"start\" font-size=\"12\">3 pods of v1</text><text class=\"t2\" x=\"10\" y=\"83\" text-anchor=\"start\" font-size=\"11\">step 1</text><rect class=\"b\" x=\"80\" y=\"60\" width=\"76\" height=\"34\" rx=\"6\"/><text class=\"tb\" x=\"118\" y=\"80.8\" text-anchor=\"middle\" font-size=\"12\">v1</text><rect class=\"b\" x=\"166\" y=\"60\" width=\"76\" height=\"34\" rx=\"6\"/><text class=\"tb\" x=\"204\" y=\"80.8\" text-anchor=\"middle\" font-size=\"12\">v1</text><rect class=\"b\" x=\"252\" y=\"60\" width=\"76\" height=\"34\" rx=\"6\"/><text class=\"tb\" x=\"290\" y=\"80.8\" text-anchor=\"middle\" font-size=\"12\">v1</text><rect class=\"b warn\" x=\"338\" y=\"60\" width=\"76\" height=\"34\" rx=\"6\"/><text class=\"tb\" x=\"376\" y=\"74.3\" text-anchor=\"middle\" font-size=\"12\">v2</text><text class=\"t2\" x=\"376\" y=\"87.9\" text-anchor=\"middle\" font-size=\"9\">starting</text><text class=\"t2\" x=\"440\" y=\"82\" text-anchor=\"start\" font-size=\"12\">surge: a v2 pod starts</text><text class=\"t2\" x=\"10\" y=\"129\" text-anchor=\"start\" font-size=\"11\">step 2</text><rect class=\"b\" x=\"80\" y=\"106\" width=\"76\" height=\"34\" rx=\"6\"/><text class=\"tb\" x=\"118\" y=\"126.8\" text-anchor=\"middle\" font-size=\"12\">v1</text><rect class=\"b\" x=\"166\" y=\"106\" width=\"76\" height=\"34\" rx=\"6\"/><text class=\"tb\" x=\"204\" y=\"126.8\" text-anchor=\"middle\" font-size=\"12\">v1</text><rect class=\"b hi\" x=\"252\" y=\"106\" width=\"76\" height=\"34\" rx=\"6\"/><text class=\"tb ta\" x=\"290\" y=\"126.8\" text-anchor=\"middle\" font-size=\"12\">v2</text><rect class=\"b warn\" x=\"338\" y=\"106\" width=\"76\" height=\"34\" rx=\"6\"/><text class=\"tb\" x=\"376\" y=\"120.3\" text-anchor=\"middle\" font-size=\"12\">v2</text><text class=\"t2\" x=\"376\" y=\"133.9\" text-anchor=\"middle\" font-size=\"9\">starting</text><text class=\"t2\" x=\"440\" y=\"128\" text-anchor=\"start\" font-size=\"12\">v2 ready: one v1 removed</text><text class=\"t2\" x=\"10\" y=\"175\" text-anchor=\"start\" font-size=\"11\">step 3</text><rect class=\"b\" x=\"80\" y=\"152\" width=\"76\" height=\"34\" rx=\"6\"/><text class=\"tb\" x=\"118\" y=\"172.8\" text-anchor=\"middle\" font-size=\"12\">v1</text><rect class=\"b hi\" x=\"166\" y=\"152\" width=\"76\" height=\"34\" rx=\"6\"/><text class=\"tb ta\" x=\"204\" y=\"172.8\" text-anchor=\"middle\" font-size=\"12\">v2</text><rect class=\"b hi\" x=\"252\" y=\"152\" width=\"76\" height=\"34\" rx=\"6\"/><text class=\"tb ta\" x=\"290\" y=\"172.8\" text-anchor=\"middle\" font-size=\"12\">v2</text><rect class=\"b warn\" x=\"338\" y=\"152\" width=\"76\" height=\"34\" rx=\"6\"/><text class=\"tb\" x=\"376\" y=\"166.3\" text-anchor=\"middle\" font-size=\"12\">v2</text><text class=\"t2\" x=\"376\" y=\"179.9\" text-anchor=\"middle\" font-size=\"9\">starting</text><text class=\"t2\" x=\"440\" y=\"174\" text-anchor=\"start\" font-size=\"12\">and again</text><text class=\"t2\" x=\"10\" y=\"221\" text-anchor=\"start\" font-size=\"11\">step 4</text><rect class=\"b hi\" x=\"80\" y=\"198\" width=\"76\" height=\"34\" rx=\"6\"/><text class=\"tb ta\" x=\"118\" y=\"218.8\" text-anchor=\"middle\" font-size=\"12\">v2</text><rect class=\"b hi\" x=\"166\" y=\"198\" width=\"76\" height=\"34\" rx=\"6\"/><text class=\"tb ta\" x=\"204\" y=\"218.8\" text-anchor=\"middle\" font-size=\"12\">v2</text><rect class=\"b hi\" x=\"252\" y=\"198\" width=\"76\" height=\"34\" rx=\"6\"/><text class=\"tb ta\" x=\"290\" y=\"218.8\" text-anchor=\"middle\" font-size=\"12\">v2</text><text class=\"ok tb\" x=\"440\" y=\"220\" text-anchor=\"start\" font-size=\"12\">done: 3 pods of v2</text></svg></div><figcaption>There are always at least 3 ready pods, so users never notice. If a new pod never becomes ready, the rollout simply stops there.</figcaption></figure>\n\n<ul>\n<li><code>maxSurge</code>: how many pods <i>above</i> the desired count may exist during the rollout.</li>\n<li><code>maxUnavailable</code>: how many pods <i>below</i> the desired count may be unavailable.</li>\n</ul>\n<p>Both default to 25%; surge rounds up and unavailable rounds down, so with 3 replicas the default is also 1 and 0. The other strategy, <code>Recreate</code>, deletes all old pods before creating new ones: brief downtime, but useful when two versions must never run at the same time.</p>\n<pre><code>$ kubectl set image deployment/web web=demee/app:1.2    # or edit the YAML and apply\n$ kubectl rollout status deployment/web                 # waits and reports progress\n$ kubectl annotate deployment/web kubernetes.io/change-cause=\"bump to 1.2\"\n$ kubectl rollout history deployment/web                # revisions + change-cause\n$ kubectl rollout history deployment/web --revision=3   # what revision 3 contained\n$ kubectl rollout undo deployment/web                   # back to the previous revision\n$ kubectl rollout undo deployment/web --to-revision=2\n$ kubectl rollout restart deployment/web                # new pods, same spec</code></pre>\n<p>If new pods never become ready, the rollout simply stalls: with <code>maxUnavailable: 0</code> the old pods keep serving. After <code>progressDeadlineSeconds</code> (default 600) <code>rollout status</code> reports that the deployment exceeded its progress deadline. Kubernetes does <b>not</b> roll back by itself; that's your <code>rollout undo</code>. Note that an undo is recorded as a new revision number.</p>\n\n<h4>Scaling by hand</h4>\n<pre><code>$ kubectl scale deployment/web --replicas=5</code></pre>\n<p>Remember that the next <code>kubectl apply</code> of your YAML sets <code>replicas</code> back to whatever the file says.</p>\n\n<h4>Autoscaling with a HorizontalPodAutoscaler</h4>\n<p>An HPA changes <code>replicas</code> for you based on metrics:</p>\n<pre><code>apiVersion: autoscaling/v2\nkind: HorizontalPodAutoscaler\nmetadata:\n  name: web\nspec:\n  scaleTargetRef:\n    apiVersion: apps/v1\n    kind: Deployment\n    name: web\n  minReplicas: 3\n  maxReplicas: 10\n  metrics:\n    - type: Resource\n      resource:\n        name: cpu\n        target:\n          type: Utilization\n          averageUtilization: 70     # % of the pods' CPU *request*</code></pre>\n<p>It aims for <code>desired = ceil(current replicas &times; current usage / target)</code>: 3 pods averaging 140% against a 70% target becomes 6. Scaling up is quick; by default it waits 5 minutes of lower load before scaling down, to avoid flapping.</p>\n<ul>\n<li>Utilization is a percentage of <b>requests</b>, so the containers must have CPU requests set.</li>\n<li>It needs <b>metrics-server</b> installed. Test with <code>kubectl top pods</code>: if that errors, so will the HPA, and <code>kubectl get hpa</code> shows <code>&lt;unknown&gt;</code> in the TARGETS column. On minikube: <code>minikube addons enable metrics-server</code>; elsewhere apply the manifest from the metrics-server GitHub releases.</li>\n<li>When an HPA owns a Deployment, remove <code>replicas</code> from the Deployment YAML, or every apply will fight the autoscaler.</li>\n</ul>\n<pre><code>$ kubectl get hpa web --watch        # current vs target, replica count\n$ kubectl describe hpa web           # events explain every scaling decision</code></pre>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=s_o8dwzRlu4&amp;t=1186s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Kubernetes Crash Course <span class=\"learn-sources-part\">· Deployment and StatefulSet (19:46)</span></a></div>","kubernetes/services-ingress-networking":"\n<p class=\"learn-lead\">Pods come and go, and every new pod gets a new IP address. Services give a group of pods one stable name and address, Ingress brings outside HTTP traffic in by hostname and path, and NetworkPolicies decide who may talk to whom.</p>\n\n<h4>The pod network</h4>\n<p>Every pod gets its own IP, and every pod can reach every other pod directly, across nodes, without NAT. A <b>CNI plugin</b> (Calico, Cilium, Flannel and others) builds that network. Because pod IPs change whenever a pod is replaced, nothing should ever be hard-coded to one: you talk to a <b>Service</b> instead.</p>\n\n<h4>Service types</h4>\n<p><b>ClusterIP</b> (the default) gives a virtual IP reachable only inside the cluster. Right for anything internal: APIs, databases, caches.</p>\n<pre><code>apiVersion: v1\nkind: Service\nmetadata:\n  name: web\nspec:\n  type: ClusterIP\n  selector:\n    app: web                  # all ready pods with this label\n  ports:\n    - name: http\n      port: 80                # the Service's port\n      targetPort: 3000        # the container's port</code></pre>\n<p><b>NodePort</b> also opens the same port (range 30000-32767) on <i>every</i> node, so <code>http://&lt;any-node-ip&gt;:30080</code> reaches the pods. Fine for labs, rarely used directly in production.</p>\n<pre><code>apiVersion: v1\nkind: Service\nmetadata:\n  name: web-nodeport\nspec:\n  type: NodePort\n  selector:\n    app: web\n  ports:\n    - port: 80\n      targetPort: 3000\n      nodePort: 30080         # omit it and Kubernetes picks one</code></pre>\n<p><b>LoadBalancer</b> asks the cloud provider (EKS, GKE, AKS) for a real external load balancer with a public IP. Locally, <code>minikube tunnel</code> fills that role; on bare metal you need something like MetalLB, otherwise EXTERNAL-IP stays <code>&lt;pending&gt;</code>.</p>\n<pre><code>apiVersion: v1\nkind: Service\nmetadata:\n  name: web-public\nspec:\n  type: LoadBalancer\n  selector:\n    app: web\n  ports:\n    - port: 80\n      targetPort: 3000</code></pre>\n\n<h4>port, targetPort, nodePort</h4>\n<figure class=\"learn-diagram dg\" data-dg=\"k8s-ports\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 220\" role=\"img\" aria-label=\"Three ports: an outside client hits nodePort 30080 on any node, which leads to the Service port 80, which forwards to targetPort 8080 on the pod; other pods use web:80 directly\" style=\"--dgw:680px\"><defs><marker id=\"k8s-ports--hi\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk hi\" d=\"M0,0 L8,4 L0,8 z\"/></marker><marker id=\"k8s-ports--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"b\" x=\"10\" y=\"20\" width=\"150\" height=\"52\" rx=\"6\"/><text class=\"tb\" x=\"85\" y=\"43.2\" text-anchor=\"middle\" font-size=\"13\">outside client</text><text class=\"t2\" x=\"85\" y=\"57.7\" text-anchor=\"middle\" font-size=\"10\">curl node-ip:30080</text><rect class=\"b warn\" x=\"210\" y=\"20\" width=\"150\" height=\"52\" rx=\"6\"/><text class=\"tb\" x=\"285\" y=\"43.2\" text-anchor=\"middle\" font-size=\"13\">nodePort 30080</text><text class=\"t2\" x=\"285\" y=\"57.7\" text-anchor=\"middle\" font-size=\"10\">on every node</text><rect class=\"b hi\" x=\"410\" y=\"20\" width=\"120\" height=\"52\" rx=\"6\"/><text class=\"tb ta\" x=\"470\" y=\"43.2\" text-anchor=\"middle\" font-size=\"13\">port 80</text><text class=\"t2\" x=\"470\" y=\"57.7\" text-anchor=\"middle\" font-size=\"10\">Service web</text><rect class=\"b ok\" x=\"570\" y=\"20\" width=\"100\" height=\"52\" rx=\"6\"/><text class=\"tb tm\" x=\"620\" y=\"43.2\" text-anchor=\"middle\" font-size=\"13\">:8080</text><text class=\"t2\" x=\"620\" y=\"57.7\" text-anchor=\"middle\" font-size=\"10\">targetPort</text><rect class=\"b\" x=\"260\" y=\"130\" width=\"220\" height=\"52\" rx=\"6\"/><text class=\"tb\" x=\"370\" y=\"152.7\" text-anchor=\"middle\" font-size=\"13\">another pod</text><text class=\"t2\" x=\"370\" y=\"168.0\" text-anchor=\"middle\" font-size=\"11\">http://web:80</text><path class=\"ln\" d=\"M162,46 L208,46\" marker-end=\"url(#k8s-ports--n)\"/><path class=\"ln\" d=\"M362,46 L408,46\" marker-end=\"url(#k8s-ports--n)\"/><path class=\"ln\" d=\"M532,46 L568,46\" marker-end=\"url(#k8s-ports--n)\"/><path class=\"ln hi\" d=\"M482,156 L470,156 L470,74\" marker-end=\"url(#k8s-ports--hi)\"/><text class=\"ta\" x=\"520\" y=\"110\" text-anchor=\"middle\" font-size=\"10\">inside the cluster</text></svg></div><figcaption>Read it right to left: the app listens on <code>targetPort</code>, the Service exposes <code>port</code>, and <code>nodePort</code> exists only for traffic from outside.</figcaption></figure>\n\n<div class=\"learn-table-wrap\"><table class=\"learn-table\"><thead><tr><th>Field</th><th>Where it listens</th><th>Who uses it</th></tr></thead><tbody>\n<tr><td><code>port</code></td><td>On the Service's ClusterIP</td><td>Other pods: <code>http://web:80</code></td></tr>\n<tr><td><code>targetPort</code></td><td>On the pod (the <code>containerPort</code>); can also be a port <i>name</i></td><td>The Service forwards here. Defaults to <code>port</code></td></tr>\n<tr><td><code>nodePort</code></td><td>On every node's IP (30000-32767)</td><td>Clients outside the cluster (NodePort/LoadBalancer only)</td></tr>\n</tbody></table></div>\n\n<h4>Selectors and endpoints</h4>\n<p>A Service finds its pods purely by <b>label selector</b>, and only pods that pass their readiness probe receive traffic. The list of current pod IPs is kept in <b>EndpointSlices</b>:</p>\n<pre><code>$ kubectl describe svc web                       # \"Endpoints:\" line\n$ kubectl get endpointslices -l kubernetes.io/service-name=web\n$ kubectl get pods -l app=web --show-labels      # do the labels really match?</code></pre>\n<p>A Service with no endpoints is the number one reason for \"connection refused\": either the selector doesn't match the pod labels (a typo, <code>app: Web</code> vs <code>app: web</code>) or no pod is ready.</p>\n\n<h4>Cluster DNS</h4>\n<p>CoreDNS gives every Service a DNS name of the form <code>&lt;service&gt;.&lt;namespace&gt;.svc.cluster.local</code> (<code>cluster.local</code> is the default cluster domain):</p>\n<ul>\n<li>from the same namespace: <code>web</code></li>\n<li>from another namespace: <code>web.shop</code></li>\n<li>fully qualified: <code>web.shop.svc.cluster.local</code></li>\n</ul>\n<pre><code>$ kubectl run tmp --rm -it --image=busybox:1.36 --restart=Never -- \\\n    nslookup web.shop.svc.cluster.local\n$ kubectl run tmp --rm -it --image=busybox:1.36 --restart=Never -- \\\n    wget -qO- http://web.shop</code></pre>\n<p>A ClusterIP is virtual (it's implemented by kube-proxy's forwarding rules), so it usually doesn't answer <code>ping</code>. Test with a real request instead. A <b>headless</b> Service (<code>clusterIP: None</code>) has no virtual IP at all: its DNS name returns the pod IPs directly, which is what StatefulSets use.</p>\n\n<h4>Ingress: HTTP routing from outside</h4>\n<p>Instead of one LoadBalancer per Service, an <b>Ingress</b> routes many hostnames and paths through one entry point. The Ingress object is only a set of rules: an <b>ingress controller</b> (Traefik, HAProxy, F5 NGINX, your cloud's controller...) must be installed to actually carry them out. Without one, the Ingress just sits there with no address.</p>\n<figure class=\"learn-diagram dg\" data-dg=\"k8s-ingress\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 240\" role=\"img\" aria-label=\"Users reach one ingress controller, which routes / to the web Service and /api to the api Service, each with its own pods\" style=\"--dgw:680px\"><defs><marker id=\"k8s-ingress--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker><marker id=\"k8s-ingress--ok\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk ok\" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"b\" x=\"10\" y=\"90\" width=\"120\" height=\"56\" rx=\"6\"/><text class=\"tb\" x=\"70\" y=\"114.7\" text-anchor=\"middle\" font-size=\"13\">users</text><text class=\"t2\" x=\"70\" y=\"130.0\" text-anchor=\"middle\" font-size=\"11\">the internet</text><rect class=\"b hi\" x=\"170\" y=\"80\" width=\"170\" height=\"76\" rx=\"6\"/><text class=\"tb ta\" x=\"255\" y=\"107.8\" text-anchor=\"middle\" font-size=\"12\">ingress controller</text><text class=\"t2\" x=\"255\" y=\"122.2\" text-anchor=\"middle\" font-size=\"10\">shop.example.com</text><text class=\"t2\" x=\"255\" y=\"136.2\" text-anchor=\"middle\" font-size=\"10\">TLS ends here</text><rect class=\"b\" x=\"400\" y=\"30\" width=\"130\" height=\"52\" rx=\"6\"/><text class=\"tb\" x=\"465\" y=\"53.2\" text-anchor=\"middle\" font-size=\"13\">svc: web</text><text class=\"t2\" x=\"465\" y=\"67.7\" text-anchor=\"middle\" font-size=\"10\">path /</text><rect class=\"b\" x=\"400\" y=\"150\" width=\"130\" height=\"52\" rx=\"6\"/><text class=\"tb\" x=\"465\" y=\"173.2\" text-anchor=\"middle\" font-size=\"13\">svc: api</text><text class=\"t2\" x=\"465\" y=\"187.7\" text-anchor=\"middle\" font-size=\"10\">path /api</text><rect class=\"b ok\" x=\"570\" y=\"20\" width=\"100\" height=\"30\" rx=\"6\"/><text class=\"tb\" x=\"620\" y=\"38.5\" text-anchor=\"middle\" font-size=\"11\">web pod</text><rect class=\"b ok\" x=\"570\" y=\"140\" width=\"100\" height=\"30\" rx=\"6\"/><text class=\"tb\" x=\"620\" y=\"158.5\" text-anchor=\"middle\" font-size=\"11\">api pod</text><rect class=\"b ok\" x=\"570\" y=\"56\" width=\"100\" height=\"30\" rx=\"6\"/><text class=\"tb\" x=\"620\" y=\"74.5\" text-anchor=\"middle\" font-size=\"11\">web pod</text><rect class=\"b ok\" x=\"570\" y=\"176\" width=\"100\" height=\"30\" rx=\"6\"/><text class=\"tb\" x=\"620\" y=\"194.5\" text-anchor=\"middle\" font-size=\"11\">api pod</text><path class=\"ln\" d=\"M132,118 L168,118\" marker-end=\"url(#k8s-ingress--n)\"/><path class=\"ln\" d=\"M342,104 L398,56\" marker-end=\"url(#k8s-ingress--n)\"/><text class=\"tl\" x=\"370\" y=\"70\" text-anchor=\"middle\" font-size=\"11\">/</text><path class=\"ln\" d=\"M342,132 L398,176\" marker-end=\"url(#k8s-ingress--n)\"/><text class=\"tl\" x=\"362\" y=\"172\" text-anchor=\"middle\" font-size=\"11\">/api</text><path class=\"ln ok\" d=\"M532,56 L568,40\" marker-end=\"url(#k8s-ingress--ok)\"/><path class=\"ln ok\" d=\"M532,56 L568,70\" marker-end=\"url(#k8s-ingress--ok)\"/><path class=\"ln ok\" d=\"M532,176 L568,160\" marker-end=\"url(#k8s-ingress--ok)\"/><path class=\"ln ok\" d=\"M532,176 L568,190\" marker-end=\"url(#k8s-ingress--ok)\"/></svg></div><figcaption>One entry point, many apps. The Ingress object only holds the rules; the controller is the program that actually receives the traffic.</figcaption></figure>\n\n<pre><code>apiVersion: networking.k8s.io/v1\nkind: Ingress\nmetadata:\n  name: shop\nspec:\n  ingressClassName: traefik          # must match: kubectl get ingressclass\n  tls:\n    - hosts:\n        - shop.example.com\n      secretName: shop-tls           # a kubernetes.io/tls Secret\n  rules:\n    - host: shop.example.com\n      http:\n        paths:\n          - path: /api\n            pathType: Prefix         # /api and /api/..., not /apix\n            backend:\n              service:\n                name: api\n                port:\n                  number: 80\n          - path: /\n            pathType: Prefix\n            backend:\n              service:\n                name: web\n                port:\n                  number: 80</code></pre>\n<pre><code>$ kubectl create secret tls shop-tls --cert=tls.crt --key=tls.key\n$ kubectl get ingress shop                  # ADDRESS column = controller's IP\n$ curl -H \"Host: shop.example.com\" http://&lt;address&gt;/api/health   # test before DNS exists</code></pre>\n<p>The longest matching path wins, so <code>/api/health</code> goes to <code>api</code> and everything else to <code>web</code>. <code>pathType</code> can be <code>Prefix</code>, <code>Exact</code> or <code>ImplementationSpecific</code>.</p>\n<div class=\"learn-callout\">The widely used community controller <b>ingress-nginx</b> was retired by the Kubernetes project in March 2026: no more releases or security fixes. Existing installs keep working, but new clusters should choose another controller. The newer <b>Gateway API</b> is the long-term successor to Ingress and is worth learning next.</div>\n\n<h4>kubectl port-forward</h4>\n<p>For quick access from your laptop without exposing anything:</p>\n<pre><code>$ kubectl port-forward svc/web 8080:80         # localhost:8080 -&gt; Service port 80\n$ kubectl port-forward pod/web-7c9d8f6b5-x2kq9 9229:9229   # e.g. a debugger port</code></pre>\n<p>It connects to a <i>single</i> pod behind the Service (no load balancing) and stops when you press Ctrl+C. Great for debugging, never for real traffic.</p>\n\n<h4>NetworkPolicy: a firewall for pods</h4>\n<p>By default any pod can reach any other pod. A NetworkPolicy restricts that. Once a pod is selected by a policy for <code>Ingress</code>, everything not explicitly allowed is denied. This lets only the web pods reach the database:</p>\n<pre><code>apiVersion: networking.k8s.io/v1\nkind: NetworkPolicy\nmetadata:\n  name: db-allow-web\nspec:\n  podSelector:\n    matchLabels:\n      app: db                  # the pods being protected\n  policyTypes:\n    - Ingress\n  ingress:\n    - from:\n        - podSelector:\n            matchLabels:\n              app: web\n      ports:\n        - protocol: TCP\n          port: 5432</code></pre>\n<p>Policies are enforced by the CNI plugin. Calico and Cilium do; plain Flannel doesn't, and there the policy is silently ignored.</p>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=s_o8dwzRlu4&amp;t=739s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Kubernetes Crash Course <span class=\"learn-sources-part\">· Service and Ingress (12:19)</span></a></div>","kubernetes/config-secrets-storage-debugging":"\n<p class=\"learn-lead\">The same image should run in every environment, with settings, passwords and data supplied from outside. This chapter covers ConfigMaps, Secrets and persistent storage, then the four pod errors you'll meet most often and the exact commands that explain each one.</p>\n\n<h4>ConfigMaps</h4>\n<p>A ConfigMap holds non-secret settings as key-value pairs. Create it from the command line or from YAML:</p>\n<pre><code>$ kubectl create configmap web-config \\\n    --from-literal=LOG_LEVEL=info \\\n    --from-file=app.yaml               # key = file name, value = file contents\n$ kubectl create configmap web-env --from-env-file=web.env   # KEY=value lines\n$ kubectl get configmap web-config -o yaml</code></pre>\n<pre><code>apiVersion: v1\nkind: ConfigMap\nmetadata:\n  name: web-config\ndata:\n  LOG_LEVEL: info\n  app.yaml: |\n    port: 3000\n    cache: true</code></pre>\n\n<h4>Secrets</h4>\n<pre><code>$ kubectl create secret generic db-cred \\\n    --from-literal=username=app \\\n    --from-literal=password='S3cr3t!'\n$ kubectl get secret db-cred -o jsonpath='{.data.password}'\nUzNjcjN0IQ==\n$ echo 'UzNjcjN0IQ==' | base64 -d\nS3cr3t!</code></pre>\n<p>That's the important lesson: Secret values are only <b>base64-encoded, not encrypted</b>. Anyone allowed to read Secrets in the namespace can decode them in one command. In YAML, <code>data:</code> expects base64 (<code>echo -n 'S3cr3t!' | base64</code>, where <code>-n</code> avoids encoding a newline) and <code>stringData:</code> takes plain text. To actually protect them: restrict access with RBAC, enable encryption at rest for etcd (off by default in a self-managed cluster), and never commit Secret YAML to git; use Sealed Secrets, SOPS or the External Secrets Operator instead.</p>\n\n<h4>Using them in a pod</h4>\n<pre><code>apiVersion: v1\nkind: Pod\nmetadata:\n  name: web\nspec:\n  containers:\n    - name: web\n      image: demee/app:1.1\n      env:\n        - name: LOG_LEVEL\n          valueFrom:\n            configMapKeyRef:\n              name: web-config\n              key: LOG_LEVEL\n        - name: DB_PASSWORD\n          valueFrom:\n            secretKeyRef:\n              name: db-cred\n              key: password\n      volumeMounts:\n        - name: config\n          mountPath: /etc/web          # file appears as /etc/web/app.yaml\n          readOnly: true\n  volumes:\n    - name: config\n      configMap:\n        name: web-config\n        items:\n          - key: app.yaml\n            path: app.yaml</code></pre>\n<p><code>envFrom</code> with a <code>configMapRef</code> or <code>secretRef</code> imports every key at once. Secrets can be mounted as files too (<code>secret: {secretName: db-cred}</code>). One behaviour to remember: <b>environment variables are read once, at container start</b>. Edit the ConfigMap and running pods keep the old values until <code>kubectl rollout restart deployment/web</code>. Mounted files do update in place after a short delay (except when mounted with <code>subPath</code>).</p>\n\n<h4>Persistent storage: PVC and StorageClass</h4>\n<p>A pod's filesystem is lost when the pod is replaced. For data that must survive, the pod uses a <b>PersistentVolumeClaim</b> (PVC): a request for storage. A <b>StorageClass</b> describes a kind of storage (a cloud SSD, a local path) and creates a matching <b>PersistentVolume</b> (PV) automatically when a claim appears.</p>\n<figure class=\"learn-diagram dg\" data-dg=\"k8s-storage\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 200\" role=\"img\" aria-label=\"A pod mounts a PersistentVolumeClaim asking for 5Gi; it is bound to a PersistentVolume that the StorageClass created on a real cloud disk\" style=\"--dgw:680px\"><defs><marker id=\"k8s-storage--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker><marker id=\"k8s-storage--warn\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk warn\" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"b ok\" x=\"10\" y=\"60\" width=\"130\" height=\"60\" rx=\"6\"/><text class=\"tb\" x=\"75\" y=\"87.2\" text-anchor=\"middle\" font-size=\"13\">pod</text><text class=\"t2\" x=\"75\" y=\"101.7\" text-anchor=\"middle\" font-size=\"10\">mounts /uploads</text><rect class=\"b hi\" x=\"190\" y=\"60\" width=\"140\" height=\"60\" rx=\"6\"/><text class=\"tb ta\" x=\"260\" y=\"87.2\" text-anchor=\"middle\" font-size=\"13\">PVC: uploads</text><text class=\"t2\" x=\"260\" y=\"101.7\" text-anchor=\"middle\" font-size=\"10\">asks for 5Gi</text><rect class=\"b\" x=\"380\" y=\"60\" width=\"120\" height=\"60\" rx=\"6\"/><text class=\"tb\" x=\"440\" y=\"87.2\" text-anchor=\"middle\" font-size=\"13\">PV</text><text class=\"t2\" x=\"440\" y=\"101.7\" text-anchor=\"middle\" font-size=\"10\">the volume</text><rect class=\"b warn\" x=\"380\" y=\"150\" width=\"120\" height=\"44\" rx=\"6\"/><text class=\"tb\" x=\"440\" y=\"175.8\" text-anchor=\"middle\" font-size=\"12\">StorageClass</text><rect class=\"b\" x=\"550\" y=\"60\" width=\"120\" height=\"60\" rx=\"6\"/><text class=\"tb\" x=\"610\" y=\"87.2\" text-anchor=\"middle\" font-size=\"13\">real disk</text><text class=\"t2\" x=\"610\" y=\"101.7\" text-anchor=\"middle\" font-size=\"10\">cloud SSD</text><path class=\"ln\" d=\"M142,90 L188,90\" marker-end=\"url(#k8s-storage--n)\"/><text class=\"tl\" x=\"165\" y=\"83\" text-anchor=\"middle\" font-size=\"11\">uses</text><path class=\"ln\" d=\"M332,90 L378,90\" marker-end=\"url(#k8s-storage--n)\"/><text class=\"tl\" x=\"355\" y=\"83\" text-anchor=\"middle\" font-size=\"11\">bound</text><path class=\"ln\" d=\"M502,90 L548,90\" marker-end=\"url(#k8s-storage--n)\"/><path class=\"ln warn\" d=\"M440,148 L440,122\" marker-end=\"url(#k8s-storage--warn)\"/><text class=\"warn\" x=\"520\" y=\"180\" text-anchor=\"start\" font-size=\"11\">creates it on demand</text><text class=\"t2\" x=\"260\" y=\"22\" text-anchor=\"middle\" font-size=\"12\">the pod can be replaced; the claim and the data stay</text></svg></div><figcaption>The pod only knows its claim. The StorageClass turns that claim into a real disk, so the data outlives any single pod.</figcaption></figure>\n\n<pre><code>apiVersion: v1\nkind: PersistentVolumeClaim\nmetadata:\n  name: uploads\nspec:\n  accessModes:\n    - ReadWriteOnce            # mountable by one node at a time\n  storageClassName: standard   # omit to use the cluster's default class\n  resources:\n    requests:\n      storage: 5Gi</code></pre>\n<pre><code>$ kubectl get storageclass     # the default one is marked \"(default)\"\n$ kubectl get pvc              # STATUS should become Bound</code></pre>\n<p>In the pod spec: <code>volumes: [{name: uploads, persistentVolumeClaim: {claimName: uploads}}]</code> plus a <code>volumeMounts</code> entry. Worth knowing:</p>\n<ul>\n<li><b>Access modes</b>: <code>ReadWriteOnce</code> is what most block storage supports; <code>ReadWriteMany</code> (many nodes at once) needs shared storage such as NFS or a cloud file service. A 3-replica Deployment sharing one RWO claim fails once pods land on different nodes.</li>\n<li>Many classes use <code>WaitForFirstConsumer</code>: the PVC stays <code>Pending</code> until a pod uses it. That's normal.</li>\n<li>Dynamically created volumes usually have reclaim policy <code>Delete</code>: <b>delete the PVC and the disk and its data are gone</b>.</li>\n</ul>\n\n<h4>StatefulSets, briefly</h4>\n<p>Databases need more than a Deployment gives them. A <b>StatefulSet</b> gives each pod a stable name (<code>db-0</code>, <code>db-1</code>), starts them in order, and through <code>volumeClaimTemplates</code> gives each pod its own PVC that follows it when it's rescheduled. It needs a headless Service named in <code>serviceName</code>, which gives each pod a DNS name like <code>db-0.db</code>.</p>\n<pre><code>apiVersion: apps/v1\nkind: StatefulSet\nmetadata:\n  name: db\nspec:\n  serviceName: db\n  replicas: 1\n  selector:\n    matchLabels:\n      app: db\n  template:\n    metadata:\n      labels:\n        app: db\n    spec:\n      containers:\n        - name: postgres\n          image: postgres:16\n          env:\n            - name: POSTGRES_PASSWORD\n              valueFrom:\n                secretKeyRef:\n                  name: db-cred\n                  key: password\n            - name: PGDATA             # subfolder: some disks have lost+found at the root\n              value: /var/lib/postgresql/data/pgdata\n          volumeMounts:\n            - name: data\n              mountPath: /var/lib/postgresql/data\n  volumeClaimTemplates:\n    - metadata:\n        name: data\n      spec:\n        accessModes: [\"ReadWriteOnce\"]\n        resources:\n          requests:\n            storage: 10Gi</code></pre>\n<p>Deleting or scaling down a StatefulSet leaves its PVCs behind by default, so the data isn't lost by accident.</p>\n\n<h4>Debugging: the three commands</h4>\n<pre><code>$ kubectl get pods                               # STATUS and RESTARTS\n$ kubectl describe pod web-7c9d8f6b5-x2kq9       # config, Last State, and Events at the bottom\n$ kubectl logs web-7c9d8f6b5-x2kq9 --previous    # output of the crashed container\n$ kubectl get events --sort-by=.metadata.creationTimestamp   # everything, in order</code></pre>\n<p>Plain <code>kubectl logs</code> shows the <i>current</i> container, which may have just restarted and printed nothing useful yet. <code>--previous</code> shows the one that died.</p>\n\n<div class=\"learn-table-wrap\"><table class=\"learn-table\"><thead><tr><th>Status</th><th>What it means</th><th>Where to look</th><th>Typical fix</th></tr></thead><tbody>\n<tr><td><b>Pending</b></td><td>The scheduler can't place the pod on any node</td><td><code>describe pod</code> events: <code>0/3 nodes are available: 3 Insufficient cpu</code>, or <code>unbound immediate PersistentVolumeClaims</code></td><td>Lower requests, add nodes, fix the PVC or the nodeSelector/taints</td></tr>\n<tr><td><b>ImagePullBackOff</b> / <b>ErrImagePull</b></td><td>The node can't download the image</td><td><code>describe pod</code> events: <code>not found</code>, <code>pull access denied</code>, <code>401 Unauthorized</code></td><td>Fix the name/tag; for private registries add <code>imagePullSecrets</code></td></tr>\n<tr><td><b>CrashLoopBackOff</b></td><td>The container keeps starting and exiting; restarts wait longer each time (up to 5 minutes)</td><td><code>logs --previous</code>; <code>describe</code> shows <code>Last State: Terminated</code> with its exit code</td><td>Fix the app error, missing config, or a too-strict liveness probe</td></tr>\n<tr><td><b>OOMKilled</b></td><td>The container used more memory than its limit</td><td><code>describe pod</code>: <code>Reason: OOMKilled</code>, <code>Exit Code: 137</code>; <code>kubectl top pod</code></td><td>Raise <code>limits.memory</code> or fix the leak</td></tr>\n<tr><td><b>CreateContainerConfigError</b></td><td>A referenced ConfigMap or Secret (or key) doesn't exist</td><td><code>describe pod</code>: e.g. <code>secret \"db-cred\" not found</code></td><td>Create it in the <i>same namespace</i>, check the key name</td></tr>\n</tbody></table></div>\n\n<p>An OOMKilled container often shows as <code>CrashLoopBackOff</code> in <code>kubectl get pods</code>; the real reason is in <code>Last State</code>:</p>\n<pre><code>$ kubectl describe pod web-7c9d8f6b5-x2kq9\n    State:          Waiting\n      Reason:       CrashLoopBackOff\n    Last State:     Terminated\n      Reason:       OOMKilled\n      Exit Code:    137</code></pre>\n<p>For a private registry, create the pull secret once and reference it from the pod spec:</p>\n<pre><code>$ kubectl create secret docker-registry regcred \\\n    --docker-server=ghcr.io --docker-username=demee --docker-password=&lt;token&gt;\n# in the pod spec:\n#   imagePullSecrets:\n#     - name: regcred</code></pre>\n<p>And when the image has no shell for <code>kubectl exec</code>, attach a temporary debug container that shares the app container's processes:</p>\n<pre><code>$ kubectl debug -it web-7c9d8f6b5-x2kq9 --image=busybox:1.36 --target=web</code></pre>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=s_o8dwzRlu4&amp;t=871s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Kubernetes Crash Course <span class=\"learn-sources-part\">· ConfigMap and Secret (14:31)</span></a><a href=\"https://www.youtube.com/watch?v=s_o8dwzRlu4&amp;t=1072s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Kubernetes Crash Course <span class=\"learn-sources-part\">· Volume (17:52)</span></a><a href=\"https://www.youtube.com/watch?v=s_o8dwzRlu4&amp;t=1186s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Kubernetes Crash Course <span class=\"learn-sources-part\">· Deployment and StatefulSet (19:46)</span></a></div>","kubernetes/your-first-cluster-hands-on":"\n<p class=\"learn-lead\">Reading about Pods and Services only goes so far. In this chapter you build a real Kubernetes cluster on your own laptop, deploy an app to it, reach it, scale it, update it, break it on purpose and clean up. Everything runs inside Docker, so it costs nothing and leaves nothing behind.</p>\n\n<h4>kind or minikube?</h4>\n<p>Both give you a working cluster on one machine. <b>kind</b> (\"Kubernetes in Docker\") runs each Kubernetes node as a Docker container: it starts in under a minute, is very light, and is what many CI pipelines use to test against a real cluster. <b>minikube</b> runs a single node in a container or VM and comes with handy add-ons (dashboard, ingress, metrics-server). Either is fine for learning; this chapter uses kind, and the minikube equivalents are at the end. You need Docker running (Linux chapter 11 sets it up).</p>\n\n<h4>Install kubectl and kind</h4>\n<p>On a Mac, <code>brew install kubectl kind</code> does both. On Linux or WSL (Intel/AMD machines), download the binaries:</p>\n<pre><code># kubectl: the client you'll use for every cluster, local or cloud\n$ curl -LO \"https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl\"\n$ sudo install -m 0755 kubectl /usr/local/bin/kubectl\n\n# kind: check kind.sigs.k8s.io for the newest version number\n$ KIND_VERSION=v0.24.0\n$ curl -Lo ./kind https://kind.sigs.k8s.io/dl/${KIND_VERSION}/kind-linux-amd64\n$ chmod +x ./kind &amp;&amp; sudo mv ./kind /usr/local/bin/kind\n\n$ kubectl version --client\n$ kind version</code></pre>\n\n<h4>Create the cluster</h4>\n<pre><code>$ kind create cluster --name dev\nCreating cluster \"dev\" ...\n ✓ Ensuring node image\n ✓ Preparing nodes\n ✓ Starting control-plane\nSet kubectl context to \"kind-dev\"\n\n$ kubectl get nodes\nNAME                STATUS   ROLES           AGE   VERSION\ndev-control-plane   Ready    control-plane   45s   v1.31.0    # yours may be newer</code></pre>\n<p>kind also wrote the connection details into <code>~/.kube/config</code>, the <b>kubeconfig</b> file every kubectl command reads. That's why kubectl \"just knows\" where the cluster is.</p>\n\n<h4>Contexts and namespaces</h4>\n<p>A <b>context</b> in the kubeconfig is a saved combination of a cluster, a user and a default namespace. When you also work with a cloud cluster, switching context is how you choose which cluster a command hits, so always check before running anything destructive.</p>\n<pre><code>$ kubectl config get-contexts        # all saved contexts, * marks the current one\n$ kubectl config current-context\nkind-dev\n$ kubectl config use-context kind-dev</code></pre>\n<p>A <b>namespace</b> is a folder inside a cluster. It groups related objects, lets two teams use the same names without clashing, and is the unit that access rules and resource quotas apply to. Every cluster starts with <code>default</code>, <code>kube-system</code> (Kubernetes' own parts) and a few others.</p>\n<pre><code>$ kubectl create namespace shop\n$ kubectl config set-context --current --namespace=shop   # make it the default\n$ kubectl get pods -A                                     # -A: every namespace</code></pre>\n\n<h4>Deploy an app</h4>\n<p>Save this as <code>web.yaml</code>. It's a Deployment that keeps two copies of nginx running, and a Service that gives them one stable address:</p>\n<pre><code>apiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: web\n  namespace: shop\nspec:\n  replicas: 2\n  selector:\n    matchLabels: {app: web}\n  template:\n    metadata:\n      labels: {app: web}\n    spec:\n      containers:\n        - name: web\n          image: nginx:1.27\n          ports:\n            - containerPort: 80\n          resources:\n            requests: {cpu: 50m, memory: 32Mi}\n            limits: {memory: 128Mi}\n---\napiVersion: v1\nkind: Service\nmetadata:\n  name: web\n  namespace: shop\nspec:\n  selector: {app: web}\n  ports:\n    - port: 80\n      targetPort: 80</code></pre>\n<pre><code>$ kubectl apply -f web.yaml\ndeployment.apps/web created\nservice/web created\n$ kubectl rollout status deployment/web\ndeployment \"web\" successfully rolled out\n$ kubectl get deploy,rs,pods -o wide</code></pre>\n\n<h4>Reach it</h4>\n<p>The Service is type <code>ClusterIP</code>, so it's only reachable from inside the cluster. For testing from your laptop, <b>port-forward</b> opens a tunnel through kubectl:</p>\n<figure class=\"learn-diagram dg\" data-dg=\"k8s-port-forward\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 220\" role=\"img\" aria-label=\"On your laptop, curl to localhost:8080 goes through kubectl port-forward, which tunnels into the kind cluster to the web Service and on to an nginx pod\" style=\"--dgw:680px\"><defs><marker id=\"k8s-port-forward--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"g\" x=\"10\" y=\"10\" width=\"660\" height=\"200\" rx=\"8\"/><text class=\"tg \" x=\"20\" y=\"26\" font-size=\"11\">your laptop</text><rect class=\"b warn\" x=\"26\" y=\"50\" width=\"170\" height=\"56\" rx=\"6\"/><text class=\"tb tm\" x=\"111\" y=\"74.7\" text-anchor=\"middle\" font-size=\"13\">curl</text><text class=\"t2\" x=\"111\" y=\"90.0\" text-anchor=\"middle\" font-size=\"11\">localhost:8080</text><rect class=\"b\" x=\"26\" y=\"130\" width=\"170\" height=\"56\" rx=\"6\"/><text class=\"tb tm\" x=\"111\" y=\"154.7\" text-anchor=\"middle\" font-size=\"13\">kubectl</text><text class=\"t2\" x=\"111\" y=\"170.0\" text-anchor=\"middle\" font-size=\"11\">port-forward</text><rect class=\"g hi\" x=\"250\" y=\"40\" width=\"404\" height=\"156\" rx=\"8\"/><text class=\"tg hi\" x=\"260\" y=\"56\" font-size=\"11\">kind cluster (a Docker container)</text><rect class=\"b hi\" x=\"270\" y=\"90\" width=\"150\" height=\"56\" rx=\"6\"/><text class=\"tb ta tm\" x=\"345\" y=\"115.2\" text-anchor=\"middle\" font-size=\"13\">svc/web</text><text class=\"t2\" x=\"345\" y=\"129.7\" text-anchor=\"middle\" font-size=\"10\">:80  ClusterIP</text><rect class=\"b ok\" x=\"480\" y=\"90\" width=\"150\" height=\"56\" rx=\"6\"/><text class=\"tb\" x=\"555\" y=\"115.2\" text-anchor=\"middle\" font-size=\"13\">pod: nginx</text><text class=\"t2\" x=\"555\" y=\"129.7\" text-anchor=\"middle\" font-size=\"10\">:80</text><path class=\"ln\" d=\"M111,108 L111,128\" marker-end=\"url(#k8s-port-forward--n)\"/><path class=\"ln\" d=\"M198,158 L268,128\" marker-end=\"url(#k8s-port-forward--n)\"/><text class=\"tl\" x=\"226\" y=\"132\" text-anchor=\"middle\" font-size=\"11\">tunnel</text><path class=\"ln\" d=\"M422,118 L478,118\" marker-end=\"url(#k8s-port-forward--n)\"/></svg></div><figcaption>A ClusterIP Service is invisible from outside the cluster. Port-forward borrows kubectl's connection to reach it, for you only, while the command runs.</figcaption></figure>\n\n<pre><code>$ kubectl port-forward svc/web 8080:80\nForwarding from 127.0.0.1:8080 -&gt; 80\n# in a second terminal:\n$ curl -I localhost:8080\nHTTP/1.1 200 OK\nServer: nginx/1.27.x</code></pre>\n<p>Port-forward is for you, not for users. Real traffic comes in through an Ingress or a LoadBalancer Service (Kubernetes chapter 4).</p>\n\n<h4>Scale, update, roll back</h4>\n<pre><code>$ kubectl scale deployment/web --replicas=4\n$ kubectl set image deployment/web web=nginx:1.27-alpine   # container name = new image\n$ kubectl rollout status deployment/web                    # watch pods being replaced one by one\n$ kubectl rollout history deployment/web\n$ kubectl rollout undo deployment/web                      # back to the previous version</code></pre>\n<p>In real projects you'd change the image in <code>web.yaml</code> and <code>kubectl apply</code> it again, so the file in Git always matches what's running. The commands above are just the quickest way to see it happen.</p>\n\n<h4>Break it on purpose</h4>\n<p>Point the Deployment at an image that doesn't exist and watch how Kubernetes reports it:</p>\n<pre><code>$ kubectl set image deployment/web web=nginx:does-not-exist\n$ kubectl get pods\nweb-7c9d...   0/1   ImagePullBackOff   0   30s\n$ kubectl describe pod web-7c9d...      # read the Events at the bottom\n  Failed to pull image \"nginx:does-not-exist\": ... not found\n$ kubectl rollout undo deployment/web   # fix it</code></pre>\n<p>Notice the old pods kept serving while the broken ones failed: a rolling update only removes old pods when new ones become ready. Now delete a pod by hand with <code>kubectl delete pod &lt;name&gt;</code> and run <code>kubectl get pods</code> again. A new one appears within seconds, because the ReplicaSet always works back to the number you asked for.</p>\n\n<h4>Run your own image</h4>\n<p>The cluster's nodes are containers, so they can't see images you've only built on your laptop. Load them in first:</p>\n<pre><code>$ docker build -t myapp:dev .\n$ kind load docker-image myapp:dev --name dev\n# then use image: myapp:dev in the Deployment</code></pre>\n<p>Use a real tag like <code>dev</code>, not <code>latest</code>: with <code>latest</code>, Kubernetes always tries to pull from a registry and fails with ImagePullBackOff.</p>\n\n<h4>Clean up</h4>\n<pre><code>$ kubectl delete namespace shop     # deletes everything inside it\n$ kind delete cluster --name dev    # removes the whole cluster</code></pre>\n\n<h4>The same steps on minikube</h4>\n<pre><code>$ minikube start                          # instead of kind create cluster\n$ minikube image load myapp:dev           # instead of kind load docker-image\n$ minikube service web -n shop --url      # prints a URL that reaches the Service\n$ minikube addons enable ingress          # a ready-made Ingress controller\n$ minikube delete</code></pre>\n\n<h4>Common problems</h4>\n<ul>\n<li><b><code>The connection to the server localhost:8080 was refused</code></b>: kubectl has no cluster to talk to. Check <code>kubectl config get-contexts</code>, and that Docker (and the kind containers) are running.</li>\n<li><b>Pods stuck in <code>Pending</code></b>: <code>kubectl describe pod</code> usually says <code>Insufficient cpu</code> or <code>memory</code>. Give Docker Desktop more resources, or lower the requests.</li>\n<li><b>ImagePullBackOff for your own image</b>: you forgot <code>kind load</code>, or used the <code>latest</code> tag.</li>\n<li><b>Changes \"don't apply\"</b>: you're in a different namespace or context than you think. <code>kubectl config get-contexts</code> shows both.</li>\n</ul>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=s_o8dwzRlu4&amp;t=1959s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Kubernetes Crash Course <span class=\"learn-sources-part\">· Minikube and kubectl: a local cluster (32:39)</span></a><a href=\"https://www.youtube.com/watch?v=s_o8dwzRlu4&amp;t=3940s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Kubernetes Crash Course <span class=\"learn-sources-part\">· Interacting with the cluster (1:05:40)</span></a><a href=\"https://www.youtube.com/watch?v=H_a5DTKSEjY&amp;t=209s\" target=\"_blank\" rel=\"noopener noreferrer\">Vishakha Sadhwani · The ONLY Kubernetes Course You'll Ever Need <span class=\"learn-sources-part\">· Ways to run Kubernetes (3:29)</span></a></div>","kubernetes/helm-jobs-cronjobs-daemonsets":"\n<p class=\"learn-lead\">Deployments are for apps that run forever. Real clusters also run one-off tasks, tasks on a timetable, and agents that must sit on every node, and most third-party software (monitoring, ingress controllers, databases) is installed with Helm rather than hand-written YAML. This chapter covers all four.</p>\n\n<h4>Jobs: run to completion</h4>\n<p>A <b>Job</b> runs a pod until it finishes successfully, retrying if it fails. Database migrations, a one-time data import or a report are typical Jobs.</p>\n<pre><code>apiVersion: batch/v1\nkind: Job\nmetadata:\n  name: migrate-db\nspec:\n  backoffLimit: 3                  # retry a failed pod at most 3 times\n  activeDeadlineSeconds: 600       # give up after 10 minutes in total\n  ttlSecondsAfterFinished: 3600    # delete the finished Job an hour later\n  template:\n    spec:\n      restartPolicy: Never         # Jobs need Never or OnFailure\n      containers:\n        - name: migrate\n          image: ghcr.io/you/myapp:1.4.0\n          command: [\"python\", \"manage.py\", \"migrate\"]</code></pre>\n<pre><code>$ kubectl apply -f job.yaml\n$ kubectl get jobs\nNAME         STATUS     COMPLETIONS   DURATION   AGE\nmigrate-db   Complete   1/1           12s        40s\n$ kubectl logs job/migrate-db</code></pre>\n\n<h4>CronJobs: Jobs on a timetable</h4>\n<p>A <b>CronJob</b> creates a Job on a schedule, written in the same five-field format as Linux cron (Linux chapter 9).</p>\n<pre><code>apiVersion: batch/v1\nkind: CronJob\nmetadata:\n  name: nightly-backup\nspec:\n  schedule: \"0 2 * * *\"            # 02:00 every day\n  timeZone: \"Europe/London\"        # without it, the schedule uses the cluster's time zone (usually UTC)\n  concurrencyPolicy: Forbid        # don't start a new run while the last one is still going\n  successfulJobsHistoryLimit: 3\n  failedJobsHistoryLimit: 3\n  jobTemplate:\n    spec:\n      backoffLimit: 2\n      template:\n        spec:\n          restartPolicy: OnFailure\n          containers:\n            - name: backup\n              image: ghcr.io/you/backup:1.0\n              args: [\"--target\", \"s3://my-backups\"]</code></pre>\n<p>Waiting until 2 a.m. to see whether it works is no fun, so trigger a run by hand:</p>\n<pre><code>$ kubectl create job backup-test --from=cronjob/nightly-backup\n$ kubectl get cronjob nightly-backup     # LAST SCHEDULE shows when it last fired</code></pre>\n<p>Set <code>suspend: true</code> in the spec to pause a CronJob without deleting it.</p>\n\n<h4>DaemonSets: one pod on every node</h4>\n<p>A <b>DaemonSet</b> runs exactly one copy of a pod on every node (or every node matching a selector), and adds one automatically when a node joins. It's how clusters run node-level agents: log collectors like Fluent Bit, the Prometheus node exporter, and networking plugins.</p>\n<pre><code>apiVersion: apps/v1\nkind: DaemonSet\nmetadata:\n  name: node-exporter\n  namespace: monitoring\nspec:\n  selector:\n    matchLabels: {app: node-exporter}\n  template:\n    metadata:\n      labels: {app: node-exporter}\n    spec:\n      tolerations:                         # also run on control-plane nodes\n        - key: node-role.kubernetes.io/control-plane\n          effect: NoSchedule\n      containers:\n        - name: node-exporter\n          image: prom/node-exporter:v1.8.2\n          ports:\n            - containerPort: 9100</code></pre>\n\n<h4>Which workload for which job</h4>\n<figure class=\"learn-diagram dg\" data-dg=\"k8s-workloads\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 324\" role=\"img\" aria-label=\"Choosing a workload: runs forever and one per node means DaemonSet; runs forever with its own storage means StatefulSet, otherwise Deployment; finishes on a schedule means CronJob, otherwise Job\" style=\"--dgw:680px\"><defs><marker id=\"k8s-workloads--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"b hi\" x=\"250\" y=\"10\" width=\"180\" height=\"44\" rx=\"6\"/><text class=\"tb ta\" x=\"340\" y=\"36.2\" text-anchor=\"middle\" font-size=\"13\">runs forever?</text><rect class=\"b\" x=\"40\" y=\"96\" width=\"200\" height=\"44\" rx=\"6\"/><text class=\"tb\" x=\"140\" y=\"122.2\" text-anchor=\"middle\" font-size=\"13\">one per node?</text><rect class=\"b\" x=\"440\" y=\"96\" width=\"200\" height=\"44\" rx=\"6\"/><text class=\"tb\" x=\"540\" y=\"122.2\" text-anchor=\"middle\" font-size=\"13\">on a schedule?</text><path class=\"ln\" d=\"M300,56 L150,94\" marker-end=\"url(#k8s-workloads--n)\"/><text class=\"tl\" x=\"210\" y=\"68\" text-anchor=\"middle\" font-size=\"11\">yes</text><path class=\"ln\" d=\"M380,56 L530,94\" marker-end=\"url(#k8s-workloads--n)\"/><text class=\"tl\" x=\"500\" y=\"68\" text-anchor=\"middle\" font-size=\"11\">no, it finishes</text><rect class=\"b ok\" x=\"10\" y=\"184\" width=\"120\" height=\"44\" rx=\"6\"/><text class=\"tb\" x=\"70\" y=\"210.2\" text-anchor=\"middle\" font-size=\"13\">DaemonSet</text><rect class=\"b\" x=\"170\" y=\"184\" width=\"160\" height=\"44\" rx=\"6\"/><text class=\"tb\" x=\"250\" y=\"209.8\" text-anchor=\"middle\" font-size=\"12\">own storage?</text><path class=\"ln\" d=\"M110,142 L72,182\" marker-end=\"url(#k8s-workloads--n)\"/><text class=\"tl\" x=\"76\" y=\"160\" text-anchor=\"middle\" font-size=\"11\">yes</text><path class=\"ln\" d=\"M170,142 L240,182\" marker-end=\"url(#k8s-workloads--n)\"/><text class=\"tl\" x=\"222\" y=\"158\" text-anchor=\"middle\" font-size=\"11\">no</text><rect class=\"b ok\" x=\"420\" y=\"184\" width=\"110\" height=\"44\" rx=\"6\"/><text class=\"tb\" x=\"475\" y=\"210.2\" text-anchor=\"middle\" font-size=\"13\">CronJob</text><rect class=\"b ok\" x=\"560\" y=\"184\" width=\"110\" height=\"44\" rx=\"6\"/><text class=\"tb\" x=\"615\" y=\"210.2\" text-anchor=\"middle\" font-size=\"13\">Job</text><path class=\"ln\" d=\"M510,142 L476,182\" marker-end=\"url(#k8s-workloads--n)\"/><text class=\"tl\" x=\"478\" y=\"160\" text-anchor=\"middle\" font-size=\"11\">yes</text><path class=\"ln\" d=\"M570,142 L612,182\" marker-end=\"url(#k8s-workloads--n)\"/><text class=\"tl\" x=\"608\" y=\"160\" text-anchor=\"middle\" font-size=\"11\">no</text><rect class=\"b ok\" x=\"100\" y=\"270\" width=\"140\" height=\"44\" rx=\"6\"/><text class=\"tb\" x=\"170\" y=\"296.2\" text-anchor=\"middle\" font-size=\"13\">StatefulSet</text><rect class=\"b ok\" x=\"270\" y=\"270\" width=\"140\" height=\"44\" rx=\"6\"/><text class=\"tb\" x=\"340\" y=\"296.2\" text-anchor=\"middle\" font-size=\"13\">Deployment</text><path class=\"ln\" d=\"M225,230 L172,268\" marker-end=\"url(#k8s-workloads--n)\"/><text class=\"tl\" x=\"184\" y=\"248\" text-anchor=\"middle\" font-size=\"11\">yes</text><path class=\"ln\" d=\"M275,230 L338,268\" marker-end=\"url(#k8s-workloads--n)\"/><text class=\"tl\" x=\"322\" y=\"246\" text-anchor=\"middle\" font-size=\"11\">no</text></svg></div><figcaption>Two questions settle most cases: does it run forever, and does each copy need something of its own (a node, a disk, a schedule)?</figcaption></figure>\n\n<ul>\n<li><b>Deployment</b>: stateless apps that run forever and can be copied freely (web servers, APIs).</li>\n<li><b>StatefulSet</b>: apps where each copy needs its own identity and storage (databases, queues).</li>\n<li><b>DaemonSet</b>: one per node (agents and collectors).</li>\n<li><b>Job</b>: run once until done.</li>\n<li><b>CronJob</b>: run on a schedule.</li>\n</ul>\n\n<h4>Helm: a package manager for Kubernetes</h4>\n<p>Installing something like a full monitoring stack by hand means dozens of YAML files. <b>Helm</b> packages them as a <b>chart</b>: templates plus a <code>values.yaml</code> file of settings you can override. Installing a chart creates a <b>release</b>, which Helm can upgrade, list and roll back as one unit.</p>\n<pre><code># install Helm (on a Mac: brew install helm)\n$ curl https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3 | bash\n\n$ helm repo add prometheus-community https://prometheus-community.github.io/helm-charts\n$ helm repo update\n$ helm search repo prometheus-community\n$ helm show values prometheus-community/kube-prometheus-stack &gt; defaults.yaml   # every setting you can change\n\n$ helm install monitoring prometheus-community/kube-prometheus-stack \\\n    --namespace monitoring --create-namespace -f my-values.yaml\n\n$ helm list -A                         # releases in every namespace\n$ helm upgrade monitoring prometheus-community/kube-prometheus-stack -n monitoring -f my-values.yaml\n$ helm history monitoring -n monitoring\n$ helm rollback monitoring 1 -n monitoring\n$ helm uninstall monitoring -n monitoring</code></pre>\n\n<h4>Values: changing a chart's settings</h4>\n<p>You never edit a chart's templates; you override its values, either in a file (best, because it goes in Git) or with <code>--set</code> for a one-off:</p>\n<pre><code># my-values.yaml\ngrafana:\n  adminPassword: change-me\n  persistence:\n    enabled: true\nalertmanager:\n  enabled: false</code></pre>\n<pre><code>$ helm template monitoring prometheus-community/kube-prometheus-stack -f my-values.yaml | less   # see the YAML without installing\n$ helm upgrade --install myapp ./chart -n prod --set image.tag=1.4.0                              # install or upgrade: safe to rerun</code></pre>\n<p><code>helm upgrade --install</code> is what CI pipelines use: it works whether or not the release already exists.</p>\n\n<h4>Your own chart</h4>\n<pre><code>$ helm create myapp       # makes Chart.yaml, values.yaml and templates/\n$ helm lint myapp\n$ helm install myapp ./myapp -n shop</code></pre>\n<p>Inside <code>templates/</code>, values are filled in with Go templating, for example <code>image: \"{{ .Values.image.repository }}:{{ .Values.image.tag }}\"</code>. Start by changing <code>values.yaml</code> and reading what each template does with it.</p>\n\n<h4>Common problems</h4>\n<ul>\n<li><b><code>cannot re-use a name that is still in use</code></b>: a release with that name exists. Use <code>helm upgrade --install</code>, or pick another name.</li>\n<li><b>A Job retries forever, or never</b>: check <code>backoffLimit</code> and <code>restartPolicy</code>; <code>kubectl describe job</code> shows each attempt.</li>\n<li><b>A CronJob never fires</b>: check <code>suspend</code>, the time zone, and the schedule (crontab.guru explains any expression). If a run is missed by more than <code>startingDeadlineSeconds</code>, it's skipped.</li>\n<li><b>A DaemonSet has fewer pods than nodes</b>: some nodes have taints the pods don't tolerate, or a <code>nodeSelector</code> excludes them.</li>\n</ul>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=s_o8dwzRlu4&amp;t=1186s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Kubernetes Crash Course <span class=\"learn-sources-part\">· Deployment & StatefulSet (19:46)</span></a><a href=\"https://www.youtube.com/watch?v=H_a5DTKSEjY&amp;t=495s\" target=\"_blank\" rel=\"noopener noreferrer\">Vishakha Sadhwani · The ONLY Kubernetes Course You'll Ever Need <span class=\"learn-sources-part\">· Data plane objects (8:15)</span></a></div>","cloud/what-cloud-computing-is":"\n<p class=\"learn-lead\">Cloud computing means renting computing power, storage, networking and ready-made services from a provider over the internet, starting and stopping them yourself in minutes and paying only for what you use. This chapter sets up the vocabulary the rest of the Cloud topic relies on: service models, where the cloud physically lives, who is responsible for what, and how AWS, Azure and Google Cloud name the same building blocks.</p>\n\n<h4>Renting instead of owning</h4>\n<p>Before the cloud, running a website meant buying servers, waiting weeks for delivery, installing them in a data centre and sizing them for your busiest day, so most of the time they sat half idle. That money is <b>CapEx</b> (capital expenditure): a large up-front purchase of something you own and depreciate over years. The cloud turns it into <b>OpEx</b> (operating expenditure): a running bill that goes up and down with usage, like electricity. You trade ownership and long-term planning for flexibility.</p>\n<p>The usual definition (from the US standards body NIST) lists five characteristics. A service that has all five is \"cloud\"; a rented server you have to phone someone to resize is not.</p>\n<ul>\n<li><b>On-demand self-service</b>: you create a server or a database yourself, from a web console, a CLI or an API, with no human at the provider involved.</li>\n<li><b>Broad network access</b>: everything is reachable over the network with standard protocols.</li>\n<li><b>Resource pooling</b>: many customers share the same huge pool of hardware, isolated from each other.</li>\n<li><b>Rapid elasticity</b>: capacity grows and shrinks quickly, even automatically (the autoscaling from the AWS chapter).</li>\n<li><b>Measured service</b>: usage is metered (per second, per GB, per request) and you are billed for exactly that. <b>Pay-as-you-go</b> is the pricing side of this.</li>\n</ul>\n<p>Pay-as-you-go is not automatically cheaper. A server that runs flat out 24/7 for three years can cost more to rent than to own. The cloud wins when load varies, when you need to start fast, or when you'd rather not run a data centre at all.</p>\n\n<h4>Service models: IaaS, PaaS, SaaS and FaaS</h4>\n<p>The service models differ in <b>how much of the stack the provider runs for you</b>. The higher up you go, the less you manage and the less you can control.</p>\n<div class=\"learn-table-wrap\"><table class=\"learn-table\"><thead><tr><th>Model</th><th>You get</th><th>You still manage</th><th>Examples</th></tr></thead><tbody>\n<tr><td><b>IaaS</b> (Infrastructure as a Service)</td><td>Virtual machines, disks, networks</td><td>The operating system and its patches, runtimes, your app, your data</td><td>AWS EC2, Azure Virtual Machines, Google Compute Engine, DigitalOcean Droplets</td></tr>\n<tr><td><b>PaaS</b> (Platform as a Service)</td><td>A platform that runs your code or hosts your database</td><td>Your app code, its configuration, your data</td><td>AWS Elastic Beanstalk, Azure App Service, Google App Engine, Heroku, managed databases like Amazon RDS</td></tr>\n<tr><td><b>FaaS</b> (Functions as a Service, \"serverless\")</td><td>Runs a single function when an event arrives</td><td>The function code and its permissions</td><td>AWS Lambda, Azure Functions, Google Cloud Run functions</td></tr>\n<tr><td><b>SaaS</b> (Software as a Service)</td><td>A finished application in the browser</td><td>Your users, your data, the settings</td><td>Gmail, Microsoft 365, Slack, GitHub</td></tr>\n</tbody></table></div>\n<p>An everyday comparison: IaaS is renting an empty flat, PaaS is a serviced apartment, SaaS is a hotel room. You'll also meet in-between terms such as <b>CaaS</b> (Containers as a Service): you hand over a container image and the platform runs it, as with AWS Fargate, Azure Container Apps and Google Cloud Run. Google renamed Cloud Functions to <b>Cloud Run functions</b> in 2024, so older tutorials use the old name.</p>\n\n\n<figure class=\"learn-diagram dg\" data-dg=\"cloud-models\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 330\" role=\"img\" aria-label=\"Who manages what: on-premises you run all seven layers; with IaaS the provider runs virtualisation, servers and networking; with PaaS also the OS and runtime; with SaaS everything\" style=\"--dgw:680px\"><text class=\"tb\" x=\"200\" y=\"20\" text-anchor=\"middle\" font-size=\"13\">on-premises</text><rect class=\"b hi\" x=\"140\" y=\"32\" width=\"120\" height=\"32\" rx=\"3\"/><rect class=\"b hi\" x=\"140\" y=\"70\" width=\"120\" height=\"32\" rx=\"3\"/><rect class=\"b hi\" x=\"140\" y=\"108\" width=\"120\" height=\"32\" rx=\"3\"/><rect class=\"b hi\" x=\"140\" y=\"146\" width=\"120\" height=\"32\" rx=\"3\"/><rect class=\"b hi\" x=\"140\" y=\"184\" width=\"120\" height=\"32\" rx=\"3\"/><rect class=\"b hi\" x=\"140\" y=\"222\" width=\"120\" height=\"32\" rx=\"3\"/><rect class=\"b hi\" x=\"140\" y=\"260\" width=\"120\" height=\"32\" rx=\"3\"/><text class=\"tb\" x=\"335\" y=\"20\" text-anchor=\"middle\" font-size=\"13\">IaaS</text><rect class=\"b hi\" x=\"275\" y=\"32\" width=\"120\" height=\"32\" rx=\"3\"/><rect class=\"b hi\" x=\"275\" y=\"70\" width=\"120\" height=\"32\" rx=\"3\"/><rect class=\"b hi\" x=\"275\" y=\"108\" width=\"120\" height=\"32\" rx=\"3\"/><rect class=\"b hi\" x=\"275\" y=\"146\" width=\"120\" height=\"32\" rx=\"3\"/><rect class=\"b ok\" x=\"275\" y=\"184\" width=\"120\" height=\"32\" rx=\"3\"/><rect class=\"b ok\" x=\"275\" y=\"222\" width=\"120\" height=\"32\" rx=\"3\"/><rect class=\"b ok\" x=\"275\" y=\"260\" width=\"120\" height=\"32\" rx=\"3\"/><text class=\"tb\" x=\"470\" y=\"20\" text-anchor=\"middle\" font-size=\"13\">PaaS</text><rect class=\"b hi\" x=\"410\" y=\"32\" width=\"120\" height=\"32\" rx=\"3\"/><rect class=\"b hi\" x=\"410\" y=\"70\" width=\"120\" height=\"32\" rx=\"3\"/><rect class=\"b ok\" x=\"410\" y=\"108\" width=\"120\" height=\"32\" rx=\"3\"/><rect class=\"b ok\" x=\"410\" y=\"146\" width=\"120\" height=\"32\" rx=\"3\"/><rect class=\"b ok\" x=\"410\" y=\"184\" width=\"120\" height=\"32\" rx=\"3\"/><rect class=\"b ok\" x=\"410\" y=\"222\" width=\"120\" height=\"32\" rx=\"3\"/><rect class=\"b ok\" x=\"410\" y=\"260\" width=\"120\" height=\"32\" rx=\"3\"/><text class=\"tb\" x=\"605\" y=\"20\" text-anchor=\"middle\" font-size=\"13\">SaaS</text><rect class=\"b ok\" x=\"545\" y=\"32\" width=\"120\" height=\"32\" rx=\"3\"/><rect class=\"b ok\" x=\"545\" y=\"70\" width=\"120\" height=\"32\" rx=\"3\"/><rect class=\"b ok\" x=\"545\" y=\"108\" width=\"120\" height=\"32\" rx=\"3\"/><rect class=\"b ok\" x=\"545\" y=\"146\" width=\"120\" height=\"32\" rx=\"3\"/><rect class=\"b ok\" x=\"545\" y=\"184\" width=\"120\" height=\"32\" rx=\"3\"/><rect class=\"b ok\" x=\"545\" y=\"222\" width=\"120\" height=\"32\" rx=\"3\"/><rect class=\"b ok\" x=\"545\" y=\"260\" width=\"120\" height=\"32\" rx=\"3\"/><text class=\"t2\" x=\"130\" y=\"53\" text-anchor=\"end\" font-size=\"11\">your data</text><text class=\"t2\" x=\"130\" y=\"91\" text-anchor=\"end\" font-size=\"11\">your app</text><text class=\"t2\" x=\"130\" y=\"129\" text-anchor=\"end\" font-size=\"11\">runtime</text><text class=\"t2\" x=\"130\" y=\"167\" text-anchor=\"end\" font-size=\"11\">operating system</text><text class=\"t2\" x=\"130\" y=\"205\" text-anchor=\"end\" font-size=\"11\">virtualisation</text><text class=\"t2\" x=\"130\" y=\"243\" text-anchor=\"end\" font-size=\"11\">servers + storage</text><text class=\"t2\" x=\"130\" y=\"281\" text-anchor=\"end\" font-size=\"11\">networking</text><rect class=\"b hi\" x=\"140\" y=\"300\" width=\"120\" height=\"24\" rx=\"6\"/><text class=\"tb ta\" x=\"200\" y=\"315.5\" text-anchor=\"middle\" font-size=\"11\">you manage</text><rect class=\"b ok\" x=\"275\" y=\"300\" width=\"170\" height=\"24\" rx=\"6\"/><text class=\"tb\" x=\"360\" y=\"315.5\" text-anchor=\"middle\" font-size=\"11\">the provider runs it</text></svg></div><figcaption>Moving right, the provider takes over more of the stack. You give up control in exchange for less to patch, secure and keep running.</figcaption></figure>\n<h4>Deployment models: public, private, hybrid, multi-cloud</h4>\n<ul>\n<li><b>Public cloud</b>: the provider's shared infrastructure, used over the internet (AWS, Azure, Google Cloud). What people usually mean by \"the cloud\".</li>\n<li><b>Private cloud</b>: cloud-style self-service on hardware dedicated to one organisation, often in its own data centre (for example with OpenStack or VMware). More control, but you're back to buying and running hardware.</li>\n<li><b>Hybrid cloud</b>: on-premises systems and a public cloud connected and used together, for example a bank keeping its core database in-house while running its website on AWS. Providers sell tools for this, such as AWS Outposts (AWS hardware in your building) and Azure Arc (managing your own servers from Azure).</li>\n<li><b>Multi-cloud</b>: using more than one public provider, for example AWS for the app and Google Cloud for data analytics. It can avoid depending on a single vendor, but every provider has different services, permissions and bills, so it multiplies the work. Many companies end up multi-cloud by accident rather than by design.</li>\n</ul>\n\n<h4>Regions, availability zones and edge locations</h4>\n<p>The cloud is real buildings. Providers group them in three levels:</p>\n<ul>\n<li>A <b>region</b> is a geographic area with its own independent set of data centres, named with a code: AWS <code>eu-central-1</code> (Frankfurt), Google Cloud <code>europe-west3</code> (also Frankfurt), Azure <code>germanywestcentral</code>. Most resources live in exactly one region, and your data stays there unless you copy it elsewhere.</li>\n<li>An <b>availability zone</b> (AZ) is one or more data centres inside a region with separate power, cooling and networking, physically separated (typically by kilometres) and linked by fast private fibre. AWS names them by adding a letter (<code>eu-central-1a</code>), Google by adding a suffix (<code>europe-west3-a</code>). AWS regions normally have three or more AZs, and Google Cloud regions and zone-enabled Azure regions usually have three.</li>\n<li><b>Edge locations</b> (points of presence) are many small sites in cities worldwide that sit close to users. They don't run your servers; they cache content (CloudFront, the AWS CDN), answer DNS (Route 53) and run tiny edge functions.</li>\n</ul>\n<p>Spreading copies across two or more AZs protects you from a data-centre failure; copying to a second region protects you from a whole-region outage, at more cost and complexity. On AWS, <code>eu-central-1a</code> in your account is not necessarily the same building as <code>eu-central-1a</code> in someone else's: AWS maps the letters differently per account. When comparing across accounts, use the <b>AZ ID</b> (like <code>euc1-az2</code>), which is the same everywhere.</p>\n<div class=\"learn-callout\">To choose a region, weigh: <b>latency</b> (close to your users), <b>data residency</b> (some laws require data to stay in a country or in the EU), <b>service availability</b> (new services don't reach every region at once) and <b>price</b> (the same service costs different amounts in different regions). AWS's <code>us-east-1</code> (N. Virginia) is special: some global features live there, such as billing metrics and the TLS certificates used by CloudFront.</div>\n\n\n<figure class=\"learn-diagram dg\" data-dg=\"cloud-regions\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 240\" role=\"img\" aria-label=\"A region such as eu-central-1 holds three availability zones, each with its own data centres and power; edge locations sit closer to users and cache content\" style=\"--dgw:680px\"><rect class=\"g hi\" x=\"10\" y=\"10\" width=\"450\" height=\"220\" rx=\"8\"/><text class=\"tg hi\" x=\"20\" y=\"26\" font-size=\"11\">region: eu-central-1 (Frankfurt)</text><rect class=\"g\" x=\"26\" y=\"44\" width=\"130\" height=\"170\" rx=\"8\"/><text class=\"tg \" x=\"36\" y=\"60\" font-size=\"11\">AZ eu-central-1a</text><rect class=\"b\" x=\"40\" y=\"78\" width=\"102\" height=\"40\" rx=\"6\"/><text class=\"\" x=\"91\" y=\"101.5\" text-anchor=\"middle\" font-size=\"11\">data centre</text><rect class=\"b\" x=\"40\" y=\"130\" width=\"102\" height=\"40\" rx=\"6\"/><text class=\"\" x=\"91\" y=\"153.5\" text-anchor=\"middle\" font-size=\"11\">data centre</text><text class=\"t2\" x=\"91\" y=\"196\" text-anchor=\"middle\" font-size=\"10\">own power</text><rect class=\"g\" x=\"172\" y=\"44\" width=\"130\" height=\"170\" rx=\"8\"/><text class=\"tg \" x=\"182\" y=\"60\" font-size=\"11\">AZ eu-central-1b</text><rect class=\"b\" x=\"186\" y=\"78\" width=\"102\" height=\"40\" rx=\"6\"/><text class=\"\" x=\"237\" y=\"101.5\" text-anchor=\"middle\" font-size=\"11\">data centre</text><rect class=\"b\" x=\"186\" y=\"130\" width=\"102\" height=\"40\" rx=\"6\"/><text class=\"\" x=\"237\" y=\"153.5\" text-anchor=\"middle\" font-size=\"11\">data centre</text><text class=\"t2\" x=\"237\" y=\"196\" text-anchor=\"middle\" font-size=\"10\">own power</text><rect class=\"g\" x=\"318\" y=\"44\" width=\"130\" height=\"170\" rx=\"8\"/><text class=\"tg \" x=\"328\" y=\"60\" font-size=\"11\">AZ eu-central-1c</text><rect class=\"b\" x=\"332\" y=\"78\" width=\"102\" height=\"40\" rx=\"6\"/><text class=\"\" x=\"383\" y=\"101.5\" text-anchor=\"middle\" font-size=\"11\">data centre</text><rect class=\"b\" x=\"332\" y=\"130\" width=\"102\" height=\"40\" rx=\"6\"/><text class=\"\" x=\"383\" y=\"153.5\" text-anchor=\"middle\" font-size=\"11\">data centre</text><text class=\"t2\" x=\"383\" y=\"196\" text-anchor=\"middle\" font-size=\"10\">own power</text><rect class=\"b warn\" x=\"500\" y=\"30\" width=\"170\" height=\"52\" rx=\"6\"/><text class=\"tb\" x=\"585\" y=\"53.2\" text-anchor=\"middle\" font-size=\"13\">edge location</text><text class=\"t2\" x=\"585\" y=\"67.7\" text-anchor=\"middle\" font-size=\"10\">CDN cache near users</text><rect class=\"b warn\" x=\"500\" y=\"100\" width=\"170\" height=\"52\" rx=\"6\"/><text class=\"tb\" x=\"585\" y=\"123.2\" text-anchor=\"middle\" font-size=\"13\">edge location</text><text class=\"t2\" x=\"585\" y=\"137.7\" text-anchor=\"middle\" font-size=\"10\">CDN cache near users</text><text class=\"t2\" x=\"585\" y=\"190\" text-anchor=\"middle\" font-size=\"11\">many more edge locations</text><text class=\"t2\" x=\"585\" y=\"208\" text-anchor=\"middle\" font-size=\"11\">than regions</text></svg></div><figcaption>Spread an app over at least two AZs and one building failing doesn't take it down. Regions are for distance and data rules; edges are for speed.</figcaption></figure>\n<h4>The shared responsibility model</h4>\n<p>Security in the cloud is split between you and the provider. AWS phrases it as: AWS is responsible for security <b>of</b> the cloud (buildings, hardware, the virtualisation layer, the global network), and you are responsible for security <b>in</b> the cloud (what you build and how you configure it). Where the line sits depends on the service model:</p>\n<div class=\"learn-table-wrap\"><table class=\"learn-table\"><thead><tr><th>Service</th><th>Provider handles</th><th>You handle</th></tr></thead><tbody>\n<tr><td>EC2 virtual machine (IaaS)</td><td>Hardware, hypervisor, physical network</td><td>OS updates, firewall rules (security groups), installed software, SSH keys, data, IAM permissions</td></tr>\n<tr><td>RDS database (managed)</td><td>Also the OS and database engine patching, automated backups</td><td>Who can connect, network placement, choosing encryption and backup retention, your schema and data</td></tr>\n<tr><td>Lambda function (FaaS)</td><td>Also the servers, OS and language runtime</td><td>Your code and its dependencies, the function's permissions, input validation</td></tr>\n<tr><td>S3 storage</td><td>Durability, disks, the storage service itself</td><td>Who can read and write each bucket, encryption settings, versioning</td></tr>\n</tbody></table></div>\n<p>Whatever the model, <b>your data, your identities and permissions, and your configuration are always your job</b>. Most cloud breaches aren't provider failures; they're a public bucket, a leaked access key or a database open to the internet.</p>\n\n<h4>The same building blocks on AWS, Azure and Google Cloud</h4>\n<p>Learn the concepts once and the names are mostly translation:</p>\n<div class=\"learn-table-wrap\"><table class=\"learn-table\"><thead><tr><th>Building block</th><th>AWS</th><th>Azure</th><th>Google Cloud</th></tr></thead><tbody>\n<tr><td>Virtual machines</td><td>EC2</td><td>Virtual Machines</td><td>Compute Engine</td></tr>\n<tr><td>Object storage</td><td>S3</td><td>Blob Storage</td><td>Cloud Storage</td></tr>\n<tr><td>Block disks for VMs</td><td>EBS</td><td>Managed Disks</td><td>Persistent Disk, Hyperdisk</td></tr>\n<tr><td>Managed SQL databases</td><td>RDS, Aurora</td><td>Azure SQL Database, Azure Database for PostgreSQL / MySQL</td><td>Cloud SQL, AlloyDB</td></tr>\n<tr><td>NoSQL database</td><td>DynamoDB</td><td>Cosmos DB</td><td>Firestore, Bigtable</td></tr>\n<tr><td>Serverless functions</td><td>Lambda</td><td>Azure Functions</td><td>Cloud Run functions</td></tr>\n<tr><td>Serverless containers</td><td>ECS on Fargate</td><td>Container Apps</td><td>Cloud Run</td></tr>\n<tr><td>Managed Kubernetes</td><td>EKS</td><td>AKS</td><td>GKE</td></tr>\n<tr><td>Container registry</td><td>ECR</td><td>Container Registry (ACR)</td><td>Artifact Registry</td></tr>\n<tr><td>Private network</td><td>VPC</td><td>Virtual Network (VNet)</td><td>VPC</td></tr>\n<tr><td>Identity and permissions</td><td>IAM, IAM Identity Center</td><td>Microsoft Entra ID (formerly Azure AD) plus Azure RBAC</td><td>Cloud IAM</td></tr>\n<tr><td>Monitoring and logs</td><td>CloudWatch</td><td>Azure Monitor</td><td>Cloud Monitoring, Cloud Logging</td></tr>\n<tr><td>Provider's own IaC</td><td>CloudFormation, CDK</td><td>ARM templates, Bicep</td><td>Infrastructure Manager (runs Terraform)</td></tr>\n</tbody></table></div>\n<p>The differences are in the details. AWS organises everything into <b>accounts</b>; Azure into <b>subscriptions</b> and <b>resource groups</b>; Google Cloud into <b>projects</b>. A Google Cloud VPC is global with regional subnets, while AWS and Azure networks belong to one region. Terraform, covered in the DevOps topic, works with all three.</p>\n\n<h4>How to choose</h4>\n<ul>\n<li><b>What the team already knows</b> usually matters most. A provider your team can operate safely beats a slightly better one nobody understands.</li>\n<li><b>Existing ecosystem</b>: companies built on Microsoft 365 and Active Directory often pick Azure; data and ML-heavy teams often like Google Cloud (BigQuery, GKE); AWS has the widest range of services and the largest community, so most tutorials and job ads assume it.</li>\n<li><b>Regions and compliance</b>: is there a region near your users that meets your legal requirements?</li>\n<li><b>Managed services you need</b>, and how much lock-in you accept. Plain VMs, containers and PostgreSQL move between clouds easily; DynamoDB or Cosmos DB don't.</li>\n<li><b>Cost</b> for your actual workload, estimated with each provider's own pricing calculator rather than list-price comparisons.</li>\n</ul>\n<p>For learning, pick one (this topic uses AWS) and go deep. The second cloud is much faster to learn than the first.</p>\n\n<h4>Common misconceptions</h4>\n<ul>\n<li><b>\"The cloud is always cheaper.\"</b> Only if you size things properly and switch off what you don't use. The costs chapter shows where surprise bills come from.</li>\n<li><b>\"The provider handles security.\"</b> Only its half. Your configuration is on you.</li>\n<li><b>\"The cloud never goes down.\"</b> Whole AZs and occasionally whole regions have outages. Resilience is something you design, using several AZs.</li>\n<li><b>\"Serverless means no servers.\"</b> There are servers; you just don't see or manage them.</li>\n</ul>\n","cloud/cloud-computing-aws":"\n<p class=\"learn-lead\">Cloud computing means renting infrastructure on demand and paying for what you use. The Be A Better Dev videos cover the concepts that come up in every cloud design, and the most important AWS services that implement them.</p>\n\n<h4>Scaling</h4>\n<p><b>Vertical scaling</b> (scaling up) means a bigger machine: more CPU and RAM. It's simple but has a ceiling, and upgrading usually means a restart. <b>Horizontal scaling</b> (scaling out) means more machines of the same size behind a load balancer. There's practically no ceiling and no single point of failure, but the app must be <b>stateless</b>: session data lives in a shared database or cache, not on one server, so any server can answer any request.</p>\n<figure class=\"learn-diagram dg\" data-dg=\"cloud-scaling\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 220\" role=\"img\" aria-label=\"Vertical scaling swaps a small machine for a bigger one; horizontal scaling adds more identical machines behind a load balancer\" style=\"--dgw:680px\"><defs><marker id=\"cloud-scaling--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker><marker id=\"cloud-scaling--ok\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk ok\" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><text class=\"tb\" x=\"160\" y=\"22\" text-anchor=\"middle\" font-size=\"13\">vertical: scale up</text><rect class=\"b\" x=\"20\" y=\"110\" width=\"90\" height=\"60\" rx=\"6\"/><text class=\"tb\" x=\"65\" y=\"137.2\" text-anchor=\"middle\" font-size=\"13\">small</text><text class=\"t2\" x=\"65\" y=\"151.7\" text-anchor=\"middle\" font-size=\"10\">2 vCPU</text><rect class=\"b hi\" x=\"170\" y=\"60\" width=\"140\" height=\"140\" rx=\"6\"/><text class=\"tb ta\" x=\"240\" y=\"127.2\" text-anchor=\"middle\" font-size=\"13\">bigger</text><text class=\"t2\" x=\"240\" y=\"141.7\" text-anchor=\"middle\" font-size=\"10\">16 vCPU, 64 GB</text><path class=\"ln\" d=\"M112,140 L168,140\" marker-end=\"url(#cloud-scaling--n)\"/><text class=\"tl\" x=\"140\" y=\"130\" text-anchor=\"middle\" font-size=\"10\">resize</text><text class=\"bad\" x=\"160\" y=\"214\" text-anchor=\"middle\" font-size=\"11\">a ceiling, and usually a restart</text><text class=\"tb\" x=\"510\" y=\"22\" text-anchor=\"middle\" font-size=\"13\">horizontal: scale out</text><rect class=\"b hi\" x=\"440\" y=\"40\" width=\"140\" height=\"40\" rx=\"6\"/><text class=\"tb ta\" x=\"510\" y=\"63.8\" text-anchor=\"middle\" font-size=\"12\">load balancer</text><rect class=\"b ok\" x=\"370\" y=\"120\" width=\"90\" height=\"56\" rx=\"6\"/><text class=\"tb\" x=\"415\" y=\"145.2\" text-anchor=\"middle\" font-size=\"13\">app</text><text class=\"t2\" x=\"415\" y=\"159.7\" text-anchor=\"middle\" font-size=\"10\">2 vCPU</text><path class=\"ln ok\" d=\"M510,82 L415,118\" marker-end=\"url(#cloud-scaling--ok)\"/><rect class=\"b ok\" x=\"470\" y=\"120\" width=\"90\" height=\"56\" rx=\"6\"/><text class=\"tb\" x=\"515\" y=\"145.2\" text-anchor=\"middle\" font-size=\"13\">app</text><text class=\"t2\" x=\"515\" y=\"159.7\" text-anchor=\"middle\" font-size=\"10\">2 vCPU</text><path class=\"ln ok\" d=\"M510,82 L515,118\" marker-end=\"url(#cloud-scaling--ok)\"/><rect class=\"b ok\" x=\"570\" y=\"120\" width=\"90\" height=\"56\" rx=\"6\"/><text class=\"tb\" x=\"615\" y=\"145.2\" text-anchor=\"middle\" font-size=\"13\">app</text><text class=\"t2\" x=\"615\" y=\"159.7\" text-anchor=\"middle\" font-size=\"10\">2 vCPU</text><path class=\"ln ok\" d=\"M510,82 L615,118\" marker-end=\"url(#cloud-scaling--ok)\"/><text class=\"ok\" x=\"510\" y=\"214\" text-anchor=\"middle\" font-size=\"11\">no ceiling, but the app must be stateless</text></svg></div><figcaption>Scaling out is how the cloud handles real traffic: add a machine when busy, remove it when quiet. It only works if any machine can serve any request.</figcaption></figure>\n\n<p><b>Autoscaling</b> adds and removes servers (or containers) automatically based on a metric like CPU usage or request count: more machines at peak times, fewer at night, so you pay for what you actually need.</p>\n\n<h4>Serverless and event-driven</h4>\n<p>With <b>serverless</b> functions (AWS <b>Lambda</b>) you upload just a function; the cloud runs it when it's triggered, scales it automatically, and bills per call. There are no servers to patch, at the cost of time limits, cold starts and less control. It suits <b>event-driven</b> designs, where services react to events instead of calling each other directly: \"a file was uploaded\", \"an order was placed\". Queues and topics (<b>SQS</b>, <b>SNS</b>, <b>EventBridge</b>) pass those events along and keep services loosely connected, so one slow service doesn't bring down the rest.</p>\n\n<h4>Storage types</h4>\n<ul>\n<li><b>Object storage</b> (<b>S3</b>): files (\"objects\") in buckets, reached over HTTP. Practically unlimited and cheap. Used for backups, images, logs, static websites.</li>\n<li><b>Block storage</b> (<b>EBS</b>): a virtual hard disk attached to one server. Used for operating systems and databases.</li>\n<li><b>File storage</b> (<b>EFS</b>): a shared network drive that many servers mount at once.</li>\n</ul>\n\n<h4>Availability and durability</h4>\n<p><b>Availability</b> is whether the service is up and answering, measured in \"nines\": 99.9% availability allows about 8.8 hours of downtime a year, 99.99% about 53 minutes. <b>Durability</b> is whether stored data survives: S3 is designed for 11 nines of durability, meaning it's practically never lost. They're different: a system can be temporarily down (unavailable) while your data is perfectly safe (durable).</p>\n<p>Clouds are split into <b>regions</b> (geographic areas, like Frankfurt) and each region into several <b>availability zones</b>: separate data centres with their own power and network. Running copies in two or more zones keeps you up if one fails.</p>\n\n<h4>The main AWS services, by job</h4>\n<div class=\"learn-table-wrap\"><table class=\"learn-table\">\n<tr><th>Job</th><th>AWS service</th></tr>\n<tr><td>DNS for your domains</td><td>Route 53</td></tr>\n<tr><td>Virtual machines</td><td>EC2</td></tr>\n<tr><td>Containers</td><td>ECS, EKS (Kubernetes), Fargate (serverless containers), ECR (image registry)</td></tr>\n<tr><td>Functions</td><td>Lambda</td></tr>\n<tr><td>Load balancing and autoscaling</td><td>Elastic Load Balancing (ALB/NLB), Auto Scaling groups</td></tr>\n<tr><td>Storage</td><td>S3 (objects), EBS (disks), EFS (shared files)</td></tr>\n<tr><td>CDN</td><td>CloudFront</td></tr>\n<tr><td>Databases and caching</td><td>RDS / Aurora (SQL), DynamoDB (NoSQL), ElastiCache (Redis)</td></tr>\n<tr><td>APIs and user login</td><td>API Gateway, Cognito</td></tr>\n<tr><td>Messaging</td><td>SQS (queues), SNS (notifications), EventBridge (events), Step Functions (workflows)</td></tr>\n<tr><td>Secrets and config</td><td>Secrets Manager, Systems Manager Parameter Store</td></tr>\n<tr><td>Monitoring and logs</td><td>CloudWatch</td></tr>\n<tr><td>Permissions</td><td>IAM (users, roles, policies)</td></tr>\n<tr><td>Private network</td><td>VPC (see Networking)</td></tr>\n<tr><td>Infrastructure as code and CI/CD</td><td>CloudFormation / CDK, CodePipeline, CodeBuild, CodeDeploy</td></tr>\n</table></div>\n<p><b>IAM</b> deserves a special mention: every action in AWS is checked against IAM policies. The golden rule is <b>least privilege</b>: give each user, server and pipeline only the permissions it actually needs, and give servers <b>roles</b> instead of storing access keys on them.</p>\n\n<h4>CI/CD on AWS</h4>\n<p>The edureka AWS DevOps tutorial builds the same pipeline with AWS's own services: <b>CodeCommit</b> (Git hosting), <b>CodeBuild</b> (build and test), <b>CodeDeploy</b> (deploy to EC2 or other targets) and <b>CodePipeline</b>, which chains them together and triggers on every change. Jenkins, GitHub Actions and GitLab CI do the same job; the choice is mostly about where your code already lives.</p>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=FhLu0ASUrzA&amp;t=597s\" target=\"_blank\" rel=\"noopener noreferrer\">edureka! · AWS DevOps Tutorial For Beginners <span class=\"learn-sources-part\">· CI/CD pipeline on AWS (9:57)</span></a><a href=\"https://www.youtube.com/watch?v=ZaA0kNm18pE&amp;t=18s\" target=\"_blank\" rel=\"noopener noreferrer\">Be A Better Dev · Cloud Computing Explained <span class=\"learn-sources-part\">· Scaling, load balancing, autoscaling (0:18)</span></a><a href=\"https://www.youtube.com/watch?v=ZaA0kNm18pE&amp;t=651s\" target=\"_blank\" rel=\"noopener noreferrer\">Be A Better Dev · Cloud Computing Explained <span class=\"learn-sources-part\">· Serverless and event-driven architecture (10:51)</span></a><a href=\"https://www.youtube.com/watch?v=ZaA0kNm18pE&amp;t=1631s\" target=\"_blank\" rel=\"noopener noreferrer\">Be A Better Dev · Cloud Computing Explained <span class=\"learn-sources-part\">· Storage, availability, durability (27:11)</span></a><a href=\"https://www.youtube.com/watch?v=OGYEXGy8ca4&amp;t=792s\" target=\"_blank\" rel=\"noopener noreferrer\">Be A Better Dev · AWS Explained <span class=\"learn-sources-part\">· Compute, containers and serverless on AWS (13:12)</span></a><a href=\"https://www.youtube.com/watch?v=OGYEXGy8ca4&amp;t=1490s\" target=\"_blank\" rel=\"noopener noreferrer\">Be A Better Dev · AWS Explained <span class=\"learn-sources-part\">· Databases and caching (24:50)</span></a><a href=\"https://www.youtube.com/watch?v=OGYEXGy8ca4&amp;t=3554s\" target=\"_blank\" rel=\"noopener noreferrer\">Be A Better Dev · AWS Explained <span class=\"learn-sources-part\">· IAM and networking (59:14)</span></a></div>","cloud/compute-virtual-machines-containers-serverless":"\n<p class=\"learn-lead\">The AWS chapter listed the compute services by job. This chapter gets hands-on: how to pick and launch an EC2 virtual machine and log in to it, what happens when you stop or terminate it, how containers run on ECS and EKS, and what a Lambda function looks like in practice, with its limits and cold starts.</p>\n\n<h4>Reading an EC2 instance type</h4>\n<p>An <b>instance type</b> decides the CPU, memory, network and storage your VM gets. The name is a code:</p>\n<pre><code>t3.micro      t = family (burstable general purpose)   3 = generation   micro = size\nm7g.xlarge    m = family (general purpose)   7 = generation   g = Graviton (ARM) CPU   xlarge = size\nc7i.2xlarge   c = compute optimised   7 = generation   i = Intel CPU   2xlarge = size</code></pre>\n<p>Extra letters after the generation describe the variant: <b>g</b> AWS Graviton (ARM), <b>a</b> AMD, <b>i</b> Intel, <b>d</b> local NVMe instance-store disks, <b>n</b> extra network bandwidth, <b>e</b> extra memory or storage. Sizes go <code>nano</code>, <code>micro</code>, <code>small</code>, <code>medium</code>, <code>large</code>, <code>xlarge</code>, <code>2xlarge</code> and up; from <code>large</code> upward each step roughly doubles CPU and memory, and the price with it. A newer generation is usually faster for the money, so prefer it when the choice is free.</p>\n<ul>\n<li><b>General purpose</b> (M, T): web servers, small apps, dev machines. T types are \"burstable\": a low baseline CPU plus credits to burst above it.</li>\n<li><b>Compute optimised</b> (C): CPU-heavy work such as CI builds and batch jobs.</li>\n<li><b>Memory optimised</b> (R, X): databases and in-memory caches.</li>\n<li><b>Storage optimised</b> (I, D): very fast local disks. <b>Accelerated</b> (P, G, Inf, Trn): GPUs and ML chips.</li>\n</ul>\n<p>T3 and newer burstable types start in <b>unlimited</b> mode by default: if the CPU stays above the baseline for a long time you pay extra instead of being slowed down. A burstable instance running at 100% all day is a sign you want an M or C type.</p>\n\n<h4>The pieces of an EC2 instance</h4>\n<ul>\n<li><b>AMI</b> (Amazon Machine Image): the template the root disk is created from: operating system plus anything pre-installed. AMI IDs (<code>ami-…</code>) are different in every region, and the AMI's CPU architecture (x86_64 or arm64) must match the instance type.</li>\n<li><b>Key pair</b>: AWS puts the public key on the instance; you keep the private key (<code>.pem</code>), which you can download only once. The login user depends on the AMI: <code>ec2-user</code> on Amazon Linux, <code>ubuntu</code> on Ubuntu, <code>admin</code> on Debian.</li>\n<li><b>Security group</b>: the instance's stateful firewall. A new one allows no inbound traffic and all outbound. Open only what you need, and SSH only from your own IP.</li>\n<li><b>User data</b>: a script that cloud-init runs as root on the <b>first boot</b> only, perfect for installing packages. It must start with a shebang like <code>#!/bin/bash</code>; its output goes to <code>/var/log/cloud-init-output.log</code>.</li>\n<li><b>EBS root volume</b>: the network disk holding the OS, usually <b>gp3</b> (general-purpose SSD). Its size and type are chosen at launch and can be increased later. Some types also have <b>instance store</b>: fast local disks whose data is lost when the instance stops.</li>\n</ul>\n\n<h4>Launching from the console</h4>\n<ol>\n<li>Pick your region (top right), open <b>EC2 → Instances → Launch instances</b>, give it a name.</li>\n<li>Choose an AMI (<b>Amazon Linux 2023</b> or Ubuntu Server LTS) and a type such as <code>t3.micro</code>; the console marks types that are free-tier eligible for your account.</li>\n<li>Create a <b>key pair</b> (ED25519) and save the <code>.pem</code>. Under <b>Network settings</b>, keep the default VPC with \"Auto-assign public IP\" enabled, and allow SSH from <b>My IP</b> (plus HTTP for a web server).</li>\n<li>Check the storage, optionally paste a script into <b>Advanced details → User data</b>, and click <b>Launch instance</b>.</li>\n</ol>\n\n<h4>The same launch with the AWS CLI</h4>\n<pre><code># 1. Key pair: the private key is printed once, so save it straight to a file\n$ aws ec2 create-key-pair --key-name practice-key --key-type ed25519 \\\n    --query 'KeyMaterial' --output text &gt; practice-key.pem\n$ chmod 400 practice-key.pem          # ssh refuses keys that others can read\n\n# 2. Security group in the default VPC: SSH from my IP only, HTTP from anywhere\n$ aws ec2 create-security-group --group-name web-sg \\\n    --description \"SSH from my IP, HTTP from anywhere\" --query 'GroupId' --output text\nsg-0123456789abcdef0\n$ aws ec2 authorize-security-group-ingress --group-id sg-0123456789abcdef0 \\\n    --protocol tcp --port 22 --cidr 203.0.113.25/32\n$ aws ec2 authorize-security-group-ingress --group-id sg-0123456789abcdef0 \\\n    --protocol tcp --port 80 --cidr 0.0.0.0/0\n\n# 3. user-data.sh (runs once, as root, on first boot)\n#!/bin/bash\ndnf install -y nginx\nsystemctl enable --now nginx\n\n# 4. Launch. resolve:ssm: looks up the latest Amazon Linux 2023 AMI ID for this region\n$ aws ec2 run-instances \\\n    --image-id resolve:ssm:/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64 \\\n    --instance-type t3.micro \\\n    --count 1 \\\n    --key-name practice-key \\\n    --security-group-ids sg-0123456789abcdef0 \\\n    --user-data file://user-data.sh \\\n    --metadata-options HttpTokens=required \\\n    --tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=web-01},{Key=Project,Value=practice}]' \\\n    --query 'Instances[0].InstanceId' --output text\ni-0abc1234def567890\n\n# 5. Wait, find the public IP, connect\n$ aws ec2 wait instance-running --instance-ids i-0abc1234def567890\n$ aws ec2 describe-instances --instance-ids i-0abc1234def567890 \\\n    --query 'Reservations[0].Instances[0].PublicIpAddress' --output text\n198.51.100.7\n$ ssh -i practice-key.pem ec2-user@198.51.100.7\n$ curl http://198.51.100.7            # nginx welcome page once user data has finished</code></pre>\n<p><code>HttpTokens=required</code> forces <b>IMDSv2</b>, the safer version of the instance metadata service that hands out the role's credentials. Without <code>--subnet-id</code>, the instance goes into a default subnet of the default VPC, which gives it a public IP. Instead of SSH you can use <b>EC2 Instance Connect</b> or <b>Session Manager</b> in the console; Session Manager needs no open port 22 at all, just the SSM agent (preinstalled on Amazon Linux) and an instance role with the <code>AmazonSSMManagedInstanceCore</code> policy.</p>\n\n<h4>Stop, terminate and Elastic IPs</h4>\n<div class=\"learn-table-wrap\"><table class=\"learn-table\"><thead><tr><th></th><th>Stop</th><th>Terminate</th></tr></thead><tbody>\n<tr><td>What happens</td><td>The VM is shut down but kept; start it again any time</td><td>The VM is deleted permanently</td></tr>\n<tr><td>Compute charges</td><td>None while stopped</td><td>None</td></tr>\n<tr><td>EBS volumes</td><td>Kept, and still billed</td><td>Root volume deleted by default; volumes attached later are kept by default (and still billed)</td></tr>\n<tr><td>Public IPv4</td><td>Released; a new one is given on start</td><td>Released</td></tr>\n<tr><td>Instance store data</td><td>Lost</td><td>Lost</td></tr>\n</tbody></table></div>\n<p>The CLI equivalents are <code>aws ec2 stop-instances</code>, <code>start-instances</code> and <code>terminate-instances</code>, each with <code>--instance-ids</code>. Launch with <code>--disable-api-termination</code> (termination protection) for instances that must never be deleted by accident. An <b>Elastic IP</b> is a static public IPv4 address that stays in your account until you release it, so a server keeps the same address across stops:</p>\n<pre><code>$ aws ec2 allocate-address --domain vpc --query 'AllocationId' --output text\neipalloc-0a1b2c3d4e5f67890\n$ aws ec2 associate-address --instance-id i-0abc1234def567890 --allocation-id eipalloc-0a1b2c3d4e5f67890\n$ aws ec2 release-address --allocation-id eipalloc-0a1b2c3d4e5f67890   # when you no longer need it</code></pre>\n<p>AWS charges by the hour for every public IPv4 address, attached or idle, so release Elastic IPs you don't use. For real websites, a load balancer or DNS name in front of the servers usually beats pinning one IP.</p>\n\n<h4>Containers on AWS: ECR, ECS and EKS</h4>\n<p>Images live in <b>ECR</b> (Elastic Container Registry), which works like any registry after a login:</p>\n<pre><code>$ aws ecr create-repository --repository-name practice-app\n$ aws ecr get-login-password --region eu-central-1 | docker login --username AWS \\\n    --password-stdin 123456789012.dkr.ecr.eu-central-1.amazonaws.com\n$ docker tag practice-app:1.0 123456789012.dkr.ecr.eu-central-1.amazonaws.com/practice-app:1.0\n$ docker push 123456789012.dkr.ecr.eu-central-1.amazonaws.com/practice-app:1.0</code></pre>\n<p>To run them, AWS offers two orchestrators:</p>\n<ul>\n<li><b>ECS</b> (Elastic Container Service): AWS's own, simpler orchestrator. A <b>task definition</b> (JSON) describes the containers: image, CPU and memory, ports, environment variables, log settings and an IAM <b>task role</b>. A <b>task</b> is a running copy; a <b>service</b> keeps N tasks running behind a load balancer and does rolling deployments.</li>\n<li><b>EKS</b> (Elastic Kubernetes Service): real Kubernetes with AWS running the control plane. You use <code>kubectl</code> and everything from the Kubernetes topic; it's portable, but there's an hourly charge per cluster on top of the worker capacity, and more to learn.</li>\n</ul>\n<p>Both need somewhere for the containers to run:</p>\n<ul>\n<li><b>Fargate</b>: serverless. You set CPU and memory per task and AWS supplies the machine, with no instances to patch or scale; you pay per second for what each task requests, and can't reach the host.</li>\n<li><b>EC2 launch type</b>: containers run on EC2 instances you manage (usually in an Auto Scaling group). More work, more control (GPUs, special types, per-host daemons), often cheaper for large steady workloads.</li>\n<li><b>ECS Managed Instances</b> (launched in 2025) sits in between: EC2 instances in your account that AWS provisions, patches and scales for you. On EKS, <b>Auto Mode</b> plays a similar role.</li>\n</ul>\n\n<h4>Lambda in practice</h4>\n<p>A Lambda function is code plus a <b>handler</b>, the function Lambda calls for each event:</p>\n<pre><code># lambda_function.py\nimport json\n\ndef lambda_handler(event, context):\n    name = event.get(\"name\", \"world\")\n    return {\"statusCode\": 200, \"body\": json.dumps({\"message\": f\"Hello, {name}!\"})}</code></pre>\n<pre><code>$ zip function.zip lambda_function.py\n$ aws lambda create-function --function-name hello \\\n    --runtime python3.13 --handler lambda_function.lambda_handler \\\n    --zip-file fileb://function.zip \\\n    --role arn:aws:iam::123456789012:role/hello-lambda-role \\\n    --timeout 10 --memory-size 256\n$ aws lambda invoke --function-name hello \\\n    --cli-binary-format raw-in-base64-out --payload '{\"name\": \"Demee\"}' response.json\n$ cat response.json\n{\"statusCode\": 200, \"body\": \"{\\\"message\\\": \\\"Hello, Demee!\\\"}\"}</code></pre>\n<p>The handler setting is <code>file_name.function_name</code>. The <b>execution role</b> must at least allow writing logs (the AWS managed policy <code>AWSLambdaBasicExecutionRole</code>); output from <code>print</code> goes to CloudWatch Logs in the log group <code>/aws/lambda/hello</code>. A <b>trigger</b> decides what calls the function: an HTTP request through API Gateway or a function URL, a file landing in S3, a message on an SQS queue, a schedule in EventBridge Scheduler, a change in a DynamoDB table.</p>\n<p>Limits worth knowing (check the Lambda quotas page, they change): the <b>timeout</b> defaults to 3 seconds and can be raised to at most <b>15 minutes</b> (900 seconds); <b>memory</b> is set from 128 MB to 10,240 MB, and CPU power grows in proportion to it, so more memory often makes a function faster; <code>/tmp</code> gives 512 MB of scratch space by default, configurable up to 10,240 MB. New accounts start with lower concurrency and memory quotas that AWS raises with usage. You pay per request and per GB-second of run time.</p>\n<p>A <b>cold start</b> happens when Lambda must create a new execution environment: download your code, start the runtime and run the code outside the handler. It adds latency to that one request; later requests reuse the warm environment. To reduce it: keep the package and its dependencies small, create clients (database connections, SDK clients) <b>outside</b> the handler so warm calls reuse them, and for latency-sensitive functions use <b>provisioned concurrency</b> (paid, pre-warmed environments) or <b>SnapStart</b> (available for Java, Python and .NET).</p>\n\n<h4>Which one to pick</h4>\n<figure class=\"learn-diagram dg\" data-dg=\"cloud-compute\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 190\" role=\"img\" aria-label=\"AWS compute options from most control to least to manage: EC2, EKS, ECS on Fargate, Lambda\" style=\"--dgw:680px\"><defs><marker id=\"cloud-compute--hi\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk hi\" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"b\" x=\"10\" y=\"40\" width=\"150\" height=\"60\" rx=\"6\"/><text class=\"tb\" x=\"85\" y=\"66.7\" text-anchor=\"middle\" font-size=\"13\">EC2</text><text class=\"t2\" x=\"85\" y=\"82.0\" text-anchor=\"middle\" font-size=\"11\">a whole VM</text><rect class=\"b\" x=\"180\" y=\"40\" width=\"150\" height=\"60\" rx=\"6\"/><text class=\"tb\" x=\"255\" y=\"66.7\" text-anchor=\"middle\" font-size=\"13\">EKS</text><text class=\"t2\" x=\"255\" y=\"82.0\" text-anchor=\"middle\" font-size=\"11\">Kubernetes</text><rect class=\"b hi\" x=\"350\" y=\"40\" width=\"150\" height=\"60\" rx=\"6\"/><text class=\"tb ta\" x=\"425\" y=\"66.7\" text-anchor=\"middle\" font-size=\"13\">ECS Fargate</text><text class=\"t2\" x=\"425\" y=\"82.0\" text-anchor=\"middle\" font-size=\"11\">just containers</text><rect class=\"b ok\" x=\"520\" y=\"40\" width=\"150\" height=\"60\" rx=\"6\"/><text class=\"tb\" x=\"595\" y=\"66.7\" text-anchor=\"middle\" font-size=\"13\">Lambda</text><text class=\"t2\" x=\"595\" y=\"82.0\" text-anchor=\"middle\" font-size=\"11\">just a function</text><path class=\"ln hi\" d=\"M20,130 L650,130\" marker-end=\"url(#cloud-compute--hi)\"/><text class=\"t2\" x=\"20\" y=\"154\" text-anchor=\"start\" font-size=\"12\">more control, more to look after</text><text class=\"t2\" x=\"650\" y=\"154\" text-anchor=\"end\" font-size=\"12\">less to manage, more limits</text><text class=\"t2\" x=\"340\" y=\"180\" text-anchor=\"middle\" font-size=\"11\">you patch the OS only on the far left; Lambda has a 15-minute limit</text></svg></div><figcaption>Start from the right and move left only when you hit a limit. Every step left buys control and costs you patching, scaling and security work.</figcaption></figure>\n\n<div class=\"learn-table-wrap\"><table class=\"learn-table\"><thead><tr><th>Option</th><th>Pick it when</th><th>Watch out for</th></tr></thead><tbody>\n<tr><td>EC2</td><td>You need full control of the OS, run legacy or stateful software, or are learning Linux servers</td><td>You patch, secure, back up and scale it yourself</td></tr>\n<tr><td>ECS on Fargate</td><td>You have containers and want the least operations work</td><td>Per-task pricing adds up for large steady fleets; no host access</td></tr>\n<tr><td>EKS</td><td>Your team already runs Kubernetes, or needs its ecosystem and portability</td><td>Cluster fee, and Kubernetes' complexity</td></tr>\n<tr><td>Lambda</td><td>Short, event-driven tasks, spiky or low traffic, glue between services</td><td>15-minute limit, cold starts, harder local testing, cost at very high steady volume</td></tr>\n</tbody></table></div>\n\n<h4>Common errors and fixes</h4>\n<ul>\n<li><b>SSH hangs, then \"Connection timed out\"</b>: the security group doesn't allow port 22 from your current IP (it changes on home and mobile networks), or the instance has no public IP or its subnet has no route to an internet gateway.</li>\n<li><b>\"Permission denied (publickey)\"</b>: wrong user name for the AMI, or the wrong key. <b>\"UNPROTECTED PRIVATE KEY FILE!\"</b>: run <code>chmod 400</code> on the <code>.pem</code>.</li>\n<li><b>User data did nothing</b>: missing <code>#!/bin/bash</code> first line, or you edited it after the first boot (it only runs once). Read <code>/var/log/cloud-init-output.log</code>.</li>\n<li><b>An error that the instance type's architecture doesn't match the AMI's</b>: an x86_64 AMI on a Graviton (<code>g</code>) type or the reverse. Use the <code>arm64</code> AMI for Graviton.</li>\n<li><code>VcpuLimitExceeded</code>: new accounts have low vCPU quotas. Use a smaller type or request an increase in Service Quotas.</li>\n<li><b>Lambda \"Task timed out after 3.00 seconds\"</b>: the default timeout is 3 seconds; raise it with <code>aws lambda update-function-configuration --function-name hello --timeout 30</code>, and check the function isn't waiting on a network call that can never succeed (for example a function in a private subnet with no NAT).</li>\n</ul>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=OGYEXGy8ca4&amp;t=791s\" target=\"_blank\" rel=\"noopener noreferrer\">Be A Better Dev · AWS Explained <span class=\"learn-sources-part\">· Compute services (13:11)</span></a><a href=\"https://www.youtube.com/watch?v=OGYEXGy8ca4&amp;t=957s\" target=\"_blank\" rel=\"noopener noreferrer\">Be A Better Dev · AWS Explained <span class=\"learn-sources-part\">· Container services (15:57)</span></a><a href=\"https://www.youtube.com/watch?v=OGYEXGy8ca4&amp;t=1080s\" target=\"_blank\" rel=\"noopener noreferrer\">Be A Better Dev · AWS Explained <span class=\"learn-sources-part\">· Serverless compute (18:00)</span></a><a href=\"https://www.youtube.com/watch?v=ZaA0kNm18pE&amp;t=1420s\" target=\"_blank\" rel=\"noopener noreferrer\">Be A Better Dev · Cloud Computing Explained <span class=\"learn-sources-part\">· Container orchestration (23:40)</span></a></div>","cloud/cloud-networking-security":"\n<p class=\"learn-lead\">The Networking topic showed what a VPC looks like: public and private subnets, an internet gateway, a NAT gateway, security groups. This chapter builds one step by step, compares the two AWS firewalls properly, and then covers the other half of cloud security: IAM permissions, secrets and encryption.</p>\n\n<h4>A VPC, piece by piece</h4>\n<p>A <b>VPC</b> belongs to one region and has an IPv4 range such as <code>10.0.0.0/16</code> (65,536 addresses). You split it into <b>subnets</b>, and each subnet lives in exactly <b>one availability zone</b>, so a highly available design has at least one public and one private subnet in each of two or more AZs. AWS reserves five addresses in every subnet (the first four and the last), so a <code>/24</code> gives 251 usable IPs, not 256. Every region also has a <b>default VPC</b> (<code>172.31.0.0/16</code>) with a public subnet in each AZ: fine for experiments, but real setups create their own.</p>\n<p>What makes a subnet \"public\" is nothing more than its <b>route table</b>. Each subnet is associated with one; the <code>local</code> route (traffic inside the VPC) is always there:</p>\n<div class=\"learn-table-wrap\"><table class=\"learn-table\"><thead><tr><th>Route table</th><th>Destination</th><th>Target</th></tr></thead><tbody>\n<tr><td rowspan=\"2\">Public</td><td><code>10.0.0.0/16</code></td><td><code>local</code></td></tr>\n<tr><td><code>0.0.0.0/0</code></td><td>Internet gateway (<code>igw-…</code>)</td></tr>\n<tr><td rowspan=\"2\">Private</td><td><code>10.0.0.0/16</code></td><td><code>local</code></td></tr>\n<tr><td><code>0.0.0.0/0</code></td><td>NAT gateway (<code>nat-…</code>), or no default route at all</td></tr>\n</tbody></table></div>\n<p>An instance in a public subnet also needs a public IP to be reachable. Building a VPC with the CLI shows every piece (in practice you'd write this in Terraform):</p>\n<pre><code>$ aws ec2 create-vpc --cidr-block 10.0.0.0/16 --query 'Vpc.VpcId' --output text\nvpc-0a1b2c3d4e5f67890\n$ aws ec2 create-subnet --vpc-id vpc-0a1b2c3d4e5f67890 --cidr-block 10.0.1.0/24 \\\n    --availability-zone eu-central-1a --query 'Subnet.SubnetId' --output text\nsubnet-0aaa1111bbbb22223\n$ aws ec2 create-internet-gateway --query 'InternetGateway.InternetGatewayId' --output text\nigw-0fedcba9876543210\n$ aws ec2 attach-internet-gateway --internet-gateway-id igw-0fedcba9876543210 \\\n    --vpc-id vpc-0a1b2c3d4e5f67890\n$ aws ec2 create-route-table --vpc-id vpc-0a1b2c3d4e5f67890 --query 'RouteTable.RouteTableId' --output text\nrtb-0123abcd4567ef890\n$ aws ec2 create-route --route-table-id rtb-0123abcd4567ef890 \\\n    --destination-cidr-block 0.0.0.0/0 --gateway-id igw-0fedcba9876543210\n$ aws ec2 associate-route-table --route-table-id rtb-0123abcd4567ef890 \\\n    --subnet-id subnet-0aaa1111bbbb22223\n$ aws ec2 modify-subnet-attribute --subnet-id subnet-0aaa1111bbbb22223 --map-public-ip-on-launch</code></pre>\n\n<h4>Internet gateway, NAT gateway and VPC endpoints</h4>\n<ul>\n<li>An <b>internet gateway</b> is attached to the VPC and allows traffic both ways for resources that have public IPs. It has no charge of its own.</li>\n<li>A <b>NAT gateway</b> lets private resources start connections <i>out</i> (to download updates or call an external API) while nothing on the internet can connect <i>in</i>. The classic <b>zonal</b> NAT gateway lives in a public subnet of one AZ with an Elastic IP, so for high availability you create one per AZ. Since late 2025 there's also a <b>regional</b> mode: one NAT gateway that spreads across the AZs where you have workloads and needs no public subnet. Either way, NAT gateways are billed per hour <i>and</i> per GB processed, a classic source of surprise bills.</li>\n<li><b>VPC endpoints</b> let private subnets reach AWS services without going through NAT or the internet. <b>Gateway endpoints</b> exist for S3 and DynamoDB and have no extra charge; <b>interface endpoints</b> (PrivateLink) cover most other services and cost per hour per AZ.</li>\n</ul>\n\n<h4>Security groups vs network ACLs</h4>\n<div class=\"learn-table-wrap\"><table class=\"learn-table\"><thead><tr><th></th><th>Security group</th><th>Network ACL</th></tr></thead><tbody>\n<tr><td>Attached to</td><td>A network interface (an instance, load balancer, database…)</td><td>A subnet: applies to everything in it</td></tr>\n<tr><td>State</td><td><b>Stateful</b>: if a request is allowed in, its reply is allowed out automatically</td><td><b>Stateless</b>: replies must be allowed separately, usually by opening ephemeral ports 1024-65535</td></tr>\n<tr><td>Rule types</td><td>Allow only</td><td>Allow and deny</td></tr>\n<tr><td>Evaluation</td><td>All rules are considered together</td><td>Rules in number order, lowest first; the first match wins</td></tr>\n<tr><td>Default</td><td>A new group: no inbound, all outbound allowed</td><td>The default NACL allows everything; a new custom NACL denies everything until you add rules</td></tr>\n<tr><td>Can reference</td><td>IP ranges <b>and other security groups</b></td><td>IP ranges only</td></tr>\n<tr><td>Typical use</td><td>The main firewall for every resource</td><td>A coarse extra layer, for example blocking an abusive IP range</td></tr>\n</tbody></table></div>\n<p>Referencing security groups is the key idea for layered apps. \"The database accepts PostgreSQL only from members of the app servers' group\" keeps working however many app servers come and go:</p>\n<pre><code>$ aws ec2 authorize-security-group-ingress --group-id sg-0d1e2f3a4b5c6d7e8 \\\n    --protocol tcp --port 5432 --source-group sg-0a1b2c3d4e5f6a7b8     # db group, app group</code></pre>\n\n<h4>IAM: who can do what</h4>\n<p>Every AWS API call, from the console, the CLI or code, is checked by <b>IAM</b> (Identity and Access Management). The pieces:</p>\n<ul>\n<li><b>Root user</b>: the email address that created the account. It can do everything, including closing the account, and can't be restricted by IAM policies.</li>\n<li><b>IAM users</b>: long-term identities with a password and/or access keys. For people, AWS now recommends <b>IAM Identity Center</b> (single sign-on with short-lived credentials) over IAM users where possible.</li>\n<li><b>Groups</b>: collections of users that share policies (\"developers\", \"admins\"). Attach permissions to groups, not to individual users.</li>\n<li><b>Roles</b>: identities with no password or keys of their own. Someone or something <b>assumes</b> a role and gets temporary credentials. EC2 instances, Lambda functions, ECS tasks, CI pipelines and users from other accounts all use roles.</li>\n<li><b>Policies</b>: JSON documents listing what is allowed or denied. <b>Identity-based</b> policies attach to users, groups and roles; <b>resource-based</b> policies attach to a resource, such as an S3 bucket policy.</li>\n</ul>\n<p>A policy that lets an app read and write objects in one bucket, and nothing else:</p>\n<pre><code>{\n  \"Version\": \"2012-10-17\",\n  \"Statement\": [\n    {\n      \"Sid\": \"ListTheBucket\",\n      \"Effect\": \"Allow\",\n      \"Action\": \"s3:ListBucket\",\n      \"Resource\": \"arn:aws:s3:::demee-practice-assets\"\n    },\n    {\n      \"Sid\": \"ReadWriteObjects\",\n      \"Effect\": \"Allow\",\n      \"Action\": [\"s3:GetObject\", \"s3:PutObject\"],\n      \"Resource\": \"arn:aws:s3:::demee-practice-assets/*\"\n    }\n  ]\n}</code></pre>\n<ul>\n<li><code>\"Version\": \"2012-10-17\"</code> is the policy language version, not today's date. Always use exactly this value.</li>\n<li>Each <b>statement</b> has an <code>Effect</code> (Allow or Deny), <code>Action</code>s in the form <code>service:Operation</code>, and the <code>Resource</code>s they apply to, as ARNs (Amazon Resource Names). <code>Sid</code> is just a label.</li>\n<li>Listing is an action on the <b>bucket</b> (<code>arn:aws:s3:::bucket</code>), while reading and writing are actions on <b>objects</b> (<code>arn:aws:s3:::bucket/*</code>). Mixing these two up is the most common reason an S3 policy \"doesn't work\".</li>\n</ul>\n<p>How AWS decides: everything is <b>denied by default</b>; an <b>Allow</b> in any applicable policy permits the action; an explicit <b>Deny</b> anywhere always wins over any Allow. A role also has a <b>trust policy</b> saying who may assume it. This one lets EC2 instances use the role:</p>\n<pre><code>{\n  \"Version\": \"2012-10-17\",\n  \"Statement\": [\n    {\n      \"Effect\": \"Allow\",\n      \"Principal\": { \"Service\": \"ec2.amazonaws.com\" },\n      \"Action\": \"sts:AssumeRole\"\n    }\n  ]\n}</code></pre>\n\n<h4>Least privilege, MFA and the root account</h4>\n<p><b>Least privilege</b> means every identity gets only the actions and resources it needs. Start with AWS managed policies while learning, then narrow them down; IAM Access Analyzer can generate a policy from the actions a role actually used. Protect the root user above everything else: turn on <b>MFA</b> (AWS now requires it for root users on all account types), never create access keys for it, and use it only for the few tasks that need it, such as changing account settings or closing the account. Day to day, sign in as an admin user or Identity Center user that also has MFA. If root is compromised, everything is.</p>\n\n<h4>Access keys vs roles</h4>\n<p>An <b>access key</b> (an ID starting <code>AKIA</code> plus a secret) is a long-lived password for the API. It works from anywhere until someone deletes it, so a key pasted into code and pushed to a public GitHub repository can be found and abused within minutes, typically to launch crypto-mining instances on your bill. A <b>role</b> hands out temporary credentials (IDs starting <code>ASIA</code>, plus a session token) that expire on their own. The rule: <b>code running in AWS uses a role</b> (EC2 instance profile, Lambda execution role, ECS task role), and <b>CI pipelines use OIDC</b> (for example GitHub Actions assuming a role) instead of stored keys. Creating a role for EC2 from the trust policy above:</p>\n<pre><code>$ aws iam create-role --role-name web-server-role --assume-role-policy-document file://trust.json\n$ aws iam attach-role-policy --role-name web-server-role \\\n    --policy-arn arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore</code></pre>\n<p>EC2 receives a role through an <b>instance profile</b>, a wrapper the console creates for you when you pick the role at launch (with the CLI: <code>create-instance-profile</code>, <code>add-role-to-instance-profile</code>, then <code>aws ec2 associate-iam-instance-profile</code>).</p>\n\n<h4>Secrets: Secrets Manager and Parameter Store</h4>\n<p>Database passwords and API tokens don't belong in code, AMIs, user data or environment variables baked into images. AWS has two places for them, and your app reads them at start-up using its role:</p>\n<ul>\n<li><b>Systems Manager Parameter Store</b>: key-value configuration in a path hierarchy; the <code>SecureString</code> type is encrypted with KMS. Standard parameters have no extra charge. Good for config and simple secrets.</li>\n<li><b>Secrets Manager</b>: built for secrets, with <b>automatic rotation</b> (for example changing an RDS password on a schedule) and cross-account sharing. Charged per secret per month and per API call.</li>\n</ul>\n<pre><code>$ aws ssm put-parameter --name /practice/db/password --type SecureString --value 'S3cure-Example'\n$ aws ssm get-parameter --name /practice/db/password --with-decryption \\\n    --query 'Parameter.Value' --output text\n$ aws secretsmanager get-secret-value --secret-id practice/db \\\n    --query 'SecretString' --output text</code></pre>\n<p>Values typed on the command line end up in your shell history; for real secrets, use <code>--value file://secret.txt</code> or let the service generate them (RDS can keep its master password in Secrets Manager for you).</p>\n\n<h4>Encryption at rest and in transit</h4>\n<p><b>At rest</b> means stored data is encrypted on disk. AWS services use <b>KMS</b> (Key Management Service) keys for this: either AWS managed keys (named like <code>aws/s3</code>, <code>aws/ebs</code>) or <b>customer managed keys</b> you create, which let you control who may use the key, see its use in CloudTrail and disable it. S3 encrypts every new object by default. EBS encryption can be switched on by default per region (<code>aws ec2 enable-ebs-encryption-by-default</code>). RDS encryption has to be chosen when the database is created. <b>In transit</b> means TLS on every connection (see the TLS chapter in Networking): HTTPS on load balancers with free certificates from <b>ACM</b> (AWS Certificate Manager), TLS to databases, and S3 bucket policies that deny requests where <code>aws:SecureTransport</code> is false.</p>\n\n<h4>A typical three-tier layout</h4>\n<figure class=\"learn-diagram dg\" data-dg=\"cloud-3tier\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 400\" role=\"img\" aria-label=\"A three-tier VPC across two availability zones: public subnets hold the load balancer and NAT, private app subnets hold the app servers, private data subnets hold the RDS primary and standby\" style=\"--dgw:680px\"><defs><marker id=\"cloud-3tier--hi\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk hi\" d=\"M0,0 L8,4 L0,8 z\"/></marker><marker id=\"cloud-3tier--ok\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk ok\" d=\"M0,0 L8,4 L0,8 z\"/></marker><marker id=\"cloud-3tier--ok--s\" markerWidth=\"9\" markerHeight=\"9\" refX=\"1\" refY=\"4\" orient=\"auto\"><path class=\"mk ok\" d=\"M8,0 L0,4 L8,8 z\"/></marker><marker id=\"cloud-3tier--warn\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk warn\" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"b warn\" x=\"250\" y=\"6\" width=\"180\" height=\"36\" rx=\"6\"/><text class=\"tb\" x=\"340\" y=\"27.8\" text-anchor=\"middle\" font-size=\"12\">internet gateway</text><rect class=\"g hi\" x=\"10\" y=\"52\" width=\"660\" height=\"340\" rx=\"8\"/><text class=\"tg hi\" x=\"20\" y=\"68\" font-size=\"11\">VPC 10.0.0.0/16</text><text class=\"tb\" x=\"178\" y=\"84\" text-anchor=\"middle\" font-size=\"12\">AZ a</text><text class=\"tb\" x=\"502\" y=\"84\" text-anchor=\"middle\" font-size=\"12\">AZ b</text><rect class=\"g\" x=\"26\" y=\"96\" width=\"304\" height=\"76\" rx=\"8\"/><text class=\"tg \" x=\"36\" y=\"112\" font-size=\"11\">public</text><rect class=\"b warn\" x=\"86\" y=\"122\" width=\"184\" height=\"40\" rx=\"6\"/><text class=\"tb\" x=\"178\" y=\"145.8\" text-anchor=\"middle\" font-size=\"12\">ALB + NAT</text><rect class=\"g\" x=\"350\" y=\"96\" width=\"304\" height=\"76\" rx=\"8\"/><text class=\"tg \" x=\"360\" y=\"112\" font-size=\"11\">public</text><rect class=\"b warn\" x=\"410\" y=\"122\" width=\"184\" height=\"40\" rx=\"6\"/><text class=\"tb\" x=\"502\" y=\"145.8\" text-anchor=\"middle\" font-size=\"12\">ALB + NAT</text><rect class=\"g\" x=\"26\" y=\"196\" width=\"304\" height=\"76\" rx=\"8\"/><text class=\"tg \" x=\"36\" y=\"212\" font-size=\"11\">private app</text><rect class=\"b hi\" x=\"86\" y=\"222\" width=\"184\" height=\"40\" rx=\"6\"/><text class=\"tb ta\" x=\"178\" y=\"245.8\" text-anchor=\"middle\" font-size=\"12\">app (EC2/ECS)</text><rect class=\"g\" x=\"350\" y=\"196\" width=\"304\" height=\"76\" rx=\"8\"/><text class=\"tg \" x=\"360\" y=\"212\" font-size=\"11\">private app</text><rect class=\"b hi\" x=\"410\" y=\"222\" width=\"184\" height=\"40\" rx=\"6\"/><text class=\"tb ta\" x=\"502\" y=\"245.8\" text-anchor=\"middle\" font-size=\"12\">app (EC2/ECS)</text><rect class=\"g\" x=\"26\" y=\"296\" width=\"304\" height=\"76\" rx=\"8\"/><text class=\"tg \" x=\"36\" y=\"312\" font-size=\"11\">private data</text><rect class=\"b ok\" x=\"86\" y=\"322\" width=\"184\" height=\"40\" rx=\"6\"/><text class=\"tb\" x=\"178\" y=\"345.8\" text-anchor=\"middle\" font-size=\"12\">RDS primary</text><rect class=\"g\" x=\"350\" y=\"296\" width=\"304\" height=\"76\" rx=\"8\"/><text class=\"tg \" x=\"360\" y=\"312\" font-size=\"11\">private data</text><rect class=\"b ok\" x=\"410\" y=\"322\" width=\"184\" height=\"40\" rx=\"6\"/><text class=\"tb\" x=\"502\" y=\"345.8\" text-anchor=\"middle\" font-size=\"12\">RDS standby</text><path class=\"ln warn\" d=\"M320,44 L200,120\" marker-end=\"url(#cloud-3tier--warn)\"/><path class=\"ln warn\" d=\"M360,44 L480,120\" marker-end=\"url(#cloud-3tier--warn)\"/><text class=\"warn\" x=\"340\" y=\"66\" text-anchor=\"middle\" font-size=\"10\">80/443</text><path class=\"ln hi\" d=\"M178,164 L178,220\" marker-end=\"url(#cloud-3tier--hi)\"/><path class=\"ln ok\" d=\"M178,264 L178,320\" marker-end=\"url(#cloud-3tier--ok)\"/><path class=\"ln hi\" d=\"M502,164 L502,220\" marker-end=\"url(#cloud-3tier--hi)\"/><path class=\"ln ok\" d=\"M502,264 L502,320\" marker-end=\"url(#cloud-3tier--ok)\"/><text class=\"ta\" x=\"190\" y=\"188\" text-anchor=\"start\" font-size=\"10\">only from the LB</text><text class=\"ok\" x=\"190\" y=\"288\" text-anchor=\"start\" font-size=\"10\">5432 only from the app tier</text><path class=\"ln ok\" d=\"M272,342 L408,342\" marker-end=\"url(#cloud-3tier--ok)\" marker-start=\"url(#cloud-3tier--ok--s)\"/><text class=\"ok\" x=\"340\" y=\"334\" text-anchor=\"middle\" font-size=\"11\">sync</text></svg></div><figcaption>Each tier only accepts traffic from the tier above it. Nothing but the load balancer has a public address, and the database has no route to the internet at all.</figcaption></figure>\n\n<p>Picture a VPC spread over two AZs, each with three subnets. The <b>public tier</b> holds only an Application Load Balancer (and zonal NAT gateways, if used); its security group accepts 80 and 443 from the internet. The <b>app tier</b> sits in private subnets: EC2 instances in an Auto Scaling group, or ECS tasks, whose security group accepts traffic only from the load balancer's group; they reach the internet outbound through NAT and reach S3 through a gateway endpoint. The <b>data tier</b> is a further set of private subnets with no route to the internet at all, holding a Multi-AZ RDS database whose security group accepts port 5432 only from the app tier's group. Nothing but the load balancer has a public IP; admins connect with Session Manager instead of SSH through a bastion; the app reads its database password from Secrets Manager using its role; and every tier keeps working if one AZ fails.</p>\n\n<h4>Common mistakes</h4>\n<ul>\n<li><b>SSH or databases open to <code>0.0.0.0/0</code></b>. Bots scan the whole internet constantly. Restrict to your IP, use security-group references, or use Session Manager.</li>\n<li><b>Private instances can't install packages</b>: the private route table has no <code>0.0.0.0/0</code> route to a NAT gateway (or the NAT gateway itself sits in a private subnet).</li>\n<li><b>A custom network ACL breaks everything</b>: it's stateless, so without an outbound rule for ports 1024-65535 the replies never leave.</li>\n<li><code>AccessDenied</code> / <code>UnauthorizedOperation</code> \"is not authorized to perform\": read the message; it names the identity, the action and the resource. Check for an explicit Deny, bucket vs object ARNs, and the region.</li>\n<li><b>Access keys in code, <code>.env</code> files committed to Git, or on EC2 instances</b>. Use roles; if a key leaks, deactivate and delete it immediately, then check CloudTrail and your bill in every region.</li>\n</ul>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=OGYEXGy8ca4&amp;t=3553s\" target=\"_blank\" rel=\"noopener noreferrer\">Be A Better Dev · AWS Explained <span class=\"learn-sources-part\">· Identity management (59:13)</span></a><a href=\"https://www.youtube.com/watch?v=OGYEXGy8ca4&amp;t=3753s\" target=\"_blank\" rel=\"noopener noreferrer\">Be A Better Dev · AWS Explained <span class=\"learn-sources-part\">· Networking (1:02:33)</span></a><a href=\"https://www.youtube.com/watch?v=OGYEXGy8ca4&amp;t=1303s\" target=\"_blank\" rel=\"noopener noreferrer\">Be A Better Dev · AWS Explained <span class=\"learn-sources-part\">· Configuration and secrets (21:43)</span></a><a href=\"https://www.youtube.com/watch?v=ZaA0kNm18pE&amp;t=2480s\" target=\"_blank\" rel=\"noopener noreferrer\">Be A Better Dev · Cloud Computing Explained <span class=\"learn-sources-part\">· Cloud networks (41:20)</span></a></div>","cloud/storage-databases-in-the-cloud":"\n<p class=\"learn-lead\">The AWS chapter introduced object, block and file storage and the difference between availability and durability. This chapter goes deeper: how S3 is organised and secured, which storage class to use, lifecycle rules, backups and snapshots, and how the managed databases (RDS, Aurora and DynamoDB) differ, with the AWS CLI commands you'll use daily.</p>\n\n<h4>Block, file and object compared</h4>\n<figure class=\"learn-diagram dg\" data-dg=\"cloud-storage\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 220\" role=\"img\" aria-label=\"Three kinds of storage: EBS is a block disk for one instance, EFS is a shared file system for many instances, S3 stores objects reached over HTTP by anything\" style=\"--dgw:680px\"><defs><marker id=\"cloud-storage--ok\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk ok\" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"b\" x=\"10\" y=\"10\" width=\"204\" height=\"112\" rx=\"6\"/><text class=\"tb\" x=\"112\" y=\"49.3\" text-anchor=\"middle\" font-size=\"18\">EBS</text><text class=\"t2\" x=\"112\" y=\"65.5\" text-anchor=\"middle\" font-size=\"11\">block: a disk</text><text class=\"t2\" x=\"112\" y=\"80.5\" text-anchor=\"middle\" font-size=\"11\">for one instance</text><text class=\"t2\" x=\"112\" y=\"95.5\" text-anchor=\"middle\" font-size=\"11\">lives in one AZ</text><rect class=\"b\" x=\"238\" y=\"10\" width=\"204\" height=\"112\" rx=\"6\"/><text class=\"tb\" x=\"340\" y=\"49.3\" text-anchor=\"middle\" font-size=\"18\">EFS</text><text class=\"t2\" x=\"340\" y=\"65.5\" text-anchor=\"middle\" font-size=\"11\">file: a shared</text><text class=\"t2\" x=\"340\" y=\"80.5\" text-anchor=\"middle\" font-size=\"11\">NFS folder for</text><text class=\"t2\" x=\"340\" y=\"95.5\" text-anchor=\"middle\" font-size=\"11\">many instances</text><rect class=\"b hi\" x=\"466\" y=\"10\" width=\"204\" height=\"112\" rx=\"6\"/><text class=\"tb ta\" x=\"568\" y=\"49.3\" text-anchor=\"middle\" font-size=\"18\">S3</text><text class=\"t2\" x=\"568\" y=\"65.5\" text-anchor=\"middle\" font-size=\"11\">object: files over</text><text class=\"t2\" x=\"568\" y=\"80.5\" text-anchor=\"middle\" font-size=\"11\">an HTTP API, for</text><text class=\"t2\" x=\"568\" y=\"95.5\" text-anchor=\"middle\" font-size=\"11\">anything, anywhere</text><rect class=\"b ok\" x=\"62\" y=\"166\" width=\"100\" height=\"40\" rx=\"6\"/><text class=\"tb\" x=\"112\" y=\"189.8\" text-anchor=\"middle\" font-size=\"12\">EC2</text><path class=\"ln ok\" d=\"M112,164 L112,124\" marker-end=\"url(#cloud-storage--ok)\"/><rect class=\"b ok\" x=\"254\" y=\"170\" width=\"56\" height=\"34\" rx=\"6\"/><text class=\"tb\" x=\"282\" y=\"190.5\" text-anchor=\"middle\" font-size=\"11\">EC2</text><path class=\"ln ok\" d=\"M282,168 L280,124\" marker-end=\"url(#cloud-storage--ok)\"/><rect class=\"b ok\" x=\"318\" y=\"170\" width=\"56\" height=\"34\" rx=\"6\"/><text class=\"tb\" x=\"346\" y=\"190.5\" text-anchor=\"middle\" font-size=\"11\">EC2</text><path class=\"ln ok\" d=\"M346,168 L310,124\" marker-end=\"url(#cloud-storage--ok)\"/><rect class=\"b ok\" x=\"382\" y=\"170\" width=\"56\" height=\"34\" rx=\"6\"/><text class=\"tb\" x=\"410\" y=\"190.5\" text-anchor=\"middle\" font-size=\"11\">EC2</text><path class=\"ln ok\" d=\"M410,168 L340,124\" marker-end=\"url(#cloud-storage--ok)\"/><rect class=\"b ok\" x=\"480\" y=\"166\" width=\"190\" height=\"40\" rx=\"6\"/><text class=\"tb\" x=\"575\" y=\"189.8\" text-anchor=\"middle\" font-size=\"12\">apps, browsers, CLI</text><path class=\"ln ok\" d=\"M575,164 L570,124\" marker-end=\"url(#cloud-storage--ok)\"/></svg></div><figcaption>Ask who needs to read it. One server: EBS. Many servers sharing a folder: EFS. Anything with credentials, including browsers: S3.</figcaption></figure>\n\n<div class=\"learn-table-wrap\"><table class=\"learn-table\"><thead><tr><th></th><th>EBS (block)</th><th>EFS (file)</th><th>S3 (object)</th></tr></thead><tbody>\n<tr><td>Looks like</td><td>A raw disk you format and mount</td><td>A shared NFS folder</td><td>Objects reached by an HTTP API</td></tr>\n<tr><td>Used by</td><td>One EC2 instance at a time (with rare exceptions)</td><td>Many Linux instances, containers and Lambdas at once</td><td>Anything with credentials and network access</td></tr>\n<tr><td>Scope</td><td>One availability zone</td><td>Regional (across AZs)</td><td>Regional, data spread across AZs</td></tr>\n<tr><td>Size</td><td>You pick a size and pay for all of it</td><td>Grows and shrinks automatically</td><td>Practically unlimited</td></tr>\n<tr><td>Billed for</td><td>Provisioned GB (plus extra IOPS/throughput if configured)</td><td>GB actually stored</td><td>GB stored, requests, data transfer out</td></tr>\n<tr><td>Typical use</td><td>OS disks, databases on EC2</td><td>Shared uploads folder, content for a fleet of web servers</td><td>Backups, logs, images, static sites, data lakes</td></tr>\n</tbody></table></div>\n<p>EBS volume types include <b>gp3</b> (general-purpose SSD, the usual default), <b>io2</b> (provisioned IOPS for demanding databases) and <b>st1</b>/<b>sc1</b> (cheaper hard disks for large sequential data). A volume can only attach to instances in its own AZ; to move it, snapshot it and create a new volume elsewhere. You can grow a volume while it's in use (<code>aws ec2 modify-volume --volume-id vol-0123456789abcdef0 --size 30</code>), then extend the partition and filesystem inside the OS (<code>growpart</code>, then <code>xfs_growfs</code> or <code>resize2fs</code>). Volumes can't be shrunk.</p>\n\n<h4>S3: buckets, keys and prefixes</h4>\n<ul>\n<li>A <b>bucket</b> is a container created in one region. Its name must be <b>unique across all AWS accounts</b>, 3-63 characters of lowercase letters, numbers, hyphens and dots.</li>\n<li>An <b>object</b> is a file plus metadata, identified by its <b>key</b>, like <code>images/2026/logo.png</code>. S3 is flat: there are no real folders, and the console just groups keys by the <b>prefix</b> before each <code>/</code>.</li>\n<li>Objects can be up to 50 TB (raised from 5 TB in late 2025), but a single upload request is limited to 5 GB; larger files use <b>multipart upload</b>, which the AWS CLI does automatically.</li>\n<li>S3 is <b>strongly consistent</b>: once a write succeeds, every following read sees it.</li>\n</ul>\n\n<h4>Storage classes</h4>\n<p>Each object has a storage class. They trade storage price against retrieval price and speed; the durability design is the same everywhere except the One Zone classes, which keep data in a single AZ.</p>\n<div class=\"learn-table-wrap\"><table class=\"learn-table\"><thead><tr><th>Class (API name)</th><th>For</th><th>Notes</th></tr></thead><tbody>\n<tr><td>Standard (<code>STANDARD</code>)</td><td>Frequently accessed data</td><td>The default; no retrieval fee</td></tr>\n<tr><td>Intelligent-Tiering (<code>INTELLIGENT_TIERING</code>)</td><td>Unknown or changing access patterns</td><td>Moves objects between tiers automatically for a small per-object monitoring fee</td></tr>\n<tr><td>Standard-IA (<code>STANDARD_IA</code>)</td><td>Infrequent access, needed instantly</td><td>Cheaper storage, retrieval fee, 30-day minimum</td></tr>\n<tr><td>One Zone-IA (<code>ONEZONE_IA</code>)</td><td>Re-creatable infrequent data</td><td>One AZ only, so data is lost if that AZ is</td></tr>\n<tr><td>Glacier Instant Retrieval (<code>GLACIER_IR</code>)</td><td>Archives read a few times a year</td><td>Millisecond access, 90-day minimum</td></tr>\n<tr><td>Glacier Flexible Retrieval (<code>GLACIER</code>)</td><td>Archives</td><td>Restore takes minutes to hours before you can read; 90-day minimum</td></tr>\n<tr><td>Glacier Deep Archive (<code>DEEP_ARCHIVE</code>)</td><td>Long-term compliance archives</td><td>Cheapest storage; restore takes hours; 180-day minimum</td></tr>\n</tbody></table></div>\n<p>\"Minimum\" means you pay for at least that many days even if you delete the object sooner. Infrequent-access classes also bill small objects as if they were 128 KB. Check the S3 pricing page for actual prices in your region.</p>\n\n<h4>Versioning and lifecycle rules</h4>\n<p>With <b>versioning</b> on, overwriting an object keeps the old version, and deleting one just adds a <b>delete marker</b> on top, so mistakes and ransomware-style overwrites are recoverable. Once enabled it can only be suspended, never fully turned off, and every old version is billed. <b>Lifecycle rules</b> keep that under control by moving or deleting objects by age:</p>\n<pre><code># lifecycle.json\n{\n  \"Rules\": [\n    {\n      \"ID\": \"logs-archive-then-expire\",\n      \"Filter\": { \"Prefix\": \"logs/\" },\n      \"Status\": \"Enabled\",\n      \"Transitions\": [\n        { \"Days\": 30, \"StorageClass\": \"STANDARD_IA\" },\n        { \"Days\": 90, \"StorageClass\": \"GLACIER\" }\n      ],\n      \"Expiration\": { \"Days\": 365 },\n      \"NoncurrentVersionExpiration\": { \"NoncurrentDays\": 30 }\n    },\n    {\n      \"ID\": \"clean-up-failed-uploads\",\n      \"Filter\": { \"Prefix\": \"\" },\n      \"Status\": \"Enabled\",\n      \"AbortIncompleteMultipartUpload\": { \"DaysAfterInitiation\": 7 }\n    }\n  ]\n}\n\n$ aws s3api put-bucket-versioning --bucket demee-practice-assets \\\n    --versioning-configuration Status=Enabled\n$ aws s3api put-bucket-lifecycle-configuration --bucket demee-practice-assets \\\n    --lifecycle-configuration file://lifecycle.json</code></pre>\n<p>The first rule moves anything under <code>logs/</code> to Standard-IA after 30 days and to Glacier Flexible Retrieval after 90, deletes it after a year, and removes old versions 30 days after they're replaced. The second deletes the invisible parts of multipart uploads that never finished, which are otherwise billed forever.</p>\n\n<h4>Keeping buckets private, and sharing safely</h4>\n<p>New buckets have <b>Block Public Access</b> turned on and <b>ACLs disabled</b> (the \"bucket owner enforced\" setting), so nothing is public unless you deliberately change that. Access is granted with IAM policies (for your own users and roles) and <b>bucket policies</b> (for other accounts or services). Leave Block Public Access on unless the bucket really must serve the public, and even then prefer CloudFront in front.</p>\n<p>To share one private object temporarily, create a <b>presigned URL</b>: a link that carries a signature made with your credentials and works until it expires, with no change to the bucket's settings.</p>\n<pre><code>$ aws s3 presign s3://demee-practice-assets/docs/report.pdf --expires-in 3600\nhttps://demee-practice-assets.s3.eu-central-1.amazonaws.com/docs/report.pdf?X-Amz-Algorithm=AWS4-HMAC-SHA256&amp;...</code></pre>\n<p><code>--expires-in</code> is in seconds (default 3600, maximum 604800, which is 7 days). A URL signed with temporary role credentials stops working when those credentials expire, even if the time you asked for hasn't passed.</p>\n\n<h4>Static website hosting</h4>\n<p>S3 can serve a static site (HTML, CSS, JS, images) directly:</p>\n<pre><code>$ aws s3 website s3://demee-practice-site/ --index-document index.html --error-document error.html\n$ aws s3 sync ./public s3://demee-practice-site/ --delete</code></pre>\n<p>The website endpoint only speaks <b>HTTP</b> and needs the bucket to be publicly readable (Block Public Access off plus a bucket policy allowing <code>s3:GetObject</code> to everyone). The better production setup keeps the bucket private and puts <b>CloudFront</b> in front with <b>Origin Access Control</b>: you get HTTPS with an ACM certificate, your own domain, caching at edge locations, and only CloudFront can read the bucket.</p>\n\n<h4>The AWS CLI for S3</h4>\n<pre><code>$ aws s3 mb s3://demee-practice-assets --region eu-central-1      # make a bucket\n$ aws s3 ls                                                       # list your buckets\n$ aws s3 ls s3://demee-practice-assets/images/                    # list one prefix\n$ aws s3 ls s3://demee-practice-assets --recursive --human-readable --summarize\n\n$ aws s3 cp report.pdf s3://demee-practice-assets/docs/report.pdf         # upload\n$ aws s3 cp s3://demee-practice-assets/docs/report.pdf ./report-copy.pdf  # download\n$ aws s3 cp ./photos s3://demee-practice-assets/photos/ --recursive \\\n    --exclude \"*\" --include \"*.jpg\"                                # only .jpg files\n$ aws s3 cp backup.tar.gz s3://demee-practice-assets/backups/ --storage-class STANDARD_IA\n\n$ aws s3 sync ./site s3://demee-practice-assets/site/ --delete --dryrun   # preview\n$ aws s3 sync ./site s3://demee-practice-assets/site/ --delete            # mirror it\n\n$ aws s3 rm s3://demee-practice-assets/docs/report.pdf\n$ aws s3 rm s3://demee-practice-assets/tmp/ --recursive\n$ aws s3 rb s3://demee-practice-assets --force     # delete all objects, then the bucket</code></pre>\n<p><code>cp</code> copies what you name; <code>sync</code> copies only new and changed files, and with <code>--delete</code> also removes files from the destination that no longer exist in the source, so run it with <code>--dryrun</code> first. Filters are applied in order, which is why \"exclude everything, then include <code>*.jpg</code>\" works. <code>rb --force</code> can't remove old versions, so on a versioned bucket delete those first (or empty the bucket in the console).</p>\n\n<h4>Backups and snapshots</h4>\n<ul>\n<li><b>EBS snapshots</b> are point-in-time copies stored regionally (so they survive the loss of an AZ). They're <b>incremental</b>: after the first one, only changed blocks are stored. You can create volumes or AMIs from them and copy them to other regions.</li>\n<li><b>RDS</b> takes <b>automated backups</b> daily plus transaction logs, allowing <b>point-in-time restore</b> to any second within the retention period (up to 35 days). They are deleted with the database unless you choose to keep them. <b>Manual snapshots</b> stay until you delete them.</li>\n<li><b>AWS Backup</b> manages schedules and retention for EBS, RDS, DynamoDB, EFS and more in one place.</li>\n<li>A backup you have never restored is a hope, not a backup. Test restores regularly.</li>\n</ul>\n<pre><code>$ aws ec2 create-snapshot --volume-id vol-0123456789abcdef0 --description \"before upgrade\"\n$ aws rds create-db-snapshot --db-instance-identifier practice-db \\\n    --db-snapshot-identifier practice-db-before-upgrade</code></pre>\n\n<h4>Managed relational databases: RDS and Aurora</h4>\n<p><b>RDS</b> runs PostgreSQL, MySQL, MariaDB, Oracle, SQL Server or Db2 for you: AWS installs, patches, backs up and monitors it; you choose the instance size, storage, network and settings. <b>Aurora</b> is AWS's own MySQL- and PostgreSQL-compatible engine with a distributed storage layer that keeps six copies across three AZs; it's usually faster to fail over and to add readers, at a higher price, and <b>Aurora Serverless v2</b> scales capacity up and down automatically.</p>\n<pre><code>$ aws rds create-db-instance --db-instance-identifier practice-db \\\n    --engine postgres --db-instance-class db.t4g.micro --allocated-storage 20 \\\n    --master-username appadmin --manage-master-user-password \\\n    --no-publicly-accessible --storage-encrypted --backup-retention-period 7</code></pre>\n<p><code>--manage-master-user-password</code> makes RDS generate the password and keep it in Secrets Manager. Two features are often confused:</p>\n<div class=\"learn-table-wrap\"><table class=\"learn-table\"><thead><tr><th></th><th>Multi-AZ</th><th>Read replica</th></tr></thead><tbody>\n<tr><td>Purpose</td><td><b>Availability</b>: survive an AZ or instance failure</td><td><b>Scaling reads</b> (reports, read-heavy pages)</td></tr>\n<tr><td>Replication</td><td>Synchronous to a standby in another AZ</td><td>Asynchronous, so replicas can lag slightly</td></tr>\n<tr><td>Serves traffic?</td><td>The classic single standby doesn't; it takes over automatically on failure, with the same endpoint</td><td>Yes, reads only, on its own endpoint</td></tr>\n<tr><td>Where</td><td>Same region</td><td>Same or another region; can be promoted to a standalone database</td></tr>\n</tbody></table></div>\n<p>Add <code>--multi-az</code> to the create command for the first; <code>aws rds create-db-instance-read-replica --db-instance-identifier practice-db-replica --source-db-instance-identifier practice-db</code> for the second. (RDS also offers a Multi-AZ <i>cluster</i> deployment with two readable standbys.)</p>\n\n<h4>DynamoDB</h4>\n<p><b>DynamoDB</b> is a serverless key-value and document database: no instances, consistent single-digit-millisecond responses at almost any scale, billed <b>on-demand</b> per request or with <b>provisioned</b> capacity. Every item is found by its <b>partition key</b>, optionally combined with a <b>sort key</b>, and you design the keys around the queries you'll run, because there are no joins and scanning a whole table is slow and expensive.</p>\n<pre><code>$ aws dynamodb create-table --table-name Orders \\\n    --attribute-definitions AttributeName=customerId,AttributeType=S AttributeName=orderId,AttributeType=S \\\n    --key-schema AttributeName=customerId,KeyType=HASH AttributeName=orderId,KeyType=RANGE \\\n    --billing-mode PAY_PER_REQUEST\n$ aws dynamodb put-item --table-name Orders \\\n    --item '{\"customerId\": {\"S\": \"c-42\"}, \"orderId\": {\"S\": \"o-1001\"}, \"total\": {\"N\": \"59.90\"}}'\n$ aws dynamodb query --table-name Orders --key-condition-expression \"customerId = :c\" \\\n    --expression-attribute-values '{\":c\": {\"S\": \"c-42\"}}'</code></pre>\n<p><code>HASH</code> is the partition key and <code>RANGE</code> the sort key; the query returns all orders for customer <code>c-42</code>. Note the typed JSON format (<code>\"S\"</code> string, <code>\"N\"</code> number sent as a string).</p>\n\n<h4>SQL or NoSQL?</h4>\n<ul>\n<li>Choose <b>SQL</b> (RDS/Aurora) when data is relational (users, orders, products linked together), you need joins, ad-hoc queries and multi-row transactions, or you don't yet know every question you'll ask of the data. It's the safe default for most apps.</li>\n<li>Choose <b>DynamoDB</b> when access patterns are known and simple (get by ID, list by owner), you need huge scale or spiky traffic with no servers to size, or you're building serverless with Lambda.</li>\n<li>Many systems use both, plus S3 for files and ElastiCache for caching. Never store large files inside a database; store them in S3 and keep the key in the database.</li>\n</ul>\n\n<h4>Common mistakes</h4>\n<ul>\n<li><code>BucketAlreadyExists</code>: someone, in any account, already has that name. Add something unique.</li>\n<li><code>AccessDenied</code> on <code>ListBucket</code> but objects work (or the reverse): bucket ARN vs <code>bucket/*</code> ARN in the policy.</li>\n<li><b><code>sync --delete</code> to the wrong prefix, or in the wrong direction</b>: it deletes whatever doesn't match the source. Always run it with <code>--dryrun</code> first.</li>\n<li><b>Versioned bucket keeps growing</b> after deletes: old versions and delete markers are still billed. Add <code>NoncurrentVersionExpiration</code>.</li>\n<li><b>Database with public access \"just to test\"</b>: keep it private and connect through the app server or Session Manager port forwarding.</li>\n</ul>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=OGYEXGy8ca4&amp;t=145s\" target=\"_blank\" rel=\"noopener noreferrer\">Be A Better Dev · AWS Explained <span class=\"learn-sources-part\">· Static content storage (2:25)</span></a><a href=\"https://www.youtube.com/watch?v=OGYEXGy8ca4&amp;t=1223s\" target=\"_blank\" rel=\"noopener noreferrer\">Be A Better Dev · AWS Explained <span class=\"learn-sources-part\">· Storage options (20:23)</span></a><a href=\"https://www.youtube.com/watch?v=OGYEXGy8ca4&amp;t=1490s\" target=\"_blank\" rel=\"noopener noreferrer\">Be A Better Dev · AWS Explained <span class=\"learn-sources-part\">· Database services (24:50)</span></a><a href=\"https://www.youtube.com/watch?v=ZaA0kNm18pE&amp;t=2080s\" target=\"_blank\" rel=\"noopener noreferrer\">Be A Better Dev · Cloud Computing Explained <span class=\"learn-sources-part\">· Durability (34:40)</span></a></div>","cloud/costs-the-free-tier-the-aws-cli":"\n<p class=\"learn-lead\">In the cloud, every resource you forget about keeps costing money, and a leaked key can cost a lot of it. This chapter explains how AWS charges, which discounts exist, what typically causes a surprise bill and how to catch one early. Then it sets up the AWS CLI properly, including profiles and <code>--query</code>, and ends with a checklist for the first hour on a new account.</p>\n\n<h4>How AWS charges</h4>\n<p>Almost everything is metered: compute by the second or hour while it runs, storage by GB-month, requests per thousand or million, and <b>data transfer</b> by GB. Data coming <i>into</i> AWS from the internet is generally free; data going <i>out</i> to the internet is charged; traffic between AZs and between regions is charged too. Prices differ by region. Most Linux EC2 instances are billed per second (with a one-minute minimum). A stopped instance costs nothing for compute, but its disks and any public IPv4 addresses still cost money. Estimate with the <b>AWS Pricing Calculator</b> and check each service's pricing page for current numbers.</p>\n<figure class=\"learn-diagram dg\" data-dg=\"cloud-charges\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 230\" role=\"img\" aria-label=\"How AWS charges: data coming in from the internet is free, data going out is charged, traffic between availability zones is charged, and compute, storage and requests are metered\" style=\"--dgw:680px\"><defs><marker id=\"cloud-charges--bad\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk bad\" d=\"M0,0 L8,4 L0,8 z\"/></marker><marker id=\"cloud-charges--ok\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk ok\" d=\"M0,0 L8,4 L0,8 z\"/></marker><marker id=\"cloud-charges--warn\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk warn\" d=\"M0,0 L8,4 L0,8 z\"/></marker><marker id=\"cloud-charges--warn--s\" markerWidth=\"9\" markerHeight=\"9\" refX=\"1\" refY=\"4\" orient=\"auto\"><path class=\"mk warn\" d=\"M8,0 L0,4 L8,8 z\"/></marker></defs><rect class=\"b\" x=\"10\" y=\"90\" width=\"130\" height=\"56\" rx=\"6\"/><text class=\"tb\" x=\"75\" y=\"114.7\" text-anchor=\"middle\" font-size=\"13\">internet</text><text class=\"t2\" x=\"75\" y=\"130.0\" text-anchor=\"middle\" font-size=\"11\">users, you</text><rect class=\"g hi\" x=\"220\" y=\"10\" width=\"450\" height=\"210\" rx=\"8\"/><text class=\"tg hi\" x=\"230\" y=\"26\" font-size=\"11\">AWS region</text><rect class=\"b\" x=\"250\" y=\"60\" width=\"160\" height=\"60\" rx=\"6\"/><text class=\"tb\" x=\"330\" y=\"86.7\" text-anchor=\"middle\" font-size=\"13\">AZ a</text><text class=\"t2\" x=\"330\" y=\"102.0\" text-anchor=\"middle\" font-size=\"11\">EC2 + EBS</text><rect class=\"b\" x=\"490\" y=\"60\" width=\"160\" height=\"60\" rx=\"6\"/><text class=\"tb\" x=\"570\" y=\"86.7\" text-anchor=\"middle\" font-size=\"13\">AZ b</text><text class=\"t2\" x=\"570\" y=\"102.0\" text-anchor=\"middle\" font-size=\"11\">EC2 + EBS</text><path class=\"ln ok\" d=\"M142,100 L248,80\" marker-end=\"url(#cloud-charges--ok)\"/><text class=\"ok\" x=\"190\" y=\"78\" text-anchor=\"middle\" font-size=\"11\">in: free</text><path class=\"ln bad\" d=\"M248,108 L142,130\" marker-end=\"url(#cloud-charges--bad)\"/><text class=\"bad\" x=\"196\" y=\"152\" text-anchor=\"middle\" font-size=\"11\">out: charged</text><path class=\"ln warn\" d=\"M412,90 L488,90\" marker-end=\"url(#cloud-charges--warn)\" marker-start=\"url(#cloud-charges--warn--s)\"/><text class=\"warn\" x=\"450\" y=\"82\" text-anchor=\"middle\" font-size=\"11\">charged</text><text class=\"t2\" x=\"445\" y=\"156\" text-anchor=\"middle\" font-size=\"11\">running: per second or hour</text><text class=\"t2\" x=\"445\" y=\"176\" text-anchor=\"middle\" font-size=\"11\">stored: per GB-month   requests: per million</text><text class=\"bad\" x=\"445\" y=\"200\" text-anchor=\"middle\" font-size=\"11\">a stopped instance still pays for its disk and IPv4</text></svg></div><figcaption>Most surprise bills come from things left running or from data leaving AWS. Check the pricing page for each service; prices differ by region.</figcaption></figure>\n\n\n<h4>Pricing models</h4>\n<div class=\"learn-table-wrap\"><table class=\"learn-table\"><thead><tr><th>Model</th><th>How it works</th><th>Best for</th></tr></thead><tbody>\n<tr><td><b>On-Demand</b></td><td>Pay the list price for what runs, no commitment</td><td>Learning, new or unpredictable workloads, short experiments</td></tr>\n<tr><td><b>Savings Plans</b></td><td>Commit to spending a fixed amount per hour for 1 or 3 years in return for a lower rate. <b>Compute Savings Plans</b> apply across EC2 (any family, size or region), Fargate and Lambda; <b>EC2 Instance Savings Plans</b> are tied to one instance family in one region and discount more; <b>Database Savings Plans</b> (announced late 2025) cover managed databases</td><td>Steady baseline usage you're confident will continue</td></tr>\n<tr><td><b>Reserved Instances</b></td><td>Commit to specific instance attributes (type, region, platform) for 1 or 3 years. The older model; for EC2, AWS now recommends Savings Plans</td><td>Services and cases that Savings Plans don't cover</td></tr>\n<tr><td><b>Spot Instances</b></td><td>Use AWS's spare EC2 capacity at a large discount; AWS can take it back with a two-minute warning</td><td>Interruption-tolerant work: CI runners, batch jobs, stateless workers in an Auto Scaling group</td></tr>\n</tbody></table></div>\n<p>Commitments can be paid all upfront, partially upfront or with no upfront payment; more upfront means a bigger discount. Never commit before you know your real usage: a Savings Plan is billed whether you use it or not.</p>\n\n<h4>The free tier (read the current page)</h4>\n<p>AWS changed its free tier on <b>15 July 2025</b>. Accounts created since then get sign-up credits (with more earned by trying certain services) and choose between a <b>free plan</b>, which runs for a limited period (up to six months) or until the credits are used and doesn't charge your card, and a <b>paid plan</b>, where credits are used first and normal billing follows. Accounts created before that date keep the older model: 12 months of limited free usage for certain services, such as a small instance for a set number of hours per month. On both, some services have an <b>always-free</b> monthly allowance. The details (amounts, eligible instance types, which services are excluded) change, so check the AWS Free Tier page and the <b>Free Tier</b> and <b>Credits</b> pages in the Billing console for your own account. \"Free tier eligible\" in the console means eligible for <i>your</i> account's plan, within its limits, not free without limit.</p>\n\n<h4>What causes surprise bills</h4>\n<ul>\n<li><b>Forgotten resources</b>: an instance, a database or a load balancer from last week's tutorial, often in a <b>different region</b> from the one the console is showing.</li>\n<li><b>NAT gateways</b>: an hourly charge per gateway plus a charge per GB processed, even when nothing interesting is happening. Tutorials create them readily. Add an S3 gateway endpoint so S3 traffic skips the NAT.</li>\n<li><b>Data transfer out</b>: large downloads, video, or a popular file served straight from S3 or EC2. A CDN helps, but transfer is never free at scale.</li>\n<li><b>Leftover storage</b>: unattached EBS volumes (status <code>available</code>), old snapshots, and AMIs (deregistering an AMI does <i>not</i> delete its snapshots).</li>\n<li><b>Public IPv4 addresses</b>: every one is billed hourly, including idle Elastic IPs.</li>\n<li><b>Things that restart</b>: a stopped RDS instance starts again automatically after seven days.</li>\n<li><b>Logs kept forever</b>: CloudWatch Logs groups default to \"Never expire\". Set a retention period.</li>\n<li><b>Services with a base fee</b>: EKS clusters, interface VPC endpoints, idle load balancers.</li>\n<li><b>Leaked access keys</b>: attackers launch expensive instances in every region within minutes. Use roles, never commit keys, and enable MFA.</li>\n</ul>\n\n<h4>Budgets and alerts</h4>\n<p>Set these up before you build anything:</p>\n<ul>\n<li><b>AWS Budgets</b> (Billing and Cost Management → Budgets): create a monthly <b>cost budget</b> with email alerts on <b>actual</b> spend (say at 80%) and <b>forecasted</b> spend (at 100%). The <b>zero spend budget</b> template alerts you the moment anything costs more than a cent. Budgets check a few times a day, so they warn you; they don't stop resources.</li>\n<li><b>Cost Explorer</b>: charts of spend by service, region, day and tag. The first place to look when a bill surprises you.</li>\n<li><b>Cost Anomaly Detection</b>: learns your normal spend and alerts on unusual jumps. Check that a monitor exists and that its alerts go to an address you read.</li>\n<li><b>Billing preferences</b>: turn on free tier usage alerts, and \"Receive CloudWatch billing alerts\" if you want CloudWatch alarms on the <code>EstimatedCharges</code> metric (billing metrics live in <code>us-east-1</code>).</li>\n</ul>\n<p>A budget can also be created from the CLI:</p>\n<pre><code># budget.json\n{\n  \"BudgetName\": \"monthly-limit\",\n  \"BudgetLimit\": { \"Amount\": \"10\", \"Unit\": \"USD\" },\n  \"TimeUnit\": \"MONTHLY\",\n  \"BudgetType\": \"COST\"\n}\n\n# notifications.json\n[\n  {\n    \"Notification\": { \"NotificationType\": \"ACTUAL\", \"ComparisonOperator\": \"GREATER_THAN\",\n                      \"Threshold\": 80, \"ThresholdType\": \"PERCENTAGE\" },\n    \"Subscribers\": [ { \"SubscriptionType\": \"EMAIL\", \"Address\": \"you@example.com\" } ]\n  }\n]\n\n$ aws budgets create-budget --account-id 123456789012 \\\n    --budget file://budget.json --notifications-with-subscribers file://notifications.json</code></pre>\n\n<h4>Tagging</h4>\n<p><b>Tags</b> are key-value labels on resources, such as <code>Project=practice</code>, <code>Env=dev</code>, <code>Owner=demee</code>. Tag everything from day one (Terraform's <code>default_tags</code> makes this automatic). Tags let you find and delete everything belonging to one experiment, and, once you <b>activate them as cost allocation tags</b> in the Billing console, split the bill by project in Cost Explorer. Activation isn't retroactive: only costs from after activation are grouped by tag.</p>\n<pre><code>$ aws ec2 create-tags --resources i-0abc1234def567890 vol-0123456789abcdef0 \\\n    --tags Key=Project,Value=practice Key=Env,Value=dev\n$ aws resourcegroupstaggingapi get-resources --tag-filters Key=Project,Values=practice \\\n    --query 'ResourceTagMappingList[].ResourceARN' --output text</code></pre>\n\n<h4>Cleaning up</h4>\n<p>When an experiment is over, delete it the same way you built it: <code>terraform destroy</code> for Terraform projects, deleting the stack for CloudFormation, otherwise by hand in reverse order (instances and load balancers, then NAT gateways and Elastic IPs, then volumes, snapshots and buckets, and finally the VPC). Then sweep every region for leftovers:</p>\n<pre><code>$ for r in $(aws ec2 describe-regions --query 'Regions[].RegionName' --output text); do\n    echo \"== $r\"\n    aws ec2 describe-instances --region \"$r\" \\\n      --query 'Reservations[].Instances[].[InstanceId,State.Name,InstanceType]' --output text\n  done\n\n# unattached volumes and unassociated Elastic IPs in the current region\n$ aws ec2 describe-volumes --filters Name=status,Values=available \\\n    --query 'Volumes[].[VolumeId,Size,CreateTime]' --output table\n$ aws ec2 describe-addresses --query 'Addresses[?AssociationId==`null`].[PublicIp,AllocationId]' --output table</code></pre>\n<p>The Billing console's <b>Bills</b> page, broken down by service and region, is the final check: anything still charging shows up there.</p>\n\n<h4>Installing the AWS CLI v2</h4>\n<pre><code># Linux (x86_64; use awscli-exe-linux-aarch64.zip on ARM)\n$ curl \"https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip\" -o \"awscliv2.zip\"\n$ unzip awscliv2.zip\n$ sudo ./aws/install                 # add --update to upgrade an existing install\n$ aws --version\naws-cli/2.x.x Python/3.x.x Linux/...\n\n# macOS\n$ curl \"https://awscli.amazonaws.com/AWSCLIV2.pkg\" -o \"AWSCLIV2.pkg\"\n$ sudo installer -pkg AWSCLIV2.pkg -target /\n\n# Windows (run in PowerShell or cmd)\n$ msiexec.exe /i https://awscli.amazonaws.com/AWSCLIV2.msi</code></pre>\n<p>Don't use <code>pip install awscli</code>: that installs the old version 1, which lacks v2 features such as <code>aws login</code>, SSO support and the <code>--cli-binary-format</code> option.</p>\n\n<h4>Credentials and profiles</h4>\n<p>The CLI needs credentials. From best to last resort:</p>\n<ul>\n<li><code>aws login</code> (CLI 2.32 or newer): signs you in through the browser with your normal console sign-in and gives the CLI short-lived credentials that refresh automatically. No keys stored on disk.</li>\n<li><code>aws configure sso</code> then <code>aws sso login</code>: for IAM Identity Center users.</li>\n<li><code>aws configure</code> with an IAM user's access key: long-lived keys in a plain-text file. If you use it, give that user only what it needs and rotate the key.</li>\n</ul>\n<pre><code>$ aws configure\nAWS Access Key ID [None]: AKIAIOSFODNN7EXAMPLE\nAWS Secret Access Key [None]: ****************************************\nDefault region name [None]: eu-central-1\nDefault output format [None]: json\n\n# ~/.aws/config: settings per profile\n[default]\nregion = eu-central-1\noutput = json\n\n[profile practice]\nregion = eu-west-1\noutput = table\n\n# ~/.aws/credentials: keys per profile (no \"profile \" prefix here)\n[default]\naws_access_key_id = AKIAIOSFODNN7EXAMPLE\naws_secret_access_key = wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY\n\n$ aws configure --profile practice       # create or edit a named profile\n$ aws s3 ls --profile practice            # use it for one command\n$ export AWS_PROFILE=practice             # or for the whole shell session</code></pre>\n<p>Before doing anything, check <b>who and where you are</b>. Many \"it doesn't work\" moments are simply the wrong account or region:</p>\n<pre><code>$ aws sts get-caller-identity\n{\n    \"UserId\": \"AIDAEXAMPLEUSERID1234\",\n    \"Account\": \"123456789012\",\n    \"Arn\": \"arn:aws:iam::123456789012:user/demee\"\n}\n$ aws configure get region</code></pre>\n<p>Settings are resolved in this order: <b>command-line options</b> (<code>--region</code>, <code>--profile</code>, <code>--output</code>) beat <b>environment variables</b> (<code>AWS_PROFILE</code>, <code>AWS_REGION</code>, <code>AWS_ACCESS_KEY_ID</code>…), which beat the <b>config and credentials files</b>. A forgotten <code>AWS_ACCESS_KEY_ID</code> in your environment silently overrides your profile.</p>\n\n<h4>Output formats and --query</h4>\n<p><code>--output</code> can be <code>json</code> (default), <code>yaml</code>, <code>text</code> (tab-separated, best for shell scripts) or <code>table</code> (for humans). <code>--region eu-west-1</code> runs one command against another region. <code>--query</code> filters and reshapes the JSON response using <b>JMESPath</b>, on your machine after the response arrives; <code>--filters</code>, where a command supports it, filters on AWS's side before anything is sent.</p>\n<pre><code># Running instances as a table: ID, type, AZ and the value of the Name tag\n$ aws ec2 describe-instances --filters Name=instance-state-name,Values=running \\\n    --query \"Reservations[].Instances[].{ID: InstanceId, Type: InstanceType, AZ: Placement.AvailabilityZone, Name: Tags[?Key=='Name'] | [0].Value}\" \\\n    --output table\n\n# Just the bucket names, one per line\n$ aws s3api list-buckets --query 'Buckets[].Name' --output text</code></pre>\n<p>Reading the first query: <code>Reservations[].Instances[]</code> flattens the nested lists into one list of instances; <code>{ID: InstanceId, …}</code> builds a new object for each with the fields you choose; <code>Tags[?Key=='Name']</code> keeps only tags whose key is <code>Name</code>, and <code>| [0].Value</code> takes the first one's value. Strings inside JMESPath go in single quotes, so wrap the whole query in double quotes in bash. Other handy settings: <code>--no-cli-pager</code> (or <code>export AWS_PAGER=\"\"</code>) stops output opening in <code>less</code>, and <code>aws &lt;command&gt; help</code> shows every option.</p>\n\n<h4>Your first hour on a new AWS account</h4>\n<ol>\n<li>Sign in as root and turn on <b>MFA</b> (a passkey or an authenticator app). Make sure root has <b>no access keys</b>.</li>\n<li>Check the account email and set <b>alternate contacts</b> for billing and security, so AWS's warnings reach you.</li>\n<li>Create an everyday admin identity: an IAM Identity Center user, or an IAM user with MFA in an admins group. Sign out of root and use that from now on.</li>\n<li>Create a <b>zero spend budget</b> and a monthly budget with actual and forecasted alerts; turn on free tier usage alerts; check Cost Anomaly Detection is sending alerts to you.</li>\n<li>Pick a <b>home region</b> close to you and use it consistently.</li>\n<li>Install the CLI v2, run <code>aws login</code> (or <code>aws configure sso</code>), then <code>aws sts get-caller-identity</code>.</li>\n<li>Confirm <b>S3 Block Public Access</b> is on at account level and turn on <b>EBS encryption by default</b> in your region.</li>\n<li>Look at <b>CloudTrail</b> event history (the last 90 days of management events are visible by default); create a trail to S3 if you want a longer record.</li>\n<li>Decide on tags (at least <code>Project</code>) and, from the second experiment on, build with Terraform so that <code>terraform destroy</code> cleans up everything.</li>\n</ol>\n\n<h4>Common CLI errors</h4>\n<ul>\n<li><code>Unable to locate credentials</code>: nothing configured for this profile. Run <code>aws login</code>, <code>aws sso login</code> or <code>aws configure</code>, or check <code>AWS_PROFILE</code>.</li>\n<li><code>ExpiredToken</code> or \"The SSO session has expired\": temporary credentials ran out; log in again.</li>\n<li><code>InvalidClientTokenId</code> / <code>SignatureDoesNotMatch</code>: a mistyped, deleted or deactivated access key, or a stale key in environment variables overriding the file.</li>\n<li><code>Could not connect to the endpoint URL</code>: usually a misspelled region (<code>eu-central1</code> instead of <code>eu-central-1</code>).</li>\n<li><b>An empty result when you know the resource exists</b>: you're in the wrong region or account. Check <code>aws sts get-caller-identity</code> and <code>--region</code>.</li>\n<li><b>Output opens in a pager and a script hangs</b>: add <code>--no-cli-pager</code> or set <code>AWS_PAGER=\"\"</code>.</li>\n</ul>\n","devops/core-tools":"\n<p class=\"learn-lead\">DevOps is a way of working where the people who write software and the people who run it share responsibility for getting changes to users quickly and safely. In practice that means automating everything between \"I wrote code\" and \"it's running in production\", with a set of tools that each own one step.</p>\n\n<h4>The idea behind DevOps</h4>\n<p>Traditionally developers wrote code and \"threw it over the wall\" to an operations team, who deployed it by hand, often weeks later. Releases were rare, risky and slow. DevOps replaces that with small, frequent changes that flow through an automated pipeline, with fast feedback when something breaks. The lifecycle is usually drawn as a loop: <b>plan → code → build → test → release → deploy → operate → monitor</b>, and back to plan with what you learned.</p>\n\n<h4>The toolchain, one job each</h4>\n<ul>\n<li><b>Git</b> (with GitHub or GitLab): version control, the single source of truth for code and, increasingly, for infrastructure too.</li>\n<li><b>Jenkins, GitHub Actions, GitLab CI</b>: CI/CD servers that run the pipeline on every change.</li>\n<li><b>Docker</b>: packages an app with everything it needs into an image that runs the same everywhere.</li>\n<li><b>Kubernetes</b>: runs and manages many containers across many machines, restarting and scaling them automatically.</li>\n<li><b>Terraform</b>: infrastructure as code; creates servers, networks and databases in the cloud from config files.</li>\n<li><b>Ansible</b>: configuration management; logs in to existing servers and brings them to a described state (packages installed, files in place, services running), using YAML playbooks.</li>\n<li><b>Prometheus and Grafana</b>: monitoring; collect metrics and draw dashboards and alerts.</li>\n</ul>\n<p>The easy way to keep Terraform and Ansible apart: Terraform <i>creates</i> the infrastructure, Ansible <i>configures</i> what's on it. Likewise, Docker packages <i>one</i> app; Kubernetes manages <i>many</i> containers at scale.</p>\n{{DIAG:TOOL_LIFECYCLE}}\n\n<h4>Where it runs</h4>\n<p>Most of this runs in a public cloud such as AWS, Azure or Google Cloud, where you rent computing, storage and networking instead of buying hardware. The <b>Cloud</b> topic in the Docs covers how that works, the main services and what they cost.</p>\n<div class=\"learn-callout\">Exam distractors: tools like Power BI or Excel are for business reporting, not DevOps. If a question lists \"DevOps tools\", look for the ones above.</div>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=GzIFoJBVwh8&amp;t=29s\" target=\"_blank\" rel=\"noopener noreferrer\">edureka! · Linux Commands for DevOps <span class=\"learn-sources-part\">· Why Linux is at the heart of DevOps (0:29)</span></a></div>","devops/ci-cd-deployment":"\n<p class=\"learn-lead\">CI/CD is the automated path every change takes to production. Nana's CI video makes the key point: automated tests are a <b>gatekeeper</b>. Code only moves forward if they pass, so broken changes are caught minutes after they're written instead of by users.</p>\n\n<h4>Continuous Integration</h4>\n<p>In <b>CI</b>, developers merge small changes into the shared branch often (at least daily), and every push automatically triggers a pipeline that builds the code and runs the tests. Tests run at several points:</p>\n<ul>\n<li>on every <b>feature branch</b> push, so you learn about a problem while the change is fresh in your head;</li>\n<li>on every <b>pull/merge request</b>, where a failing check blocks the merge: the gatekeeper;</li>\n<li>on <b>main</b> after merging, because the combination of everyone's changes can fail even when each passed alone.</li>\n</ul>\n<p>Testing as early as possible is called <b>shifting left</b> (left being the start of the timeline). The earlier a bug is found, the cheaper it is to fix. Pipelines typically run several kinds of checks: <b>unit tests</b> (small functions in isolation), <b>integration tests</b> (parts working together, like app plus database), <b>linting</b> and code-quality scans, and security scans of dependencies.</p>\n\n<h4>Continuous Delivery and Deployment</h4>\n<p>Once the code passes, it's packaged into an <b>artifact</b> (today usually a Docker image), tagged with a version or commit ID, and stored in a <b>registry</b>. Then it's released through <b>environments</b>: typically dev, then staging (a copy of production for final checks), then production.</p>\n<ul>\n<li><b>Continuous Delivery</b>: every passing build is ready to go live, but a human clicks the button for production.</li>\n<li><b>Continuous Deployment</b>: every passing build goes to production automatically, no human step.</li>\n</ul>\n{{DIAG:CICD_GATE_EN}}\n\n<h4>Deployment strategies</h4>\n<p>Replacing a running app without downtime needs a plan:</p>\n<ul>\n<li><b>Rolling</b>: replace servers or pods a few at a time. Kubernetes does this by default.</li>\n<li><b>Blue-green</b>: run the new version (green) next to the old one (blue), test it, then switch all traffic at once. Rolling back is just switching back.</li>\n<li><b>Canary</b>: send a small share of users (say 5%) to the new version, watch error rates, and increase gradually if it's healthy.</li>\n<li><b>Feature flags</b>: ship code switched off and turn features on for chosen users without a new deployment.</li>\n<li><b>Rollback</b>: going back to the previous version when something goes wrong. Pipelines should make this one click, which is why artifacts are kept with version tags.</li>\n</ul>\n\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=MIWH2CpVyXs&amp;t=32s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · The ONLY Continuous Integration (CI) Tutorial <span class=\"learn-sources-part\">· Why tests matter (0:32)</span></a><a href=\"https://www.youtube.com/watch?v=MIWH2CpVyXs&amp;t=204s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · The ONLY Continuous Integration (CI) Tutorial <span class=\"learn-sources-part\">· Tests as the gatekeeper on merge requests (3:24)</span></a><a href=\"https://www.youtube.com/watch?v=MIWH2CpVyXs&amp;t=406s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · The ONLY Continuous Integration (CI) Tutorial <span class=\"learn-sources-part\">· What CI and a CI pipeline are, shifting left (6:46)</span></a></div>","devops/concepts-practices":"\n<p class=\"learn-lead\">Beyond the tools, DevOps rests on a few ideas: treat infrastructure like code, design systems that can change safely, and always know what your system is doing in production.</p>\n\n<h4>Infrastructure as Code</h4>\n<p><b>IaC</b> means describing servers, networks and databases in files instead of clicking through a cloud console. The files live in Git, so infrastructure changes get reviewed, versioned and can be rebuilt identically in a new region or after a disaster. No more \"nobody knows how that server was set up\".</p>\n<pre><code># main.tf (Terraform)\nresource \"aws_instance\" \"web\" {\n  ami           = \"ami-0abcdef1234567890\"\n  instance_type = \"t3.micro\"\n  tags = { Name = \"web-01\" }\n}\n\n$ terraform init      # download the provider plugins\n$ terraform plan      # preview: what would change?\n$ terraform apply     # make it so\n$ terraform destroy   # remove everything it created</code></pre>\n<p>Terraform is <b>declarative</b>: you describe the end result, not the steps, and it works out what to create, change or delete. It records what it built in a <b>state file</b>, which teams keep in shared remote storage. AWS's own equivalent is CloudFormation. <b>Ansible</b> complements it by configuring the servers once they exist; it connects over SSH and needs no agent installed on them.</p>\n\n<h4>Monoliths and microservices</h4>\n<p>A <b>monolith</b> is one application deployed as a single unit: simple to build, test and deploy at first, but every change redeploys everything and one part can't scale without the rest. <b>Microservices</b> split the system into small services that each own one job and their own data, talk over APIs or events, and deploy independently. That brings flexibility and independent scaling, but much more to operate: networking, monitoring, and failures between services. Containers and Kubernetes are what made microservices practical.</p>\n<figure class=\"learn-diagram dg\" data-dg=\"do-micro\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 250\" role=\"img\" aria-label=\"A monolith is one app with users, orders and payments sharing one database and one deploy; microservices split them into separate services, each with its own database and deploy\" style=\"--dgw:680px\"><defs><marker id=\"do-micro--hi\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk hi\" d=\"M0,0 L8,4 L0,8 z\"/></marker><marker id=\"do-micro--hi--s\" markerWidth=\"9\" markerHeight=\"9\" refX=\"1\" refY=\"4\" orient=\"auto\"><path class=\"mk hi\" d=\"M8,0 L0,4 L8,8 z\"/></marker><marker id=\"do-micro--ok\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk ok\" d=\"M0,0 L8,4 L0,8 z\"/></marker><marker id=\"do-micro--warn\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk warn\" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><text class=\"tb\" x=\"150\" y=\"20\" text-anchor=\"middle\" font-size=\"13\">monolith</text><rect class=\"g warn\" x=\"20\" y=\"32\" width=\"260\" height=\"150\" rx=\"8\"/><text class=\"tg warn\" x=\"30\" y=\"48\" font-size=\"11\">one app, one deploy</text><rect class=\"b\" x=\"36\" y=\"60\" width=\"228\" height=\"30\" rx=\"6\"/><text class=\"\" x=\"150\" y=\"78.8\" text-anchor=\"middle\" font-size=\"12\">users</text><rect class=\"b\" x=\"36\" y=\"98\" width=\"228\" height=\"30\" rx=\"6\"/><text class=\"\" x=\"150\" y=\"116.8\" text-anchor=\"middle\" font-size=\"12\">orders</text><rect class=\"b\" x=\"36\" y=\"136\" width=\"228\" height=\"30\" rx=\"6\"/><text class=\"\" x=\"150\" y=\"154.8\" text-anchor=\"middle\" font-size=\"12\">payments</text><rect class=\"b warn\" x=\"70\" y=\"200\" width=\"160\" height=\"40\" rx=\"6\"/><text class=\"tb\" x=\"150\" y=\"223.8\" text-anchor=\"middle\" font-size=\"12\">one database</text><path class=\"ln warn\" d=\"M150,184 L150,198\" marker-end=\"url(#do-micro--warn)\"/><text class=\"tb\" x=\"500\" y=\"20\" text-anchor=\"middle\" font-size=\"13\">microservices</text><rect class=\"b hi\" x=\"336\" y=\"60\" width=\"96\" height=\"50\" rx=\"6\"/><text class=\"tb ta\" x=\"384\" y=\"82.2\" text-anchor=\"middle\" font-size=\"13\">users</text><text class=\"t2\" x=\"384\" y=\"96.7\" text-anchor=\"middle\" font-size=\"10\">own deploy</text><rect class=\"b ok\" x=\"344\" y=\"190\" width=\"80\" height=\"40\" rx=\"6\"/><text class=\"tb\" x=\"384\" y=\"213.5\" text-anchor=\"middle\" font-size=\"11\">own DB</text><path class=\"ln ok\" d=\"M384,112 L384,188\" marker-end=\"url(#do-micro--ok)\"/><rect class=\"b hi\" x=\"452\" y=\"60\" width=\"96\" height=\"50\" rx=\"6\"/><text class=\"tb ta\" x=\"500\" y=\"82.2\" text-anchor=\"middle\" font-size=\"13\">orders</text><text class=\"t2\" x=\"500\" y=\"96.7\" text-anchor=\"middle\" font-size=\"10\">own deploy</text><rect class=\"b ok\" x=\"460\" y=\"190\" width=\"80\" height=\"40\" rx=\"6\"/><text class=\"tb\" x=\"500\" y=\"213.5\" text-anchor=\"middle\" font-size=\"11\">own DB</text><path class=\"ln ok\" d=\"M500,112 L500,188\" marker-end=\"url(#do-micro--ok)\"/><path class=\"ln hi\" d=\"M434,85 L450,85\" marker-end=\"url(#do-micro--hi)\" marker-start=\"url(#do-micro--hi--s)\"/><rect class=\"b hi\" x=\"568\" y=\"60\" width=\"96\" height=\"50\" rx=\"6\"/><text class=\"tb ta\" x=\"616\" y=\"82.2\" text-anchor=\"middle\" font-size=\"13\">payments</text><text class=\"t2\" x=\"616\" y=\"96.7\" text-anchor=\"middle\" font-size=\"10\">own deploy</text><rect class=\"b ok\" x=\"576\" y=\"190\" width=\"80\" height=\"40\" rx=\"6\"/><text class=\"tb\" x=\"616\" y=\"213.5\" text-anchor=\"middle\" font-size=\"11\">own DB</text><path class=\"ln ok\" d=\"M616,112 L616,188\" marker-end=\"url(#do-micro--ok)\"/><path class=\"ln hi\" d=\"M550,85 L566,85\" marker-end=\"url(#do-micro--hi)\" marker-start=\"url(#do-micro--hi--s)\"/><text class=\"ta\" x=\"502\" y=\"150\" text-anchor=\"middle\" font-size=\"11\">talk over APIs or events</text></svg></div><figcaption>Microservices trade one big deploy for many small ones. You gain independent releases and scaling, and you take on networking, versioning and a lot more to monitor.</figcaption></figure>\n\n\n<h4>Observability: knowing what's happening</h4>\n<p>You can't fix what you can't see. <b>Observability</b> rests on three kinds of data:</p>\n<ul>\n<li><b>Metrics</b>: numbers over time (CPU, request rate, error rate, response time). Collected by <b>Prometheus</b> or CloudWatch, graphed in <b>Grafana</b>.</li>\n<li><b>Logs</b>: timestamped records of events, collected centrally (ELK stack, Loki, CloudWatch Logs) so you can search across all servers at once.</li>\n<li><b>Traces</b>: the path of a single request across several services, showing where time was spent.</li>\n</ul>\n<p><b>Alerts</b> turn metrics into action: page someone when the error rate goes above 5% for five minutes, not every time CPU briefly spikes.</p>\n\n<h4>SRE and reliability targets</h4>\n<p><b>Site Reliability Engineering</b> (from Google) applies software engineering to operations. Its vocabulary: an <b>SLI</b> is something measured (the percentage of requests that succeed), an <b>SLO</b> is the internal target for it (99.9% over 30 days), and an <b>SLA</b> is the promise to customers, with penalties if missed. The gap between 100% and the SLO is the <b>error budget</b>: while there's budget left, ship features; when it's used up, focus on stability.</p>\n\n<h4>GitOps and DevSecOps</h4>\n<p><b>GitOps</b> takes IaC one step further: the Git repository describes exactly what should run in production, and a tool like Argo CD continuously syncs the cluster to match it. Deploying means merging a pull request, and rolling back means reverting one. <b>DevSecOps</b> builds security into every step instead of checking it at the end: scanning code and dependencies in CI, scanning images, keeping secrets out of Git, and least-privilege permissions everywhere.</p>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=ZaA0kNm18pE&amp;t=2167s\" target=\"_blank\" rel=\"noopener noreferrer\">Be A Better Dev · Cloud Computing Explained <span class=\"learn-sources-part\">· Infrastructure as Code (36:07)</span></a><a href=\"https://www.youtube.com/watch?v=OGYEXGy8ca4&amp;t=2952s\" target=\"_blank\" rel=\"noopener noreferrer\">Be A Better Dev · AWS Explained <span class=\"learn-sources-part\">· Monitoring and logging on AWS (49:12)</span></a><a href=\"https://www.youtube.com/watch?v=guCFLTU-XRM&amp;t=95s\" target=\"_blank\" rel=\"noopener noreferrer\">Cloud Champ · How I use Python as a DevOps Engineer <span class=\"learn-sources-part\">· Python for automation and IaC (1:35)</span></a></div>","devops/how-it-all-fits-together":"\n<p class=\"learn-lead\">Each topic on this site is one piece of the same machine. Following a single change from your keyboard to users shows where every piece fits.</p>\n\n<h4>The journey of one change</h4>\n<figure class=\"learn-diagram dg\" data-dg=\"do-journey\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 260\" role=\"img\" aria-label=\"One change travels from code to pull request, CI, an image build, a registry, a rolling deploy and monitoring, and what monitoring shows feeds the next change\" style=\"--dgw:680px\"><defs><marker id=\"do-journey--hi\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk hi\" d=\"M0,0 L8,4 L0,8 z\"/></marker><marker id=\"do-journey--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"b hi\" x=\"10\" y=\"20\" width=\"130\" height=\"60\" rx=\"6\"/><text class=\"tb ta\" x=\"75\" y=\"47.2\" text-anchor=\"middle\" font-size=\"13\">code</text><text class=\"t2\" x=\"75\" y=\"61.7\" text-anchor=\"middle\" font-size=\"10\">branch + commit</text><rect class=\"b\" x=\"190\" y=\"20\" width=\"130\" height=\"60\" rx=\"6\"/><text class=\"tb\" x=\"255\" y=\"47.2\" text-anchor=\"middle\" font-size=\"13\">pull request</text><text class=\"t2\" x=\"255\" y=\"61.7\" text-anchor=\"middle\" font-size=\"10\">review</text><rect class=\"b\" x=\"370\" y=\"20\" width=\"130\" height=\"60\" rx=\"6\"/><text class=\"tb\" x=\"435\" y=\"47.2\" text-anchor=\"middle\" font-size=\"13\">CI</text><text class=\"t2\" x=\"435\" y=\"61.7\" text-anchor=\"middle\" font-size=\"10\">tests on a runner</text><rect class=\"b\" x=\"540\" y=\"20\" width=\"130\" height=\"60\" rx=\"6\"/><text class=\"tb\" x=\"605\" y=\"47.2\" text-anchor=\"middle\" font-size=\"13\">build</text><text class=\"t2\" x=\"605\" y=\"61.7\" text-anchor=\"middle\" font-size=\"10\">image :sha</text><rect class=\"b\" x=\"540\" y=\"170\" width=\"130\" height=\"60\" rx=\"6\"/><text class=\"tb\" x=\"605\" y=\"197.2\" text-anchor=\"middle\" font-size=\"13\">registry</text><text class=\"t2\" x=\"605\" y=\"211.7\" text-anchor=\"middle\" font-size=\"10\">stores it</text><rect class=\"b\" x=\"330\" y=\"170\" width=\"130\" height=\"60\" rx=\"6\"/><text class=\"tb\" x=\"395\" y=\"197.2\" text-anchor=\"middle\" font-size=\"13\">deploy</text><text class=\"t2\" x=\"395\" y=\"211.7\" text-anchor=\"middle\" font-size=\"10\">rolling update</text><rect class=\"b ok\" x=\"110\" y=\"170\" width=\"130\" height=\"60\" rx=\"6\"/><text class=\"tb\" x=\"175\" y=\"197.2\" text-anchor=\"middle\" font-size=\"13\">monitor</text><text class=\"t2\" x=\"175\" y=\"211.7\" text-anchor=\"middle\" font-size=\"10\">metrics, alerts</text><path class=\"ln\" d=\"M142,50 L188,50\" marker-end=\"url(#do-journey--n)\"/><path class=\"ln\" d=\"M322,50 L368,50\" marker-end=\"url(#do-journey--n)\"/><path class=\"ln\" d=\"M502,50 L538,50\" marker-end=\"url(#do-journey--n)\"/><path class=\"ln\" d=\"M605,82 L605,168\" marker-end=\"url(#do-journey--n)\"/><path class=\"ln\" d=\"M538,200 L462,200\" marker-end=\"url(#do-journey--n)\"/><path class=\"ln\" d=\"M328,200 L242,200\" marker-end=\"url(#do-journey--n)\"/><path class=\"ln hi dash\" d=\"M108,168 L75,82\" marker-end=\"url(#do-journey--hi)\"/><text class=\"ta\" x=\"110\" y=\"128\" text-anchor=\"start\" font-size=\"11\">feedback: the next change</text></svg></div><figcaption>Every topic in the Docs is one box here. Git starts it, Linux and Python run it, Docker packages it, Kubernetes and the cloud host it, monitoring closes the loop.</figcaption></figure>\n\n<ol>\n<li><b>Code</b>: you create a branch, edit files and commit (<b>Git</b>). The app is written in, or automated with, <b>Python</b> and shell scripts.</li>\n<li><b>Push and review</b>: you push the branch and open a pull request on GitHub. A teammate reviews it.</li>\n<li><b>Continuous integration</b>: the push triggers a pipeline (<b>GitHub Actions / GitLab CI</b>) on a runner, a <b>Linux</b> machine. It installs dependencies and runs the tests. If any fail, the merge is blocked.</li>\n<li><b>Build</b>: after merging, the pipeline builds a <b>Docker</b> image tagged with the commit ID and pushes it to a registry.</li>\n<li><b>Deploy</b>: the pipeline updates the <b>Kubernetes</b> Deployment to the new image tag, and Kubernetes does a rolling update: new pods start, pass their health checks, then old pods are removed. No downtime.</li>\n<li><b>Infrastructure</b>: the cluster, VPC, databases and load balancer it all runs on were created by <b>Terraform</b> in the <b>cloud</b> (AWS), and are themselves versioned in Git.</li>\n<li><b>Traffic</b>: a user types your domain. <b>DNS</b> returns the load balancer's IP, the request arrives over <b>HTTPS</b>, passes the Ingress and a Service, and reaches one of your pods, all inside a VPC protected by security groups (<b>Networking</b>).</li>\n<li><b>Monitor</b>: metrics, logs and alerts (<b>Prometheus, Grafana, CloudWatch</b>) show whether the new version is healthy. If error rates jump, you roll back, fix it, and the loop starts again.</li>\n</ol>\n\n<h4>How the topics build on each other</h4>\n<pre><code>Linux        the machine everything runs on\n  ↓\nNetworking   how those machines find and talk to each other\n  ↓\nGit          tracks every change to code and infrastructure\n  ↓\nPython       automates the repetitive work\n  ↓\nCI/CD        builds, tests and ships each change automatically\n  ↓\nDocker       packages the app so it runs the same everywhere\n  ↓\nKubernetes   runs many containers reliably at scale\n  ↓\nCloud        rents the servers, networks and storage underneath\n  ↓\nMonitoring   shows whether it's all actually working</code></pre>\n\n<h4>What to focus on for the exam</h4>\n<p>You don't need to memorise every flag. For each technology, make sure you can explain: <b>what it is</b>, <b>what problem it solves</b>, its <b>two or three core ideas</b> (for example image vs container, commit vs push, pod vs deployment), a <b>few basic commands</b>, and <b>how it connects</b> to the technologies before and after it in the journey above. The Cheat sheets page has the one-line versions for a final review.</p>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=pg19Z8LL06w&amp;t=3819s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Docker Crash Course <span class=\"learn-sources-part\">· Docker in the complete development lifecycle (1:03:39)</span></a><a href=\"https://www.youtube.com/watch?v=qP8kir2GUgo&amp;t=3284s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · GitLab CI/CD Tutorial <span class=\"learn-sources-part\">· A full pipeline: test, build, push, deploy (54:44)</span></a></div>","devops/infrastructure-as-code-with-terraform":"\n<p class=\"learn-lead\">The Concepts chapter showed four Terraform commands and one resource. This chapter builds a small but complete project: how a Terraform configuration is structured, what actually happens during plan and apply, why the state file matters so much, and the mistakes that bite most beginners.</p>\n\n<h4>Why Infrastructure as Code</h4>\n<p>Clicking through the AWS console works once. It doesn't tell anyone what you clicked, it can't be reviewed, and rebuilding the same setup for staging or after an accident is guesswork. With IaC the files <i>are</i> the documentation, changes go through pull requests like code, and <code>apply</code> produces the same result every time. Terraform is <b>declarative</b> (you describe the end state, it works out the steps) and works with hundreds of platforms through <b>providers</b>. Since 2023 Terraform is under the BSL licence; <b>OpenTofu</b> is an open-source fork with the same language and a <code>tofu</code> command.</p>\n\n<h4>The building blocks</h4>\n<ul>\n<li><b>Provider</b>: a plugin that talks to one platform's API (AWS, Azure, Cloudflare, GitHub…). Terraform downloads it during <code>init</code>.</li>\n<li><b>Resource</b>: one thing to create and manage, written <code>resource \"TYPE\" \"NAME\"</code>. Its address, like <code>aws_s3_bucket.site</code>, is how you refer to it elsewhere.</li>\n<li><b>Variable</b>: an input, so the same code works for different names, regions or environments.</li>\n<li><b>Output</b>: a value printed after apply (an IP, a URL, an ARN) and readable by other tools.</li>\n<li><b>Data source</b>: reads something that already exists without managing it, like the latest Ubuntu AMI.</li>\n</ul>\n<p>Terraform loads every <code>.tf</code> file in the folder together, so splitting into files is just for readability.</p>\n\n<h4>A small, complete example: a private S3 bucket</h4>\n<pre><code># main.tf\nterraform {\n  required_version = \"&gt;= 1.5\"\n  required_providers {\n    aws = {\n      source  = \"hashicorp/aws\"\n      version = \"~&gt; 6.0\"          # any 6.x, never a surprise 7.0\n    }\n  }\n}\n\nprovider \"aws\" {\n  region = var.region\n}\n\nresource \"aws_s3_bucket\" \"site\" {\n  bucket = var.bucket_name\n  tags = {\n    Project   = \"devops-practice\"\n    ManagedBy = \"terraform\"\n  }\n}\n\nresource \"aws_s3_bucket_versioning\" \"site\" {\n  bucket = aws_s3_bucket.site.id     # a reference: Terraform creates the bucket first\n  versioning_configuration {\n    status = \"Enabled\"\n  }\n}\n\nresource \"aws_s3_bucket_public_access_block\" \"site\" {\n  bucket                  = aws_s3_bucket.site.id\n  block_public_acls       = true\n  block_public_policy     = true\n  ignore_public_acls      = true\n  restrict_public_buckets = true\n}\n\n# variables.tf\nvariable \"region\" {\n  type    = string\n  default = \"eu-central-1\"\n}\n\nvariable \"bucket_name\" {\n  description = \"Globally unique S3 bucket name\"\n  type        = string\n}\n\n# outputs.tf\noutput \"bucket_arn\" {\n  value = aws_s3_bucket.site.arn\n}\n\n# terraform.tfvars  (loaded automatically)\nbucket_name = \"demee-devops-practice-2026\"</code></pre>\n<p>References like <code>aws_s3_bucket.site.id</code> tell Terraform about <b>dependencies</b>, so it knows the bucket must exist before its versioning and access settings. Terraform finds AWS credentials the same way the AWS CLI does (<code>aws configure</code>, <code>AWS_PROFILE</code>, or environment variables). Never write access keys in a <code>.tf</code> file.</p>\n\n<h4>The workflow: init, plan, apply, destroy</h4>\n<figure class=\"learn-diagram dg\" data-dg=\"do-tf\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 240\" role=\"img\" aria-label=\"Terraform compares main.tf, what you want, with the state, what exists, and plan shows the difference; apply makes the changes to real resources and updates the state\" style=\"--dgw:680px\"><defs><marker id=\"do-tf--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker><marker id=\"do-tf--warn\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk warn\" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"b hi\" x=\"10\" y=\"30\" width=\"140\" height=\"60\" rx=\"6\"/><text class=\"tb ta tm\" x=\"80\" y=\"57.2\" text-anchor=\"middle\" font-size=\"13\">main.tf</text><text class=\"t2\" x=\"80\" y=\"71.7\" text-anchor=\"middle\" font-size=\"10\">what you want</text><rect class=\"b warn\" x=\"10\" y=\"150\" width=\"140\" height=\"60\" rx=\"6\"/><text class=\"tb\" x=\"80\" y=\"177.2\" text-anchor=\"middle\" font-size=\"13\">state</text><text class=\"t2\" x=\"80\" y=\"191.7\" text-anchor=\"middle\" font-size=\"10\">what exists</text><rect class=\"b\" x=\"240\" y=\"90\" width=\"150\" height=\"60\" rx=\"6\"/><text class=\"tb tm\" x=\"315\" y=\"116.8\" text-anchor=\"middle\" font-size=\"12\">terraform plan</text><text class=\"t2\" x=\"315\" y=\"131.2\" text-anchor=\"middle\" font-size=\"10\">the difference</text><rect class=\"b ok\" x=\"470\" y=\"30\" width=\"200\" height=\"60\" rx=\"6\"/><text class=\"tb tm\" x=\"570\" y=\"56.8\" text-anchor=\"middle\" font-size=\"12\">terraform apply</text><text class=\"t2\" x=\"570\" y=\"71.2\" text-anchor=\"middle\" font-size=\"10\">makes the changes</text><rect class=\"b\" x=\"470\" y=\"150\" width=\"200\" height=\"60\" rx=\"6\"/><text class=\"tb\" x=\"570\" y=\"177.2\" text-anchor=\"middle\" font-size=\"13\">real resources</text><text class=\"t2\" x=\"570\" y=\"191.7\" text-anchor=\"middle\" font-size=\"10\">S3, EC2, VPC...</text><path class=\"ln\" d=\"M152,60 L238,110\" marker-end=\"url(#do-tf--n)\"/><path class=\"ln\" d=\"M152,180 L238,130\" marker-end=\"url(#do-tf--n)\"/><path class=\"ln\" d=\"M392,110 L468,64\" marker-end=\"url(#do-tf--n)\"/><text class=\"tl\" x=\"430\" y=\"80\" text-anchor=\"middle\" font-size=\"10\">you type yes</text><path class=\"ln\" d=\"M570,92 L570,148\" marker-end=\"url(#do-tf--n)\"/><path class=\"ln warn dash\" d=\"M468,196 L152,196\" marker-end=\"url(#do-tf--warn)\"/><text class=\"warn\" x=\"310\" y=\"214\" text-anchor=\"middle\" font-size=\"11\">state updated</text></svg></div><figcaption>Plan is a dry run you can read; apply does exactly that plan. The state file is how Terraform knows which real resource each block in your code means.</figcaption></figure>\n\n<pre><code>$ terraform init       # download providers and modules, set up the backend\n$ terraform fmt        # format the files\n$ terraform validate   # catch syntax and type errors without touching AWS\n$ terraform plan\n  # aws_s3_bucket.site will be created\n  + resource \"aws_s3_bucket\" \"site\" {\n      + arn    = (known after apply)\n      + bucket = \"demee-devops-practice-2026\"\n      ...\nPlan: 3 to add, 0 to change, 0 to destroy.\n\n$ terraform apply      # shows the plan again, asks you to type \"yes\"\nApply complete! Resources: 3 added, 0 changed, 0 destroyed.\nOutputs:\nbucket_arn = \"arn:aws:s3:::demee-devops-practice-2026\"\n\n$ terraform destroy    # delete everything this configuration manages</code></pre>\n<p>Read plans carefully: <code>+</code> create, <code>~</code> update in place, <code>-</code> destroy, and <code>-/+</code> <b>destroy and re-create</b>. Some attribute changes (like a bucket's name) can't be made in place, and <code>-/+</code> on a database means losing its data. In CI, save the reviewed plan with <code>terraform plan -out=tfplan</code> and run <code>terraform apply tfplan</code>, so exactly what was reviewed is applied.</p>\n\n<h4>State, remote state and locking</h4>\n<p>After apply, Terraform writes <code>terraform.tfstate</code>: a JSON map from each resource address to the real object's ID and attributes. That's how it knows <code>aws_s3_bucket.site</code> is that bucket, and what to change next time. Two big problems with keeping it on your laptop: teammates don't have it, and it contains <b>secrets in plain text</b> (database passwords, keys). Teams use a <b>remote backend</b>:</p>\n<pre><code>terraform {\n  backend \"s3\" {\n    bucket       = \"demee-terraform-state\"\n    key          = \"practice-site/terraform.tfstate\"\n    region       = \"eu-central-1\"\n    encrypt      = true\n    use_lockfile = true      # S3-native locking (Terraform 1.10+)\n  }\n}</code></pre>\n<p><b>Locking</b> stops two people (or two pipelines) running apply at the same time and corrupting the state. Older setups used a DynamoDB table for this; since Terraform 1.11 that option is deprecated in favour of <code>use_lockfile</code>. Other backends include HCP Terraform, Azure Blob Storage and Google Cloud Storage. Backend blocks can't use variables, and after changing one you run <code>terraform init</code> again. Useful state commands: <code>terraform state list</code>, <code>terraform state show aws_s3_bucket.site</code>, <code>terraform output</code>.</p>\n\n\n<figure class=\"learn-diagram dg\" data-dg=\"do-tf-state\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 210\" role=\"img\" aria-label=\"You, a teammate and a CI pipeline all read and write one remote state file in an S3 backend, with a lock so only one apply runs at a time\" style=\"--dgw:680px\"><defs><marker id=\"do-tf-state--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker><marker id=\"do-tf-state--warn\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk warn\" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"b hi\" x=\"10\" y=\"14\" width=\"150\" height=\"50\" rx=\"6\"/><text class=\"tb ta\" x=\"85\" y=\"36.2\" text-anchor=\"middle\" font-size=\"13\">you</text><text class=\"t2\" x=\"85\" y=\"50.7\" text-anchor=\"middle\" font-size=\"10\">terraform apply</text><rect class=\"b\" x=\"10\" y=\"78\" width=\"150\" height=\"50\" rx=\"6\"/><text class=\"tb\" x=\"85\" y=\"100.2\" text-anchor=\"middle\" font-size=\"13\">a teammate</text><text class=\"t2\" x=\"85\" y=\"114.7\" text-anchor=\"middle\" font-size=\"10\">terraform apply</text><rect class=\"b\" x=\"10\" y=\"142\" width=\"150\" height=\"50\" rx=\"6\"/><text class=\"tb\" x=\"85\" y=\"164.2\" text-anchor=\"middle\" font-size=\"13\">CI pipeline</text><text class=\"t2\" x=\"85\" y=\"178.7\" text-anchor=\"middle\" font-size=\"10\">terraform apply</text><rect class=\"b ok\" x=\"330\" y=\"50\" width=\"200\" height=\"100\" rx=\"6\"/><text class=\"tb\" x=\"430\" y=\"81.7\" text-anchor=\"middle\" font-size=\"13\">s3 backend</text><text class=\"t2\" x=\"430\" y=\"97.0\" text-anchor=\"middle\" font-size=\"11\">terraform.tfstate</text><text class=\"t2\" x=\"430\" y=\"112.0\" text-anchor=\"middle\" font-size=\"11\">encrypted</text><text class=\"t2\" x=\"430\" y=\"127.0\" text-anchor=\"middle\" font-size=\"11\">lock: one at a time</text><path class=\"ln\" d=\"M162,39 L328,100\" marker-end=\"url(#do-tf-state--n)\"/><path class=\"ln warn dash\" d=\"M162,103 L328,100\" marker-end=\"url(#do-tf-state--warn)\"/><path class=\"ln\" d=\"M162,167 L328,100\" marker-end=\"url(#do-tf-state--n)\"/><text class=\"warn\" x=\"250\" y=\"196\" text-anchor=\"middle\" font-size=\"11\">a second apply waits for the lock</text><rect class=\"b\" x=\"570\" y=\"70\" width=\"100\" height=\"60\" rx=\"6\"/><text class=\"tb\" x=\"620\" y=\"97.2\" text-anchor=\"middle\" font-size=\"13\">AWS</text><text class=\"t2\" x=\"620\" y=\"111.7\" text-anchor=\"middle\" font-size=\"10\">resources</text><path class=\"ln\" d=\"M532,100 L568,100\" marker-end=\"url(#do-tf-state--n)\"/></svg></div><figcaption>One shared, locked state means everyone sees the same picture of what exists. A state file on one laptop is the classic way teams overwrite each other.</figcaption></figure>\n<h4>Modules</h4>\n<p>A <b>module</b> is a folder of <code>.tf</code> files you call like a function with inputs. Your root folder is itself a module. Write your own for repeated patterns, or use well-maintained ones from the Terraform Registry, always pinning a version:</p>\n<pre><code>module \"vpc\" {\n  source  = \"terraform-aws-modules/vpc/aws\"\n  version = \"~&gt; 6.0\"\n  name    = \"practice\"\n  cidr    = \"10.0.0.0/16\"\n}\n\nmodule \"logs_bucket\" {\n  source      = \"./modules/bucket\"     # your own module in a subfolder\n  bucket_name = \"demee-practice-logs\"\n}</code></pre>\n\n<h4>Drift</h4>\n<p><b>Drift</b> is when real infrastructure no longer matches the code, usually because someone changed it by hand in the console. <code>terraform plan</code> detects it (\"Objects have changed outside of Terraform\") and proposes changing it back. If the manual change was right, copy it into the code. <code>terraform apply -refresh-only</code> updates the state to match reality without changing any infrastructure. To bring an existing, hand-made resource under Terraform, write an <code>import</code> block (Terraform 1.5+) with the resource's address and real ID, then plan and apply.</p>\n\n<h4>Common mistakes</h4>\n<ul>\n<li><b>Committing state or secrets.</b> Add <code>.terraform/</code>, <code>*.tfstate</code>, <code>*.tfstate.*</code> and any <code>.tfvars</code> holding secrets to <code>.gitignore</code>. Do commit <code>.terraform.lock.hcl</code>: it pins exact provider versions for everyone.</li>\n<li><b>Hard-coded credentials</b> in the provider block. Use profiles locally and short-lived roles (OIDC) in CI.</li>\n<li><b>Renaming a resource</b> in code (say <code>site</code> to <code>website</code>) makes Terraform plan a destroy and a create. Add a <code>moved</code> block with <code>from = aws_s3_bucket.site</code> and <code>to = aws_s3_bucket.website</code> so it just updates the state.</li>\n<li><b>Unpinned versions</b>: a new major provider version can change behaviour. Always set <code>version</code> constraints.</li>\n<li><code>Error: No valid credential sources found</code>: Terraform can't find AWS credentials. Run <code>aws configure</code> or <code>aws sso login</code>, or set <code>AWS_PROFILE</code>.</li>\n<li><code>Error acquiring the state lock</code>: someone else is running, or a crashed run left a lock. Wait; only if you're sure nothing is running, use <code>terraform force-unlock LOCK_ID</code>.</li>\n<li><code>BucketAlreadyExists</code>: S3 names are global across all AWS accounts. Pick a more unique name.</li>\n</ul>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=ZaA0kNm18pE&amp;t=2167s\" target=\"_blank\" rel=\"noopener noreferrer\">Be A Better Dev · Cloud Computing Explained <span class=\"learn-sources-part\">· Infrastructure as Code (36:07)</span></a><a href=\"https://www.youtube.com/watch?v=OGYEXGy8ca4&amp;t=3179s\" target=\"_blank\" rel=\"noopener noreferrer\">Be A Better Dev · AWS Explained <span class=\"learn-sources-part\">· CI/CD and infrastructure on AWS (52:59)</span></a></div>","devops/configuration-management-with-ansible":"\n<p class=\"learn-lead\">Terraform creates servers; Ansible makes them useful: packages installed, config files in place, services running. You describe the desired state in YAML, and Ansible logs in over SSH and makes each machine match it, as many times as you like, on as many machines as you like.</p>\n\n<h4>How Ansible works</h4>\n<figure class=\"learn-diagram dg\" data-dg=\"do-ansible\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 230\" role=\"img\" aria-label=\"An Ansible control node with an inventory and a playbook connects over SSH to web1, web2 and db1, which need only SSH and Python, no agent\" style=\"--dgw:680px\"><defs><marker id=\"do-ansible--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"g hi\" x=\"10\" y=\"10\" width=\"250\" height=\"210\" rx=\"8\"/><text class=\"tg hi\" x=\"20\" y=\"26\" font-size=\"11\">control node: your laptop or CI</text><rect class=\"b\" x=\"26\" y=\"46\" width=\"218\" height=\"52\" rx=\"6\"/><text class=\"tb tm\" x=\"135\" y=\"69.2\" text-anchor=\"middle\" font-size=\"13\">inventory.ini</text><text class=\"t2\" x=\"135\" y=\"83.7\" text-anchor=\"middle\" font-size=\"10\">which machines</text><rect class=\"b hi\" x=\"26\" y=\"112\" width=\"218\" height=\"52\" rx=\"6\"/><text class=\"tb ta tm\" x=\"135\" y=\"135.2\" text-anchor=\"middle\" font-size=\"13\">site.yml</text><text class=\"t2\" x=\"135\" y=\"149.7\" text-anchor=\"middle\" font-size=\"10\">what they should look like</text><text class=\"ta\" x=\"135\" y=\"196\" text-anchor=\"middle\" font-size=\"11\">runs when you run it</text><rect class=\"b ok\" x=\"470\" y=\"14\" width=\"200\" height=\"56\" rx=\"6\"/><text class=\"tb\" x=\"570\" y=\"39.2\" text-anchor=\"middle\" font-size=\"13\">web1</text><text class=\"t2\" x=\"570\" y=\"53.7\" text-anchor=\"middle\" font-size=\"10\">SSH + Python 3, no agent</text><path class=\"ln\" d=\"M262,115 L468,42\" marker-end=\"url(#do-ansible--n)\"/><text class=\"tl\" x=\"360\" y=\"70\" text-anchor=\"middle\" font-size=\"11\">SSH</text><rect class=\"b ok\" x=\"470\" y=\"84\" width=\"200\" height=\"56\" rx=\"6\"/><text class=\"tb\" x=\"570\" y=\"109.2\" text-anchor=\"middle\" font-size=\"13\">web2</text><text class=\"t2\" x=\"570\" y=\"123.7\" text-anchor=\"middle\" font-size=\"10\">SSH + Python 3, no agent</text><path class=\"ln\" d=\"M262,115 L468,112\" marker-end=\"url(#do-ansible--n)\"/><rect class=\"b ok\" x=\"470\" y=\"154\" width=\"200\" height=\"56\" rx=\"6\"/><text class=\"tb\" x=\"570\" y=\"179.2\" text-anchor=\"middle\" font-size=\"13\">db1</text><text class=\"t2\" x=\"570\" y=\"193.7\" text-anchor=\"middle\" font-size=\"10\">SSH + Python 3, no agent</text><path class=\"ln\" d=\"M262,115 L468,182\" marker-end=\"url(#do-ansible--n)\"/></svg></div><figcaption>Ansible pushes: nothing runs on the servers until you run a playbook. The modules check first and only change what isn't already right.</figcaption></figure>\n\n<ul>\n<li><b>Agentless</b>: nothing to install on the servers. The <b>control node</b> (your laptop or a CI runner, Linux or macOS; on Windows use WSL) connects over plain <b>SSH</b> with your normal keys, copies a small Python module over, runs it and removes it. The <b>managed nodes</b> just need SSH and Python 3.</li>\n<li><b>Push-based</b>: changes happen when you run Ansible, not on a schedule.</li>\n<li><b>Modules</b> do the work: <code>ansible.builtin.apt</code>, <code>copy</code>, <code>template</code>, <code>service</code>, <code>user</code> and thousands more in collections. Each one knows how to check the current state before changing anything.</li>\n</ul>\n<pre><code>$ pipx install --include-deps ansible     # or: sudo apt install ansible\n$ ansible --version</code></pre>\n\n<h4>Inventory: which machines</h4>\n<p>The <b>inventory</b> lists hosts and sorts them into groups. The INI format is the simplest:</p>\n<pre><code># inventory.ini\n[web]\nweb1 ansible_host=203.0.113.11\nweb2 ansible_host=203.0.113.12\n\n[db]\ndb1 ansible_host=10.0.2.20\n\n[all:vars]\nansible_user=ubuntu\nansible_ssh_private_key_file=~/.ssh/id_ed25519</code></pre>\n<p>A small <code>ansible.cfg</code> next to it saves typing <code>-i inventory.ini</code> every time:</p>\n<pre><code># ansible.cfg\n[defaults]\ninventory = inventory.ini</code></pre>\n<p>In the cloud, <b>dynamic inventory</b> plugins (like <code>amazon.aws.aws_ec2</code>) build the list from your account instead, grouping instances by tags.</p>\n\n<h4>Ad-hoc commands</h4>\n<p>For one-off jobs you don't need a playbook: <code>ansible &lt;hosts&gt; -m &lt;module&gt; -a &lt;arguments&gt;</code>.</p>\n<pre><code>$ ansible all -m ansible.builtin.ping          # can Ansible log in and run Python?\nweb1 | SUCCESS =&gt; {\n    \"changed\": false,\n    \"ping\": \"pong\"\n}\n$ ansible web -a \"uptime\"                      # default module: command\nweb1 | CHANGED | rc=0 &gt;&gt;\n 10:42:07 up 12 days,  3:10,  0 user,  load average: 0.08, 0.03, 0.01\n$ ansible web -b -m ansible.builtin.apt -a \"name=htop state=present\"   # -b = sudo\n$ ansible db -m ansible.builtin.setup -a \"filter=ansible_distribution*\" # facts</code></pre>\n<p>(<code>ping</code> here isn't ICMP ping: it checks SSH login and Python.)</p>\n\n<h4>A playbook: install and run nginx</h4>\n<p>A <b>playbook</b> is a YAML file with one or more <b>plays</b>; each play maps a group of hosts to a list of <b>tasks</b>, run in order.</p>\n<pre><code># site.yml\n---\n- name: Install and run nginx\n  hosts: web\n  become: true                      # run tasks with sudo\n  vars:\n    site_title: \"DevOps practice\"\n\n  tasks:\n    - name: Install nginx\n      ansible.builtin.apt:\n        name: nginx\n        state: present\n        update_cache: true\n        cache_valid_time: 3600      # refresh the package list at most once an hour\n\n    - name: Deploy the nginx site config\n      ansible.builtin.template:\n        src: templates/site.conf.j2\n        dest: /etc/nginx/sites-available/default\n        owner: root\n        group: root\n        mode: \"0644\"\n      notify: Reload nginx          # trigger the handler, only if this changed\n\n    - name: Deploy the homepage\n      ansible.builtin.template:\n        src: templates/index.html.j2\n        dest: /var/www/html/index.html\n        mode: \"0644\"\n\n    - name: Make sure nginx is running and starts on boot\n      ansible.builtin.service:\n        name: nginx\n        state: started\n        enabled: true\n\n  handlers:\n    - name: Reload nginx\n      ansible.builtin.service:\n        name: nginx\n        state: reloaded</code></pre>\n<p>The templates use <b>Jinja2</b>: <code>templates/index.html.j2</code> could contain <code>&lt;h1&gt;{{ site_title }}&lt;/h1&gt;&lt;p&gt;Served by {{ inventory_hostname }}&lt;/p&gt;</code>, and each server gets its own name filled in.</p>\n<pre><code>$ ansible-playbook site.yml --syntax-check\n$ ansible-playbook site.yml\n...\nPLAY RECAP *********************************************************\nweb1   : ok=5    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0\nweb2   : ok=5    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0</code></pre>\n<p>That recap is from a <b>second</b> run: everything is already correct, so nothing changed. On the first run you'd see <code>changed</code> for the tasks that did real work, and the handler running at the end.</p>\n\n<h4>Idempotency and handlers</h4>\n<p><b>Idempotent</b> means running the same playbook once or ten times gives the same result. Modules make this work by describing a <i>state</i> (\"nginx is present\") rather than an action (\"install nginx\"): if it's already true, they report <code>ok</code> and do nothing. The raw <code>command</code> and <code>shell</code> modules can't know that, so they report <code>changed</code> every run. Prefer a real module, or add <code>creates:</code>/<code>removes:</code> so the command is skipped when its work is done:</p>\n<pre><code># not idempotent: adds another copy of the line on every run\n- name: Tune swappiness\n  ansible.builtin.shell: echo \"vm.swappiness=10\" &gt;&gt; /etc/sysctl.conf\n\n# idempotent: makes sure the line exists exactly once\n- name: Tune swappiness\n  ansible.builtin.lineinfile:\n    path: /etc/sysctl.conf\n    line: \"vm.swappiness=10\"</code></pre>\n<p><b>Handlers</b> are tasks that run only when notified, and only once, at the end of the play, however many tasks notified them. So nginx is reloaded only when its config actually changed, never on a run where nothing did.</p>\n\n<h4>Variables, roles and dry runs</h4>\n<ul>\n<li><b>Variables</b> can live in the play (<code>vars:</code>), in <code>group_vars/web.yml</code> (for every host in the group), in <code>host_vars/web1.yml</code>, or on the command line with <code>-e \"site_title=Test\"</code>, which beats everything else. <b>Facts</b> gathered at the start of each play, like <code>ansible_facts['distribution']</code>, are variables too.</li>\n<li><b>Roles</b> package tasks, handlers, templates and default variables into a reusable folder: <code>ansible-galaxy role init roles/nginx</code> creates the structure, and a play uses it with <code>roles: [nginx]</code>. Community roles and collections come from Ansible Galaxy.</li>\n<li><code>--check</code> is a dry run: it reports what <i>would</i> change without changing it. Add <code>--diff</code> to see the exact lines that would change in files. Note that tasks depending on earlier ones can fail in check mode (the service task can't find nginx if it wasn't really installed).</li>\n<li><code>--limit web1</code> runs on one host only, which is great for trying a change on one server first. <code>-v</code> to <code>-vvvv</code> adds detail when debugging.</li>\n<li>Secrets go in files encrypted with <b>Ansible Vault</b> (<code>ansible-vault create group_vars/web/vault.yml</code>), and you run with <code>--ask-vault-pass</code>.</li>\n</ul>\n\n<h4>Common errors and fixes</h4>\n<ul>\n<li><b>UNREACHABLE</b> with \"Permission denied (publickey)\": wrong user or key. Check <code>ansible_user</code> and <code>ansible_ssh_private_key_file</code>, and that <code>ssh ubuntu@203.0.113.11</code> works by hand.</li>\n<li><b>Host key verification failed</b>: the server isn't in <code>known_hosts</code> yet. Connect once with <code>ssh</code>, or add it with <code>ssh-keyscan</code>.</li>\n<li><b>\"Missing sudo password\"</b>: <code>become</code> needs a password on that server. Run with <code>-K</code> (<code>--ask-become-pass</code>).</li>\n<li><b>YAML errors</b>: indentation must be spaces, and a value that <i>starts</i> with <code>{{</code> must be quoted: <code>dest: \"{{ web_root }}/index.html\"</code>.</li>\n<li><b>\"… is undefined\"</b>: a variable is misspelled or not defined for that host. <code>ansible-inventory --host web1</code> shows which variables a host gets from the inventory.</li>\n</ul>\n","devops/monitoring-logging-alerting":"\n<p class=\"learn-lead\">Shipping a change is half the job; knowing whether production is healthy is the other half. Building on the observability overview in Concepts &amp; practices, this chapter covers Prometheus and PromQL, dashboards, alerting without noise, SLOs and error budgets with real numbers, and centralised logging.</p>\n\n<h4>Metrics, logs and traces</h4>\n<div class=\"learn-table-wrap\"><table class=\"learn-table\">\n<thead><tr><th></th><th>Metrics</th><th>Logs</th><th>Traces</th></tr></thead>\n<tbody>\n<tr><td>What</td><td>Numbers over time</td><td>Timestamped event records</td><td>One request's path through many services</td></tr>\n<tr><td>Answers</td><td>Is something wrong? How much, since when?</td><td>What exactly happened, to which request?</td><td>Where did the time go? Which service failed?</td></tr>\n<tr><td>Tools</td><td>Prometheus, CloudWatch</td><td>Loki, ELK / OpenSearch</td><td>OpenTelemetry, Jaeger, Tempo</td></tr>\n</tbody>\n</table></div>\n<p>A typical investigation uses all three: a metric alert says errors went up, a trace finds the slow service, its logs explain why.</p>\n\n<h4>Prometheus: the pull model</h4>\n<p>Prometheus <b>pulls</b> (scrapes): every few seconds it sends an HTTP GET to each target's <code>/metrics</code> endpoint and stores the values in its time-series database (15 days by default). Apps expose metrics with a client library; for everything else there are <b>exporters</b>, like <code>node_exporter</code> (port 9100) for a Linux machine's CPU, memory, disk and network. Short batch jobs that finish before a scrape can push to a <b>Pushgateway</b> instead.</p>\n<figure class=\"learn-diagram dg\" data-dg=\"do-prom\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 250\" role=\"img\" aria-label=\"Prometheus pulls metrics from your app and node_exporter, stores them, answers Grafana PromQL queries, and sends firing alerts to Alertmanager, which routes them to Slack or a pager\" style=\"--dgw:680px\"><defs><marker id=\"do-prom--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker><marker id=\"do-prom--ok\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk ok\" d=\"M0,0 L8,4 L0,8 z\"/></marker><marker id=\"do-prom--warn\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk warn\" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"b\" x=\"10\" y=\"20\" width=\"170\" height=\"50\" rx=\"6\"/><text class=\"tb\" x=\"95\" y=\"42.2\" text-anchor=\"middle\" font-size=\"13\">your app</text><text class=\"t2\" x=\"95\" y=\"56.7\" text-anchor=\"middle\" font-size=\"10\">:3000/metrics</text><rect class=\"b\" x=\"10\" y=\"90\" width=\"170\" height=\"50\" rx=\"6\"/><text class=\"tb\" x=\"95\" y=\"112.2\" text-anchor=\"middle\" font-size=\"13\">node_exporter</text><text class=\"t2\" x=\"95\" y=\"126.7\" text-anchor=\"middle\" font-size=\"10\">:9100/metrics</text><rect class=\"b hi\" x=\"260\" y=\"50\" width=\"170\" height=\"66\" rx=\"6\"/><text class=\"tb ta\" x=\"345\" y=\"73.2\" text-anchor=\"middle\" font-size=\"13\">Prometheus</text><text class=\"t2\" x=\"345\" y=\"87.7\" text-anchor=\"middle\" font-size=\"10\">scrapes every 15s</text><text class=\"t2\" x=\"345\" y=\"101.7\" text-anchor=\"middle\" font-size=\"10\">time-series DB</text><rect class=\"b ok\" x=\"510\" y=\"20\" width=\"160\" height=\"50\" rx=\"6\"/><text class=\"tb\" x=\"590\" y=\"42.2\" text-anchor=\"middle\" font-size=\"13\">Grafana</text><text class=\"t2\" x=\"590\" y=\"56.7\" text-anchor=\"middle\" font-size=\"10\">dashboards</text><rect class=\"b warn\" x=\"510\" y=\"110\" width=\"160\" height=\"50\" rx=\"6\"/><text class=\"tb\" x=\"590\" y=\"132.2\" text-anchor=\"middle\" font-size=\"13\">Alertmanager</text><text class=\"t2\" x=\"590\" y=\"146.7\" text-anchor=\"middle\" font-size=\"10\">routes alerts</text><rect class=\"b warn\" x=\"510\" y=\"190\" width=\"160\" height=\"44\" rx=\"6\"/><text class=\"tb\" x=\"590\" y=\"215.8\" text-anchor=\"middle\" font-size=\"12\">Slack, pager</text><path class=\"ln\" d=\"M258,70 L182,45\" marker-end=\"url(#do-prom--n)\"/><text class=\"tl\" x=\"220\" y=\"48\" text-anchor=\"middle\" font-size=\"11\">GET</text><path class=\"ln\" d=\"M258,96 L182,115\" marker-end=\"url(#do-prom--n)\"/><path class=\"ln ok\" d=\"M508,45 L432,72\" marker-end=\"url(#do-prom--ok)\"/><text class=\"ok\" x=\"470\" y=\"48\" text-anchor=\"middle\" font-size=\"11\">PromQL</text><path class=\"ln warn\" d=\"M432,100 L508,135\" marker-end=\"url(#do-prom--warn)\"/><text class=\"warn\" x=\"455\" y=\"134\" text-anchor=\"middle\" font-size=\"11\">alert rules</text><path class=\"ln warn\" d=\"M590,162 L590,188\" marker-end=\"url(#do-prom--warn)\"/></svg></div><figcaption>Prometheus does the pulling: if a target stops answering, that itself shows up as <code>up == 0</code>. Grafana only draws; Alertmanager only routes.</figcaption></figure>\n\n<pre><code># what Prometheus reads from http://10.0.2.11:3000/metrics\n# HELP http_requests_total Total HTTP requests.\n# TYPE http_requests_total counter\nhttp_requests_total{method=\"GET\",status=\"200\"} 10427\nhttp_requests_total{method=\"GET\",status=\"500\"} 31</code></pre>\n<pre><code># prometheus.yml\nglobal:\n  scrape_interval: 15s\n\nrule_files:\n  - alerts.yml\n\nscrape_configs:\n  - job_name: node\n    static_configs:\n      - targets: [\"10.0.2.11:9100\", \"10.0.2.12:9100\"]\n  - job_name: app\n    static_configs:\n      - targets: [\"10.0.2.11:3000\"]</code></pre>\n<p>Each series is a metric name plus <b>labels</b>. A <b>counter</b> only goes up (requests, errors), a <b>gauge</b> goes up and down (memory, queue length), a <b>histogram</b> counts observations into buckets (request durations) for percentiles. Because it pulls, Prometheus notices when a target stops answering and records it in the built-in <code>up</code> metric (1 = scrape worked, 0 = failed).</p>\n\n<h4>PromQL by example</h4>\n<pre><code>up == 0                                            # which targets are down?\n\nrate(http_requests_total[5m])                      # requests per second, averaged over 5 min\n\nsum by (status) (rate(http_requests_total[5m]))    # per-second rate, grouped by status code\n\n# error ratio: share of requests that returned 5xx\nsum(rate(http_requests_total{status=~\"5..\"}[5m]))\n  / sum(rate(http_requests_total[5m]))\n\n# 95th-percentile latency from a histogram\nhistogram_quantile(0.95, sum by (le) (rate(http_request_duration_seconds_bucket[5m])))\n\n# CPU busy % per machine\n100 * (1 - avg by (instance) (rate(node_cpu_seconds_total{mode=\"idle\"}[5m])))\n\n# will the root disk fill up within 24 hours at the current trend?\npredict_linear(node_filesystem_avail_bytes{mountpoint=\"/\"}[6h], 24 * 3600) &lt; 0</code></pre>\n<p>Rule of thumb: a raw counter is useless on a graph (it just climbs), so always wrap counters in <code>rate()</code> <i>before</i> you <code>sum</code> them. Never <code>rate()</code> a gauge.</p>\n\n<h4>Grafana dashboards</h4>\n<p><b>Grafana</b> stores no data itself; it queries <b>data sources</b> (Prometheus, Loki, CloudWatch, SQL…) and draws <b>panels</b>. <b>Variables</b> like <code>$instance</code> add a dropdown so one dashboard serves every server. Import community dashboards by ID: \"Node Exporter Full\" (1860) is the classic for Linux hosts. Put the golden signals across the top and details below.</p>\n\n<h4>The four golden signals</h4>\n<p>Google's SRE book suggests that if you can only measure four things about a user-facing service, measure these:</p>\n<ol>\n<li><b>Latency</b>: how long requests take. Track slow <i>errors</i> separately from slow successes, and use percentiles (p95, p99), since averages hide the unlucky users.</li>\n<li><b>Traffic</b>: demand, like requests per second.</li>\n<li><b>Errors</b>: the rate of failed requests (5xx, and also wrong answers or requests that were too slow).</li>\n<li><b>Saturation</b>: how full the service is: CPU, memory, disk, connection pools, queue length.</li>\n</ol>\n<p>Related checklists: <b>RED</b> (Rate, Errors, Duration) for services, <b>USE</b> (Utilisation, Saturation, Errors) for resources.</p>\n\n<h4>Alerting and on-call</h4>\n<p>Prometheus evaluates <b>alerting rules</b> and sends firing alerts to <b>Alertmanager</b>, which groups related alerts, removes duplicates, applies silences during maintenance, and routes them to Slack, email or a paging tool such as PagerDuty or Opsgenie.</p>\n<pre><code># alerts.yml\ngroups:\n  - name: app\n    rules:\n      - alert: HighErrorRate\n        expr: |\n          sum(rate(http_requests_total{status=~\"5..\"}[5m]))\n            / sum(rate(http_requests_total[5m])) &gt; 0.05\n        for: 5m                      # must stay true for 5 minutes before firing\n        labels:\n          severity: page\n        annotations:\n          summary: \"More than 5% of requests are failing\"\n          description: \"Error ratio is {{ $value | humanizePercentage }}.\"\n\n$ promtool check config prometheus.yml    # also checks the rule files it loads</code></pre>\n<ul>\n<li><b>Page on symptoms users feel</b> (errors, latency, downtime), not every cause. High CPU with happy users belongs on a dashboard or in a ticket.</li>\n<li><b>Every page must be actionable</b>, with a short <b>runbook</b> linked in the annotations. If the answer is \"ignore it\", fix or delete the alert: teams paged constantly start ignoring pages.</li>\n<li><code>for:</code> stops <b>flapping</b> on brief spikes.</li>\n<li><b>On-call</b> is a rotation of engineers who respond to pages, with escalation if nobody acknowledges. After a major incident, write a <b>blameless postmortem</b>: timeline, root cause, follow-ups, focused on the system rather than who slipped.</li>\n</ul>\n\n<h4>SLI, SLO, SLA and the error budget, with numbers</h4>\n<p>A quick reminder: the <b>SLI</b> is what you measure, the <b>SLO</b> is your internal target, the <b>SLA</b> is the contract with customers. Say your API promises customers 99.5% (the SLA, with credits if missed) and targets 99.9% internally (the SLO), measured as \"the share of requests that return a non-5xx response within 500 ms, over 30 days\". The stricter SLO warns you long before the contract is at risk.</p>\n<ul>\n<li>The API serves 200 requests per minute. 30 days = 43,200 minutes, so 8,640,000 requests.</li>\n<li><b>Error budget</b> = 100% − 99.9% = 0.1% of requests = <b>8,640 bad requests</b> allowed in 30 days. (In time terms, 0.1% of 30 days is 43.2 minutes of total outage.)</li>\n<li>On day 12, a bad deploy makes half the requests fail for 30 minutes: 30 × 200 × 50% = <b>3,000</b> bad requests. That's about 35% of the budget gone; 5,640 remain.</li>\n<li><b>Burn rate</b> is how fast you're spending: the actual error rate divided by the allowed one. A steady 0.5% error rate is 0.5 / 0.1 = a burn rate of 5, which would use up a 30-day budget in 30 / 5 = 6 days.</li>\n</ul>\n<p>Teams agree in advance what happens when the budget runs low: freeze risky releases and spend the time on reliability. Good SLO alerts page on fast burn; for example, the Google SRE workbook suggests paging when 2% of a 30-day budget is spent within one hour (a burn rate of 14.4).</p>\n<div class=\"learn-table-wrap\"><table class=\"learn-table\">\n<thead><tr><th>SLO</th><th>Allowed downtime per 30 days</th></tr></thead>\n<tbody>\n<tr><td>99%</td><td>7 h 12 min</td></tr>\n<tr><td>99.5%</td><td>3 h 36 min</td></tr>\n<tr><td>99.9%</td><td>43 min 12 s</td></tr>\n<tr><td>99.95%</td><td>21 min 36 s</td></tr>\n<tr><td>99.99%</td><td>4 min 19 s</td></tr>\n</tbody>\n</table></div>\n\n\n<figure class=\"learn-diagram dg\" data-dg=\"do-budget\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 190\" role=\"img\" aria-label=\"An error budget bar: 8,640 bad requests allowed per 30 days; a bad deploy on day 12 used 3,000 of them, 35 percent, leaving 5,640\" style=\"--dgw:680px\"><text class=\"tb\" x=\"10\" y=\"22\" text-anchor=\"start\" font-size=\"12\">SLO 99.9% over 30 days at 200 requests a minute: 8,640 bad requests allowed</text><rect class=\"b bad\" x=\"20\" y=\"44\" width=\"222\" height=\"50\" rx=\"6\"/><text class=\"tb\" x=\"131\" y=\"65.8\" text-anchor=\"middle\" font-size=\"12\">3,000 spent</text><text class=\"t2\" x=\"131\" y=\"80.2\" text-anchor=\"middle\" font-size=\"10\">bad deploy, day 12</text><rect class=\"b ok\" x=\"242\" y=\"44\" width=\"418\" height=\"50\" rx=\"6\"/><text class=\"tb\" x=\"451\" y=\"65.8\" text-anchor=\"middle\" font-size=\"12\">5,640 left</text><text class=\"t2\" x=\"451\" y=\"80.2\" text-anchor=\"middle\" font-size=\"10\">spend on releases, or save</text><text class=\"bad tb\" x=\"242\" y=\"120\" text-anchor=\"middle\" font-size=\"12\">35% gone</text><text class=\"t2\" x=\"340\" y=\"154\" text-anchor=\"middle\" font-size=\"12\">burn rate = actual error rate / allowed error rate</text><text class=\"t2\" x=\"340\" y=\"176\" text-anchor=\"middle\" font-size=\"11\">0.5% / 0.1% = 5: the whole month&#x27;s budget gone in 6 days</text></svg></div><figcaption>The budget turns reliability into a number the team can spend. Plenty left: ship faster. Running low: slow down and fix what's burning it.</figcaption></figure>\n<h4>Centralised logging</h4>\n<p>With many servers, and containers that vanish with their logs, SSH plus <code>grep</code> doesn't scale. An <b>agent</b> on each machine ships logs to a central store searchable in one place:</p>\n<ul>\n<li><b>ELK / Elastic Stack</b>: Elasticsearch indexes the full text of every line, Logstash or Beats collect, Kibana searches. Powerful, but indexing everything costs storage and memory. <b>OpenSearch</b> is the open-source fork.</li>\n<li><b>Grafana Loki</b>: indexes only a few <b>labels</b> (app, env, host) and stores lines compressed, so it's much cheaper, and you query it in Grafana beside your metrics. Collect with <b>Grafana Alloy</b> (Promtail reached end of life in March 2026), Fluent Bit or Vector.</li>\n</ul>\n<pre><code>{app=\"api\", env=\"prod\"} |= \"error\"                        # lines containing \"error\"\n{app=\"api\"} | json | status &gt;= 500                        # parse JSON logs, filter on a field\nsum by (app) (rate({env=\"prod\"} |= \"error\" [5m]))         # error lines per second, per app</code></pre>\n<p>Log <b>structured JSON</b> with consistent fields (level, message, request ID) so you can filter logs like data and follow one request across services. Never log passwords, tokens or personal data, and set a retention period: logs get expensive.</p>\n\n<h4>Common problems</h4>\n<ul>\n<li><b>Target DOWN</b> on Prometheus's Status → Targets page: \"connection refused\" means nothing listens on that port; \"context deadline exceeded\" usually means a firewall or security group is blocking the scrape.</li>\n<li><b>Grafana shows \"No data\"</b>: wrong data source, a time range with no data, or a typo in the metric or label name. Run the query in Prometheus's own UI first.</li>\n<li><b>Prometheus using huge amounts of memory</b>: <b>high cardinality</b>. Every unique label combination is a separate series, so labels like user ID, email or full URL create millions. Keep label values to small, fixed sets.</li>\n<li><b>Counters drop to zero after a deploy</b>: they reset on restart. <code>rate()</code> handles that; raw values don't.</li>\n</ul>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=OGYEXGy8ca4&amp;t=2951s\" target=\"_blank\" rel=\"noopener noreferrer\">Be A Better Dev · AWS Explained <span class=\"learn-sources-part\">· Monitoring and logging on AWS (49:11)</span></a><a href=\"https://www.youtube.com/watch?v=guCFLTU-XRM&amp;t=305s\" target=\"_blank\" rel=\"noopener noreferrer\">Cloud Champ · How I use Python as a DevOps Engineer <span class=\"learn-sources-part\">· Python for monitoring and alerting (5:05)</span></a></div>","devops/yaml-in-15-minutes":"\n<p class=\"learn-lead\">Docker Compose files, Kubernetes manifests, GitHub Actions workflows, Ansible playbooks, Helm values: they're all YAML. The format is simple, but one wrong space breaks it, and a few of its rules surprise everyone once. Learn them here and the rest of DevOps gets easier to read.</p>\n\n<h4>Keys and values</h4>\n<p>YAML describes data with <code>key: value</code> pairs. The space after the colon is required.</p>\n<pre><code>name: web\nreplicas: 3\ndebug: false\nimage: nginx:1.27      # a colon inside a value is fine when it's not followed by a space</code></pre>\n\n<h4>Indentation is the structure</h4>\n<p>Nesting is shown by indentation, the same idea as Python. Use <b>spaces only, never tabs</b>, and be consistent; two spaces per level is the convention almost everywhere.</p>\n<pre><code>database:\n  host: db.internal\n  port: 5432\n  credentials:\n    user: app</code></pre>\n<p>Here <code>port</code> belongs to <code>database</code>, and <code>user</code> belongs to <code>credentials</code>. Move <code>port</code> two spaces left and it becomes a top-level key instead; nothing errors, the meaning just silently changes.</p>\n\n<h4>Lists</h4>\n<p>A dash and a space start each list item. Items can be simple values or whole maps, which is exactly how Kubernetes lists containers and how Actions lists steps:</p>\n<pre><code>ports:\n  - 80\n  - 443\n\ncontainers:\n  - name: web          # one item: a map with two keys\n    image: nginx:1.27\n  - name: sidecar      # the next item\n    image: busybox:1.36</code></pre>\n<p>There's also a compact \"flow\" style taken from JSON: <code>ports: [80, 443]</code> and <code>labels: {app: web, tier: front}</code>. Use it for short things only.</p>\n\n<h4>Strings, and when to quote them</h4>\n<p>Most text needs no quotes. Single quotes keep everything exactly as written; double quotes allow escapes like <code>\\n</code>. Quote a value when YAML might read it as something else:</p>\n<ul>\n<li><b>Numbers that are really text</b>: <code>version: 3.10</code> is read as the number 3.1. Write <code>\"3.10\"</code>. This is the classic bug in <code>python-version</code> in GitHub Actions.</li>\n<li><b>yes, no, on, off</b>: some tools read these as true and false. Quote them when you mean the word.</li>\n<li><b>Leading zeros and colons</b>: <code>mode: 0755</code> can be read as an octal number, and older parsers turn <code>22:22</code> into a base-60 number. Quote file modes and port mappings like <code>\"8080:80\"</code>.</li>\n<li><b>Values starting with special characters</b> such as <code>*</code>, <code>&amp;</code>, <code>!</code>, <code>{</code>, <code>[</code>, <code>@</code>, <code>`</code> or <code>#</code>.</li>\n<li><b>Kubernetes environment variables</b> must be strings: <code>value: \"8080\"</code>, not <code>value: 8080</code>.</li>\n</ul>\n\n<h4>Multi-line text</h4>\n<p>Scripts inside CI files are usually written as block text:</p>\n<pre><code>run: |                 # | keeps every line break: perfect for shell commands\n  pip install -r requirements.txt\n  pytest -q\n\ndescription: &gt;          # &gt; folds lines into one paragraph\n  This text is written over\n  several lines but becomes one.</code></pre>\n<p>Adding a minus (<code>|-</code> or <code>&gt;-</code>) drops the final newline.</p>\n\n<h4>Comments, several documents and reuse</h4>\n<ul>\n<li><code>#</code> starts a comment, anywhere outside quotes.</li>\n<li><code>---</code> separates several documents in one file. Kubernetes uses it to put a Deployment and its Service in the same file.</li>\n<li><b>Anchors and aliases</b> reuse a block: <code>&amp;name</code> labels it, <code>*name</code> repeats it, and <code>&lt;&lt;: *name</code> merges a map into another. Docker Compose (with <code>x-</code> fields) and GitLab CI use this a lot:</li>\n</ul>\n<pre><code>x-common: &amp;common\n  restart: unless-stopped\n  logging:\n    options: {max-size: \"10m\"}\n\nservices:\n  web:\n    &lt;&lt;: *common\n    image: ghcr.io/you/web:1.0\n  worker:\n    &lt;&lt;: *common\n    image: ghcr.io/you/worker:1.0</code></pre>\n\n<h4>YAML and JSON</h4>\n<p>Modern YAML is a superset of JSON, so any JSON document is also valid YAML. That's why Kubernetes accepts both, and why Python chapter 8 can load either into the same dicts and lists.</p>\n<figure class=\"learn-diagram dg\" data-dg=\"do-yaml-json\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 220\" role=\"img\" aria-label=\"The same data written as YAML, with indentation and dashes, and as JSON, with braces, brackets and quotes\" style=\"--dgw:680px\"><defs><marker id=\"do-yaml-json--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker><marker id=\"do-yaml-json--n--s\" markerWidth=\"9\" markerHeight=\"9\" refX=\"1\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M8,0 L0,4 L8,8 z\"/></marker></defs><rect class=\"g hi\" x=\"10\" y=\"10\" width=\"300\" height=\"200\" rx=\"8\"/><text class=\"tg hi\" x=\"20\" y=\"26\" font-size=\"11\">YAML</text><text class=\"tc\" x=\"28\" y=\"48\" text-anchor=\"start\" font-size=\"13\">name: web</text><text class=\"tc\" x=\"28\" y=\"69\" text-anchor=\"start\" font-size=\"13\">replicas: 3</text><text class=\"tc\" x=\"28\" y=\"90\" text-anchor=\"start\" font-size=\"13\">ports:</text><text class=\"tc\" x=\"28\" y=\"111\" text-anchor=\"start\" font-size=\"13\">  - 80</text><text class=\"tc\" x=\"28\" y=\"132\" text-anchor=\"start\" font-size=\"13\">  - 443</text><text class=\"tc\" x=\"28\" y=\"153\" text-anchor=\"start\" font-size=\"13\">env:</text><text class=\"tc\" x=\"28\" y=\"174\" text-anchor=\"start\" font-size=\"13\">  DEBUG: false</text><rect class=\"g ok\" x=\"370\" y=\"10\" width=\"300\" height=\"200\" rx=\"8\"/><text class=\"tg ok\" x=\"380\" y=\"26\" font-size=\"11\">the same data in JSON</text><text class=\"tc\" x=\"388\" y=\"48\" text-anchor=\"start\" font-size=\"13\">{</text><text class=\"tc\" x=\"388\" y=\"69\" text-anchor=\"start\" font-size=\"13\">  &quot;name&quot;: &quot;web&quot;,</text><text class=\"tc\" x=\"388\" y=\"90\" text-anchor=\"start\" font-size=\"13\">  &quot;replicas&quot;: 3,</text><text class=\"tc\" x=\"388\" y=\"111\" text-anchor=\"start\" font-size=\"13\">  &quot;ports&quot;: [80, 443],</text><text class=\"tc\" x=\"388\" y=\"132\" text-anchor=\"start\" font-size=\"13\">  &quot;env&quot;: {&quot;DEBUG&quot;: false}</text><text class=\"tc\" x=\"388\" y=\"153\" text-anchor=\"start\" font-size=\"13\">}</text><path class=\"ln\" d=\"M312,110 L368,110\" marker-end=\"url(#do-yaml-json--n)\" marker-start=\"url(#do-yaml-json--n--s)\"/><text class=\"tb\" x=\"340\" y=\"100\" text-anchor=\"middle\" font-size=\"14\">=</text></svg></div><figcaption>Indentation in YAML does the job of JSON's braces, and a leading dash marks a list item. Both load into the same dicts and lists.</figcaption></figure>\n\n\n<h4>Check before you apply</h4>\n<pre><code>$ pip install yamllint &amp;&amp; yamllint compose.yaml           # style and syntax\n$ python3 -c 'import sys, yaml; yaml.safe_load(open(sys.argv[1]))' file.yaml\n$ docker compose config                                      # Compose: shows the final, merged file\n$ kubectl apply --dry-run=client -f web.yaml                 # Kubernetes: validates without changing anything</code></pre>\n<p>For GitHub Actions, the <code>actionlint</code> tool catches mistakes in workflow files before you push. VS Code's YAML extension underlines most errors as you type.</p>\n\n<h4>Common errors</h4>\n<ul>\n<li><b><code>mapping values are not allowed here</code></b>: a missing space after a colon, or a colon followed by a space inside an unquoted value. Quote the value.</li>\n<li><b><code>found character '\\t' that cannot start any token</code></b>: a tab. Replace it with spaces, and set your editor to insert spaces.</li>\n<li><b><code>did not find expected key</code></b> or <b><code>could not find expected ':'</code></b>: inconsistent indentation, usually one line off by a space.</li>\n<li><b><code>cannot unmarshal number into ... of type string</code></b> from Kubernetes: a number where text is expected (environment values, annotations). Quote it.</li>\n</ul>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=s_o8dwzRlu4&amp;t=1588s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Kubernetes Crash Course <span class=\"learn-sources-part\">· Kubernetes configuration files (26:28)</span></a><a href=\"https://www.youtube.com/watch?v=R8_veQiYBjI&amp;t=784s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · GitHub Actions Tutorial <span class=\"learn-sources-part\">· Syntax of the workflow file (13:04)</span></a></div>","devops/a-complete-ci-cd-pipeline":"\n<p class=\"learn-lead\">Git chapter 6 introduced workflows. Here you build the whole pipeline a real team runs: every push and pull request is tested, every merge to <code>main</code> builds a Docker image and pushes it to a registry, and the new version is deployed to a server, with secrets kept out of the code and a manual approval before production.</p>\n\n<h4>The plan</h4>\n<ol>\n<li><b>Test</b> on every push and pull request. Nothing else happens if this fails.</li>\n<li><b>Build and push</b> a Docker image, but only for <code>main</code>, tagged with the commit's SHA so every version is traceable.</li>\n<li><b>Deploy</b> that exact image to the server, after a person approves it.</li>\n</ol>\n<p>The repository holds the app, its tests, a <code>Dockerfile</code>, and the workflow in <code>.github/workflows/pipeline.yml</code>. The server holds a <code>compose.yaml</code> that runs the image.</p>\n\n\n<figure class=\"learn-diagram dg\" data-dg=\"do-pipeline\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 200\" role=\"img\" aria-label=\"The pipeline: a push or pull request runs the tests; on main a passing build pushes an image tagged with the commit SHA; after a person approves, that exact image is deployed\" style=\"--dgw:680px\"><defs><marker id=\"do-pipeline--bad\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk bad\" d=\"M0,0 L8,4 L0,8 z\"/></marker><marker id=\"do-pipeline--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"b warn\" x=\"10\" y=\"40\" width=\"118\" height=\"64\" rx=\"6\"/><text class=\"tb\" x=\"69\" y=\"76.2\" text-anchor=\"middle\" font-size=\"13\">push / PR</text><rect class=\"b\" x=\"144\" y=\"40\" width=\"118\" height=\"64\" rx=\"6\"/><text class=\"tb\" x=\"203\" y=\"69.2\" text-anchor=\"middle\" font-size=\"13\">test</text><text class=\"t2\" x=\"203\" y=\"83.7\" text-anchor=\"middle\" font-size=\"10\">every push</text><path class=\"ln\" d=\"M130,72 L142,72\" marker-end=\"url(#do-pipeline--n)\"/><rect class=\"b hi\" x=\"278\" y=\"40\" width=\"118\" height=\"64\" rx=\"6\"/><text class=\"tb ta\" x=\"337\" y=\"69.2\" text-anchor=\"middle\" font-size=\"13\">build + push</text><text class=\"t2\" x=\"337\" y=\"83.7\" text-anchor=\"middle\" font-size=\"10\">main only, :sha</text><path class=\"ln\" d=\"M264,72 L276,72\" marker-end=\"url(#do-pipeline--n)\"/><rect class=\"b warn\" x=\"412\" y=\"40\" width=\"118\" height=\"64\" rx=\"6\"/><text class=\"tb\" x=\"471\" y=\"69.2\" text-anchor=\"middle\" font-size=\"13\">approve</text><text class=\"t2\" x=\"471\" y=\"83.7\" text-anchor=\"middle\" font-size=\"10\">a person</text><path class=\"ln\" d=\"M398,72 L410,72\" marker-end=\"url(#do-pipeline--n)\"/><rect class=\"b ok\" x=\"546\" y=\"40\" width=\"118\" height=\"64\" rx=\"6\"/><text class=\"tb\" x=\"605\" y=\"69.2\" text-anchor=\"middle\" font-size=\"13\">deploy</text><text class=\"t2\" x=\"605\" y=\"83.7\" text-anchor=\"middle\" font-size=\"10\">the same image</text><path class=\"ln\" d=\"M532,72 L544,72\" marker-end=\"url(#do-pipeline--n)\"/><path class=\"ln bad\" d=\"M203,106 L203,150\" marker-end=\"url(#do-pipeline--bad)\"/><text class=\"bad\" x=\"203\" y=\"170\" text-anchor=\"middle\" font-size=\"11\">fails: nothing else runs</text><text class=\"ok\" x=\"480\" y=\"150\" text-anchor=\"middle\" font-size=\"11\">same image tested, built once, deployed</text></svg></div><figcaption>Each stage only runs if the one before it passed. Tagging by commit SHA means you always know exactly which code is live, and rolling back is just redeploying an older tag.</figcaption></figure>\n<h4>The whole workflow</h4>\n<pre><code>name: pipeline\non:\n  push:\n    branches: [main]\n  pull_request:\n\npermissions:\n  contents: read                     # the default for every job: read the code, nothing more\n\nconcurrency:\n  group: pipeline-${{ github.ref }}\n  cancel-in-progress: true           # a newer push cancels the older run of the same branch\n\njobs:\n  test:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v4\n      - uses: actions/setup-python@v5\n        with:\n          python-version: \"3.12\"     # quoted: see YAML in 15 minutes\n          cache: pip\n      - run: pip install -r requirements-dev.txt\n      - run: pytest -q\n\n  build:\n    needs: test\n    if: github.ref == 'refs/heads/main'\n    runs-on: ubuntu-latest\n    permissions:\n      contents: read\n      packages: write                # allowed to push to GitHub Container Registry\n    steps:\n      - uses: actions/checkout@v4\n      - name: Image name (registries need lowercase)\n        run: echo \"IMAGE=ghcr.io/${GITHUB_REPOSITORY,,}\" &gt;&gt; \"$GITHUB_ENV\"\n      - uses: docker/setup-buildx-action@v3\n      - uses: docker/login-action@v3\n        with:\n          registry: ghcr.io\n          username: ${{ github.actor }}\n          password: ${{ secrets.GITHUB_TOKEN }}\n      - uses: docker/build-push-action@v6\n        with:\n          push: true\n          tags: ${{ env.IMAGE }}:${{ github.sha }},${{ env.IMAGE }}:latest\n          cache-from: type=gha\n          cache-to: type=gha,mode=max\n\n  deploy:\n    needs: build\n    runs-on: ubuntu-latest\n    environment: production          # waits for approval if the environment requires it\n    steps:\n      - name: Deploy over SSH\n        env:\n          SSH_KEY: ${{ secrets.SSH_KEY }}\n          HOST: ${{ secrets.DEPLOY_HOST }}\n          DEPLOY_USER: ${{ secrets.DEPLOY_USER }}\n          TAG: ${{ github.sha }}\n        run: |\n          mkdir -p ~/.ssh\n          printf '%s\\n' \"$SSH_KEY\" &gt; ~/.ssh/id_ed25519\n          chmod 600 ~/.ssh/id_ed25519\n          ssh-keyscan -H \"$HOST\" &gt;&gt; ~/.ssh/known_hosts\n          ssh \"$DEPLOY_USER@$HOST\" \"cd /srv/app &amp;&amp; echo TAG=$TAG &gt; .env &amp;&amp; docker compose pull &amp;&amp; docker compose up -d\"</code></pre>\n\n<h4>Stage by stage</h4>\n<ul>\n<li><b>test</b> uses <code>cache: pip</code> so dependencies aren't downloaded from scratch every run. <code>requirements-dev.txt</code> holds the app's packages plus test tools like pytest.</li>\n<li><b>build</b> runs only after <code>test</code> passes (<code>needs</code>) and only on <code>main</code> (<code>if</code>). The image goes to GHCR (GitHub Container Registry) using the automatic <code>GITHUB_TOKEN</code>, so there's no password to manage. Tagging with <code>github.sha</code> means you can always tell which commit is running, and roll back to any of them. The <code>gha</code> cache reuses Docker layers between runs.</li>\n<li><b>deploy</b> logs in to the server over SSH and tells Docker Compose to pull and start the new tag. Writing the tag into <code>.env</code> on the server means a later manual <code>docker compose up</code> keeps the same version.</li>\n</ul>\n<p>On the server, <code>/srv/app/compose.yaml</code> uses that tag:</p>\n<pre><code>services:\n  web:\n    image: ghcr.io/you/app:${TAG:-latest}\n    restart: unless-stopped\n    ports:\n      - \"80:8000\"</code></pre>\n<p>New GHCR packages are private, so log the server in once with a GitHub token that only has <code>read:packages</code>: <code>docker login ghcr.io -u you</code>. Or make the package public in its settings on GitHub.</p>\n\n<h4>Secrets and environments</h4>\n<ul>\n<li>Add secrets under the repository's Settings, then Secrets and variables, then Actions. Workflows read them as <code>${{ secrets.NAME }}</code>, and GitHub masks them in logs. Never <code>echo</code> them anyway.</li>\n<li>The deploy key is a <b>separate SSH key pair</b> made just for CI. Its public half goes into <code>~/.ssh/authorized_keys</code> of a dedicated <code>deploy</code> user on the server; the private half (including the BEGIN and END lines) goes into the <code>SSH_KEY</code> secret.</li>\n<li>Under Settings, then <b>Environments</b>, create <code>production</code> and add <b>required reviewers</b> (available on public repositories, and on private ones with paid plans). The deploy job then waits for a click before it runs. Environments can also hold their own secrets, so a staging job can't see production's.</li>\n<li><code>ssh-keyscan</code> trusts whatever host answers the first time. For more safety, store the server's known_hosts line as a secret and write that instead.</li>\n<li>Deploying to a cloud? Prefer <b>OIDC</b> over stored access keys: with <code>permissions: id-token: write</code>, the <code>aws-actions/configure-aws-credentials</code> action exchanges a short-lived GitHub token for temporary AWS credentials, so there's no long-lived key to leak (Cloud chapter 4 covers roles).</li>\n</ul>\n\n<h4>Keeping main green</h4>\n<p>Under Settings, then Branches, add a <b>branch protection rule</b> (or ruleset) for <code>main</code> that requires the <code>test</code> job to pass before a pull request can be merged. Combined with the pipeline above, broken code can't reach <code>main</code>, and <code>main</code> is always deployable.</p>\n\n<h4>Rolling back</h4>\n<p>Because every image is tagged with its commit, rolling back is just deploying an older tag. Either re-run the old workflow run from the Actions tab, or add a manual trigger:</p>\n<pre><code>on:\n  workflow_dispatch:\n    inputs:\n      tag:\n        description: \"Image tag (commit SHA) to deploy\"\n        required: true</code></pre>\n<p>and use <code>${{ inputs.tag }}</code> instead of <code>github.sha</code> in the deploy step.</p>\n\n<h4>Deploying to Kubernetes instead</h4>\n<p>The test and build jobs stay exactly the same. The deploy step changes to something like <code>kubectl set image deployment/web web=$IMAGE:$TAG</code> or <code>helm upgrade --install</code>, with the cluster credentials coming from a secret or OIDC. Bigger teams often go one step further with <b>GitOps</b>: the pipeline only updates the image tag in a Git repository, and a tool inside the cluster such as Argo CD notices and applies it.</p>\n\n<h4>Common failures</h4>\n<ul>\n<li><b><code>denied: permission_denied: write_package</code></b>: the job is missing <code>packages: write</code>, or the package already exists and isn't linked to this repository (fix it in the package's settings).</li>\n<li><b><code>repository name must be lowercase</code></b>: use the lowercase step shown above.</li>\n<li><b><code>Host key verification failed</code></b>: <code>known_hosts</code> wasn't written, or the server was rebuilt and its key changed.</li>\n<li><b><code>Permission denied (publickey)</code></b>: wrong user, the public key isn't in <code>authorized_keys</code>, or the secret lost its first or last line.</li>\n<li><b>The workflow never starts</b>: the file isn't in <code>.github/workflows/</code>, the branch name in <code>on:</code> is wrong, or the YAML is invalid (the Actions tab shows the error).</li>\n<li><b>Secrets are empty</b>: pull requests from forks don't get secrets, on purpose. Run the deploy only on pushes to <code>main</code>, as above.</li>\n</ul>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=R8_veQiYBjI&amp;t=590s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · GitHub Actions Tutorial <span class=\"learn-sources-part\">· Create a CI workflow (9:50)</span></a><a href=\"https://www.youtube.com/watch?v=R8_veQiYBjI&amp;t=1475s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · GitHub Actions Tutorial <span class=\"learn-sources-part\">· Build a Docker image and push it (24:35)</span></a><a href=\"https://www.youtube.com/watch?v=MIWH2CpVyXs&amp;t=406s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · The ONLY Continuous Integration (CI) Tutorial <span class=\"learn-sources-part\">· What a CI pipeline is (6:46)</span></a><a href=\"https://www.youtube.com/watch?v=qP8kir2GUgo&amp;t=3284s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · GitLab CI/CD Tutorial <span class=\"learn-sources-part\">· Deploy the application (54:44)</span></a></div>","devops/capstone-ship-an-app-end-to-end":"\n<p class=\"learn-lead\">This chapter is a project, not a lesson. You'll take a small web app from an empty folder to a live HTTPS address, with tests, a container image, an automated pipeline and basic monitoring, using every topic in these Docs. Do it once on your own and you'll have something real to show, and you'll know where your gaps are.</p>\n\n<h4>What you'll build</h4>\n<p>A tiny Python API with two endpoints, running in Docker on a cloud server behind HTTPS, deployed automatically whenever you merge to <code>main</code>. Budget a weekend. Each step names the chapter to revisit if you get stuck.</p>\n<figure class=\"learn-diagram dg\" data-dg=\"do-capstone\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 270\" role=\"img\" aria-label=\"The capstone: you push to GitHub, Actions tests and builds an image to ghcr.io and deploys over SSH; on the server Caddy serves HTTPS and forwards to the web container\" style=\"--dgw:680px\"><defs><marker id=\"do-capstone--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"b hi\" x=\"10\" y=\"20\" width=\"120\" height=\"52\" rx=\"6\"/><text class=\"tb ta\" x=\"70\" y=\"43.2\" text-anchor=\"middle\" font-size=\"13\">you</text><text class=\"t2\" x=\"70\" y=\"57.7\" text-anchor=\"middle\" font-size=\"10\">git push</text><rect class=\"b\" x=\"190\" y=\"10\" width=\"200\" height=\"72\" rx=\"6\"/><text class=\"tb\" x=\"290\" y=\"36.2\" text-anchor=\"middle\" font-size=\"13\">GitHub</text><text class=\"t2\" x=\"290\" y=\"50.7\" text-anchor=\"middle\" font-size=\"10\">repo + Actions:</text><text class=\"t2\" x=\"290\" y=\"64.7\" text-anchor=\"middle\" font-size=\"10\">test, build, deploy</text><rect class=\"b warn\" x=\"470\" y=\"20\" width=\"200\" height=\"52\" rx=\"6\"/><text class=\"tb\" x=\"570\" y=\"43.2\" text-anchor=\"middle\" font-size=\"13\">ghcr.io</text><text class=\"t2\" x=\"570\" y=\"57.7\" text-anchor=\"middle\" font-size=\"10\">the image, tagged :sha</text><rect class=\"g hi\" x=\"190\" y=\"120\" width=\"480\" height=\"140\" rx=\"8\"/><text class=\"tg hi\" x=\"200\" y=\"136\" font-size=\"11\">cloud server  /srv/app</text><rect class=\"b ok\" x=\"210\" y=\"160\" width=\"170\" height=\"60\" rx=\"6\"/><text class=\"tb\" x=\"295\" y=\"187.2\" text-anchor=\"middle\" font-size=\"13\">Caddy</text><text class=\"t2\" x=\"295\" y=\"201.7\" text-anchor=\"middle\" font-size=\"10\">HTTPS, auto certs</text><rect class=\"b hi\" x=\"470\" y=\"160\" width=\"180\" height=\"60\" rx=\"6\"/><text class=\"tb ta\" x=\"560\" y=\"187.2\" text-anchor=\"middle\" font-size=\"13\">web container</text><text class=\"t2\" x=\"560\" y=\"201.7\" text-anchor=\"middle\" font-size=\"10\">the Python API</text><rect class=\"b\" x=\"10\" y=\"160\" width=\"120\" height=\"60\" rx=\"6\"/><text class=\"tb\" x=\"70\" y=\"187.2\" text-anchor=\"middle\" font-size=\"13\">users</text><text class=\"t2\" x=\"70\" y=\"201.7\" text-anchor=\"middle\" font-size=\"10\">https://</text><path class=\"ln\" d=\"M132,46 L188,46\" marker-end=\"url(#do-capstone--n)\"/><path class=\"ln\" d=\"M392,46 L468,46\" marker-end=\"url(#do-capstone--n)\"/><text class=\"tl\" x=\"430\" y=\"39\" text-anchor=\"middle\" font-size=\"11\">push image</text><path class=\"ln\" d=\"M290,84 L290,118\" marker-end=\"url(#do-capstone--n)\"/><text class=\"tl\" x=\"300\" y=\"104\" text-anchor=\"start\" font-size=\"11\">deploy over SSH</text><path class=\"ln\" d=\"M570,74 L570,158\" marker-end=\"url(#do-capstone--n)\"/><text class=\"tl\" x=\"580\" y=\"118\" text-anchor=\"start\" font-size=\"11\">pull</text><path class=\"ln\" d=\"M132,190 L208,190\" marker-end=\"url(#do-capstone--n)\"/><text class=\"tl\" x=\"170\" y=\"183\" text-anchor=\"middle\" font-size=\"11\">HTTPS</text><path class=\"ln\" d=\"M382,190 L468,190\" marker-end=\"url(#do-capstone--n)\"/><text class=\"tl\" x=\"425\" y=\"183\" text-anchor=\"middle\" font-size=\"11\">proxy</text></svg></div><figcaption>Every piece is something an earlier chapter taught. Build it once end to end and the whole Docs will click into place.</figcaption></figure>\n\n\n<h4>Step 1: the project and Git</h4>\n<pre><code>$ mkdir capstone &amp;&amp; cd capstone\n$ git init\n$ python3 -m venv .venv &amp;&amp; source .venv/bin/activate\n$ printf '.venv/\\n__pycache__/\\n.env\\n' &gt; .gitignore</code></pre>\n<p>Two dependency files: <code>requirements.txt</code> for the app and <code>requirements-dev.txt</code> for development:</p>\n<pre><code># requirements.txt\nflask&gt;=3.0,&lt;4\ngunicorn&gt;=22,&lt;24\n\n# requirements-dev.txt\n-r requirements.txt\npytest&gt;=8,&lt;9</code></pre>\n<pre><code>$ pip install -r requirements-dev.txt</code></pre>\n<p>Revisit: Git chapters 1 and 2, Python chapter 7.</p>\n\n<h4>Step 2: the app and a test</h4>\n<pre><code># app.py\nimport os\nimport socket\nfrom flask import Flask, jsonify\n\napp = Flask(__name__)\n\n@app.get(\"/\")\ndef index():\n    return jsonify(message=\"Hello from my capstone\",\n                   host=socket.gethostname(),\n                   version=os.environ.get(\"APP_VERSION\", \"dev\"))\n\n@app.get(\"/health\")\ndef health():\n    return jsonify(status=\"ok\")</code></pre>\n<pre><code># test_app.py\nfrom app import app\n\ndef test_health():\n    client = app.test_client()\n    r = client.get(\"/health\")\n    assert r.status_code == 200\n    assert r.get_json() == {\"status\": \"ok\"}</code></pre>\n<pre><code>$ pytest -q\n1 passed\n$ flask --app app run          # try it on http://127.0.0.1:5000, then Ctrl+C\n$ git add . &amp;&amp; git commit -m \"App with a health check and a test\"</code></pre>\n<p>Revisit: Python chapters 3, 6 and 8.</p>\n\n<h4>Step 3: put it in a container</h4>\n<pre><code># Dockerfile\nFROM python:3.12-slim\nWORKDIR /app\nCOPY requirements.txt .\nRUN pip install --no-cache-dir -r requirements.txt\nCOPY app.py .\nRUN useradd --create-home appuser\nUSER appuser\nEXPOSE 8000\nCMD [\"gunicorn\", \"--bind\", \"0.0.0.0:8000\", \"--workers\", \"2\", \"app:app\"]</code></pre>\n<pre><code># .dockerignore\n.venv\n.git\n__pycache__\n.env</code></pre>\n<pre><code>$ docker build -t capstone:dev .\n$ docker run --rm -p 8000:8000 capstone:dev\n$ curl localhost:8000/health          # from a second terminal\n{\"status\":\"ok\"}</code></pre>\n<p>Revisit: Docker chapters 2 and 3.</p>\n\n<h4>Step 4: GitHub and the pipeline</h4>\n<p>Create an empty repository on GitHub, push to it, and add the workflow from the <b>CI/CD pipeline</b> chapter as <code>.github/workflows/pipeline.yml</code>. Leave out the deploy job for now; push, open the Actions tab, and check that <code>test</code> and <code>build</code> go green and that the image appears under your profile's Packages.</p>\n<pre><code>$ git remote add origin git@github.com:you/capstone.git\n$ git branch -M main\n$ git push -u origin main</code></pre>\n<p>Revisit: Git chapters 5 and 6, DevOps chapters 8 and 9.</p>\n\n<h4>Step 5: a server</h4>\n<p>Start a small Ubuntu server (an EC2 instance on the free tier works; Cloud chapter 3 walks through it) and allow inbound ports 22, 80 and 443 in its security group. Then secure it and install Docker:</p>\n<pre><code>$ ssh ubuntu@&lt;server-ip&gt;\n$ sudo apt update &amp;&amp; sudo apt upgrade -y\n$ curl -fsSL https://get.docker.com | sudo sh          # Docker's official install script\n$ sudo adduser --disabled-password --gecos \"\" deploy   # the user CI will log in as\n$ sudo usermod -aG docker deploy\n$ sudo mkdir -p /srv/app &amp;&amp; sudo chown deploy: /srv/app\n$ sudo ufw allow OpenSSH &amp;&amp; sudo ufw allow 80 &amp;&amp; sudo ufw allow 443 &amp;&amp; sudo ufw enable</code></pre>\n<p>Give the <code>deploy</code> user the public half of your CI deploy key (a key pair made just for CI, see the pipeline chapter), and turn off password logins as shown in Linux chapter 6:</p>\n<pre><code>$ sudo mkdir -p /home/deploy/.ssh\n$ sudo nano /home/deploy/.ssh/authorized_keys          # paste the public key, save\n$ sudo chown -R deploy: /home/deploy/.ssh\n$ sudo chmod 700 /home/deploy/.ssh &amp;&amp; sudo chmod 600 /home/deploy/.ssh/authorized_keys</code></pre>\n<p> One trap: ports that Docker publishes skip ufw's rules, so only publish what you really want public (here, just 80 and 443).</p>\n<p>Revisit: Linux chapters 2, 4 and 6, Cloud chapters 3 and 4.</p>\n\n<h4>Step 6: HTTPS and the first deploy</h4>\n<p>Point a domain (or a free subdomain) at the server with an <b>A record</b>, then run the app behind <b>Caddy</b>, a web server that gets and renews Let's Encrypt certificates by itself. Do this step as the <code>deploy</code> user (<code>sudo -iu deploy</code>), since that's the account the pipeline will use, and work in <code>/srv/app</code>:</p>\n<pre><code># compose.yaml\nservices:\n  web:\n    image: ghcr.io/you/capstone:${TAG:-latest}\n    restart: unless-stopped\n    environment:\n      APP_VERSION: ${TAG:-dev}\n  caddy:\n    image: caddy:2\n    restart: unless-stopped\n    ports:\n      - \"80:80\"\n      - \"443:443\"\n    volumes:\n      - ./Caddyfile:/etc/caddy/Caddyfile:ro\n      - caddy_data:/data\nvolumes:\n  caddy_data:</code></pre>\n<pre><code># Caddyfile\napp.example.com {\n    reverse_proxy web:8000\n}</code></pre>\n<pre><code>$ docker login ghcr.io -u you          # a token with read:packages, if the package is private\n$ docker compose up -d\n$ curl https://app.example.com/health\n{\"status\":\"ok\"}</code></pre>\n<p>Caddy reaches the app by its service name, <code>web</code>, because Compose puts both on one network. Only Caddy publishes ports. Revisit: Networking chapters 2 and 7, Docker chapter 4.</p>\n\n<h4>Step 7: automatic deploys</h4>\n<p>Add the deploy job back into the workflow, create the <code>production</code> environment and the <code>SSH_KEY</code>, <code>DEPLOY_HOST</code> and <code>DEPLOY_USER</code> secrets, and protect <code>main</code>. Now make a change on a branch, open a pull request, merge it, approve the deploy, and watch <code>/</code> report the new commit SHA as its version.</p>\n\n<h4>Step 8: know when it breaks</h4>\n<ul>\n<li><b>Logs</b>: <code>docker compose logs -f web</code> on the server.</li>\n<li><b>Uptime</b>: point a free uptime checker at <code>/health</code>, or add a cron job that curls it and alerts you when it fails (Linux chapter 9).</li>\n<li><b>Disk</b>: old images pile up with every deploy, so schedule <code>docker image prune -af --filter \"until=168h\"</code> weekly.</li>\n<li><b>Backups</b>: this app keeps no data, but the moment yours does, snapshot the volume or use a managed database (Cloud chapter 5).</li>\n</ul>\n<p>Revisit: DevOps chapter 7.</p>\n\n<h4>Going further</h4>\n<ul>\n<li>Create the server with <b>Terraform</b> instead of clicking (DevOps chapter 5), and install Docker on it with an <b>Ansible</b> playbook (DevOps chapter 6).</li>\n<li>Run the same image on your <b>kind</b> cluster with a Deployment and a Service (Kubernetes chapter 6), then package it as a <b>Helm</b> chart (Kubernetes chapter 7).</li>\n<li>Add a database with Compose, and a second test that uses it.</li>\n<li>Write a README that explains the architecture with a small diagram. A finished project with a clear README and a green pipeline says more than any certificate.</li>\n</ul>\n\n<h4>When you get stuck</h4>\n<ul>\n<li>Work from the inside out: does <code>curl localhost:8000/health</code> work inside the container (<code>docker compose exec web ...</code>), then from the server, then from outside? The first step that fails tells you which layer to look at (Networking chapter 6).</li>\n<li><b>Caddy can't get a certificate</b>: DNS doesn't point at the server yet, or ports 80 and 443 are blocked in the security group. <code>docker compose logs caddy</code> says which.</li>\n<li><b>502 Bad Gateway</b>: Caddy is fine but can't reach <code>web</code>; check that the web container is running and listening on 8000.</li>\n</ul>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=7aRjGIhwyQM&amp;t=250s\" target=\"_blank\" rel=\"noopener noreferrer\">Traversy Media · Linux Server Setup & MERN Deployment <span class=\"learn-sources-part\">· Creating a server (4:10)</span></a><a href=\"https://www.youtube.com/watch?v=7aRjGIhwyQM&amp;t=1830s\" target=\"_blank\" rel=\"noopener noreferrer\">Traversy Media · Linux Server Setup & MERN Deployment <span class=\"learn-sources-part\">· Firewall setup (30:30)</span></a><a href=\"https://www.youtube.com/watch?v=7aRjGIhwyQM&amp;t=2136s\" target=\"_blank\" rel=\"noopener noreferrer\">Traversy Media · Linux Server Setup & MERN Deployment <span class=\"learn-sources-part\">· Domain name & SSL (35:36)</span></a><a href=\"https://www.youtube.com/watch?v=pg19Z8LL06w&amp;t=2949s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Docker Crash Course <span class=\"learn-sources-part\">· Dockerfile: dockerize an app (49:09)</span></a></div>","devops/security-in-the-pipeline-devsecops":"\n<p class=\"learn-lead\">DevSecOps means security checks run inside the same pipeline as your tests, on every change, instead of a security review weeks after release. Each check is small and automatic. Together they catch leaked passwords, vulnerable libraries, risky infrastructure and over-powered CI jobs before any of it reaches production.</p>\n\n<h4>Shift left: catch it where it's cheap</h4>\n<p>A leaked key caught on your laptop costs a minute. The same key found in production logs costs a rotation, an investigation and maybe a breach notice. \"Shift left\" means moving each check as early (as far left in the pipeline) as it can go:</p>\n<ul>\n<li><b>On your machine:</b> a pre-commit hook that refuses to commit secrets.</li>\n<li><b>On every push and pull request:</b> dependency, code and config scans in CI.</li>\n<li><b>On every image:</b> a vulnerability scan before it's pushed (Docker chapter 6).</li>\n<li><b>In production:</b> patching, least privilege and monitoring (DevOps chapter 7).</li>\n</ul>\n\n\n<figure class=\"learn-diagram dg\" data-dg=\"do-shiftleft\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 230\" role=\"img\" aria-label=\"Security checks at each stage: gitleaks before a commit, dependency, code and config scans on each pull request, an image scan in CI, and patching and monitoring in production\" style=\"--dgw:680px\"><defs><marker id=\"do-shiftleft--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker><marker id=\"do-shiftleft--ok\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk ok\" d=\"M0,0 L8,4 L0,8 z\"/></marker><marker id=\"do-shiftleft--warn\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk warn\" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"b\" x=\"10\" y=\"30\" width=\"150\" height=\"56\" rx=\"6\"/><text class=\"tb\" x=\"85\" y=\"55.2\" text-anchor=\"middle\" font-size=\"13\">commit</text><text class=\"t2\" x=\"85\" y=\"69.7\" text-anchor=\"middle\" font-size=\"10\">your laptop</text><rect class=\"b warn\" x=\"20\" y=\"110\" width=\"130\" height=\"38\" rx=\"6\"/><text class=\"tb tm\" x=\"85\" y=\"132.5\" text-anchor=\"middle\" font-size=\"11\">gitleaks</text><path class=\"ln warn\" d=\"M85,88 L85,108\" marker-end=\"url(#do-shiftleft--warn)\"/><rect class=\"b hi\" x=\"180\" y=\"30\" width=\"150\" height=\"56\" rx=\"6\"/><text class=\"tb ta\" x=\"255\" y=\"55.2\" text-anchor=\"middle\" font-size=\"13\">pull request</text><text class=\"t2\" x=\"255\" y=\"69.7\" text-anchor=\"middle\" font-size=\"10\">CI</text><rect class=\"b warn\" x=\"190\" y=\"110\" width=\"130\" height=\"38\" rx=\"6\"/><text class=\"tb tm\" x=\"255\" y=\"132.5\" text-anchor=\"middle\" font-size=\"11\">deps, SAST, IaC</text><path class=\"ln warn\" d=\"M255,88 L255,108\" marker-end=\"url(#do-shiftleft--warn)\"/><path class=\"ln\" d=\"M162,58 L178,58\" marker-end=\"url(#do-shiftleft--n)\"/><rect class=\"b hi\" x=\"350\" y=\"30\" width=\"150\" height=\"56\" rx=\"6\"/><text class=\"tb ta\" x=\"425\" y=\"55.2\" text-anchor=\"middle\" font-size=\"13\">image</text><text class=\"t2\" x=\"425\" y=\"69.7\" text-anchor=\"middle\" font-size=\"10\">CI</text><rect class=\"b warn\" x=\"360\" y=\"110\" width=\"130\" height=\"38\" rx=\"6\"/><text class=\"tb tm\" x=\"425\" y=\"132.5\" text-anchor=\"middle\" font-size=\"11\">trivy image</text><path class=\"ln warn\" d=\"M425,88 L425,108\" marker-end=\"url(#do-shiftleft--warn)\"/><path class=\"ln\" d=\"M332,58 L348,58\" marker-end=\"url(#do-shiftleft--n)\"/><rect class=\"b ok\" x=\"520\" y=\"30\" width=\"150\" height=\"56\" rx=\"6\"/><text class=\"tb\" x=\"595\" y=\"55.2\" text-anchor=\"middle\" font-size=\"13\">production</text><text class=\"t2\" x=\"595\" y=\"69.7\" text-anchor=\"middle\" font-size=\"10\">running</text><rect class=\"b warn\" x=\"530\" y=\"110\" width=\"130\" height=\"38\" rx=\"6\"/><text class=\"tb\" x=\"595\" y=\"132.5\" text-anchor=\"middle\" font-size=\"11\">patch, monitor</text><path class=\"ln warn\" d=\"M595,88 L595,108\" marker-end=\"url(#do-shiftleft--warn)\"/><path class=\"ln\" d=\"M502,58 L518,58\" marker-end=\"url(#do-shiftleft--n)\"/><path class=\"ln ok\" d=\"M640,190 L40,190\" marker-end=\"url(#do-shiftleft--ok)\"/><text class=\"ok tb\" x=\"340\" y=\"182\" text-anchor=\"middle\" font-size=\"12\">the earlier a problem is caught, the cheaper it is to fix</text><text class=\"t2\" x=\"340\" y=\"214\" text-anchor=\"middle\" font-size=\"11\">a leaked key: one minute on a laptop, a rotation and an incident in production</text></svg></div><figcaption>Each check is small and automatic, and sits as early as it can. Most problems never get past the pull request.</figcaption></figure>\n<h4>Secrets never go in Git</h4>\n<p>Anything committed stays in the history, even after you delete it in the next commit, and anyone who clones the repo gets it. Bots scan public GitHub for keys within minutes. So:</p>\n<ul>\n<li>Keep secrets in <code>.env</code> files that are in <code>.gitignore</code>, and commit a <code>.env.example</code> with the names but no values.</li>\n<li>In CI, use the platform's secret store (GitHub Actions secrets, GitLab CI variables), never a value in the workflow file.</li>\n<li>Run a scanner before each commit. <b>gitleaks</b> knows hundreds of token formats; with the <code>pre-commit</code> framework it runs automatically:\n<pre><code># .pre-commit-config.yaml\nrepos:\n  - repo: https://github.com/gitleaks/gitleaks\n    rev: v8.21.2          # pin a release\n    hooks:\n      - id: gitleaks\n\n$ pip install pre-commit\n$ pre-commit install            # from now on, every git commit is checked</code></pre></li>\n<li>Turn on GitHub's <b>secret scanning with push protection</b> (Settings, then Code security). It blocks pushes that contain known token formats.</li>\n</ul>\n<div class=\"learn-callout\">Leaked a secret anyway? <b>Rotate it first</b>: revoke the key and make a new one. Cleaning it out of the Git history comes second, because by the time you notice, someone may already have a copy.</div>\n\n<h4>Dependencies: most of your code isn't yours</h4>\n<p>A typical app pulls in hundreds of packages, and vulnerabilities are found in them every week. Check them on every build, and let a bot open pull requests for updates:</p>\n<pre><code>$ pip-audit                     # Python: checks installed packages against known vulnerabilities\n$ npm audit --audit-level=high  # Node: exits non-zero on high or critical issues\n\n# .github/dependabot.yml: weekly update PRs for packages, base images and actions\nversion: 2\nupdates:\n  - package-ecosystem: \"pip\"\n    directory: \"/\"\n    schedule: { interval: \"weekly\" }\n  - package-ecosystem: \"docker\"\n    directory: \"/\"\n    schedule: { interval: \"weekly\" }\n  - package-ecosystem: \"github-actions\"\n    directory: \"/\"\n    schedule: { interval: \"weekly\" }</code></pre>\n<p>Small, frequent updates are easy to review and test. A year of skipped updates turns into one scary upgrade nobody wants to do.</p>\n\n<h4>Your own code: static analysis</h4>\n<p><b>SAST</b> (static application security testing) reads source code for risky patterns: SQL built by string concatenation, user input passed to a shell, disabled TLS checks. <b>CodeQL</b> is free for public repositories on GitHub (Security tab, then Code scanning; the \"default setup\" needs no YAML at all). <b>Semgrep</b> is another popular choice. Expect some false alarms; review each finding, fix or dismiss it with a reason.</p>\n\n<h4>Infrastructure as code: scan the config too</h4>\n<p>A Terraform file can open SSH to the whole internet or make a bucket public without a single line of app code changing. Config scanners catch that before <code>apply</code>:</p>\n<pre><code>$ trivy config .                 # Terraform, Kubernetes YAML, Dockerfiles, Helm charts\nmain.tf:12\nHIGH: Security group rule allows ingress from public internet (0.0.0.0/0) to port 22</code></pre>\n<p><b>Checkov</b> does the same job. Run it in the pull request, next to <code>terraform plan</code>, so the reviewer sees both.</p>\n\n<h4>Least privilege for the pipeline itself</h4>\n<p>CI holds the keys to production, so it's a favourite target. Four habits shrink the damage if a job is ever compromised:</p>\n<ul>\n<li><b>Give the workflow token only what it needs.</b> Put <code>permissions: contents: read</code> at the top of every workflow and add more (like <code>packages: write</code>) only to the job that needs it.</li>\n<li><b>Pin third-party actions to a commit SHA</b>, not a tag: <code>uses: some/action@8f4b7f8...</code>. Tags can be moved. In March 2025 the tags of a widely used action, tj-actions/changed-files, were pointed at malicious code that printed CI secrets into build logs; workflows pinned to a SHA weren't affected. Dependabot can keep pinned SHAs up to date.</li>\n<li><b>Use OIDC instead of stored cloud keys.</b> With <code>permissions: id-token: write</code>, the job gets a short-lived token from GitHub, swaps it for temporary AWS credentials, and nothing long-lived is stored anywhere. The IAM role's trust policy decides which repository and branch may use it.</li>\n<li><b>Protect deploys with environments.</b> A GitHub environment called <code>production</code> with required reviewers makes a person approve before any job using its secrets can run.</li>\n</ul>\n\n\n<figure class=\"learn-diagram dg\" data-dg=\"do-oidc\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 210\" role=\"img\" aria-label=\"OIDC: the CI job asks GitHub for a signed token naming its repo and branch, swaps it with AWS STS for temporary credentials the role trusts, and deploys with them\" style=\"--dgw:680px\"><defs><marker id=\"do-oidc--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker><marker id=\"do-oidc--ok\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk ok\" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"b hi\" x=\"10\" y=\"70\" width=\"160\" height=\"64\" rx=\"6\"/><text class=\"tb ta\" x=\"90\" y=\"99.2\" text-anchor=\"middle\" font-size=\"13\">CI job</text><text class=\"t2\" x=\"90\" y=\"113.7\" text-anchor=\"middle\" font-size=\"10\">id-token: write</text><rect class=\"b\" x=\"250\" y=\"10\" width=\"180\" height=\"56\" rx=\"6\"/><text class=\"tb\" x=\"340\" y=\"35.2\" text-anchor=\"middle\" font-size=\"13\">GitHub OIDC</text><text class=\"t2\" x=\"340\" y=\"49.7\" text-anchor=\"middle\" font-size=\"10\">signed: repo + branch</text><rect class=\"b warn\" x=\"250\" y=\"140\" width=\"180\" height=\"56\" rx=\"6\"/><text class=\"tb\" x=\"340\" y=\"165.2\" text-anchor=\"middle\" font-size=\"13\">AWS STS</text><text class=\"t2\" x=\"340\" y=\"179.7\" text-anchor=\"middle\" font-size=\"10\">checks the role trust</text><rect class=\"b ok\" x=\"510\" y=\"70\" width=\"160\" height=\"64\" rx=\"6\"/><text class=\"tb\" x=\"590\" y=\"99.2\" text-anchor=\"middle\" font-size=\"13\">AWS</text><text class=\"t2\" x=\"590\" y=\"113.7\" text-anchor=\"middle\" font-size=\"10\">short-lived keys</text><path class=\"ln\" d=\"M172,86 L248,40\" marker-end=\"url(#do-oidc--n)\"/><text class=\"tl\" x=\"196\" y=\"52\" text-anchor=\"middle\" font-size=\"11\">1 ask</text><path class=\"ln\" d=\"M248,56 L172,98\" marker-end=\"url(#do-oidc--n)\"/><text class=\"tl\" x=\"212\" y=\"96\" text-anchor=\"middle\" font-size=\"11\">2 token</text><path class=\"ln\" d=\"M172,120 L248,166\" marker-end=\"url(#do-oidc--n)\"/><text class=\"tl\" x=\"198\" y=\"158\" text-anchor=\"middle\" font-size=\"11\">3 swap it</text><path class=\"ln ok\" d=\"M432,168 L508,116\" marker-end=\"url(#do-oidc--ok)\"/><text class=\"ok\" x=\"482\" y=\"152\" text-anchor=\"middle\" font-size=\"11\">4 deploy</text><text class=\"ok tb\" x=\"340\" y=\"104\" text-anchor=\"middle\" font-size=\"12\">no stored keys anywhere</text></svg></div><figcaption>Nothing long-lived to leak. The IAM role's trust policy decides which repository and branch may assume it, and the credentials expire on their own.</figcaption></figure>\n<h4>Putting it together</h4>\n<pre><code>name: checks\non: [push, pull_request]\npermissions:\n  contents: read\n\njobs:\n  security:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v4\n        with: { fetch-depth: 0 }            # full history, so gitleaks sees every commit\n      - name: Secrets\n        uses: gitleaks/gitleaks-action@v2\n        env: { GITHUB_TOKEN: \"${{ secrets.GITHUB_TOKEN }}\" }   # repos owned by an organisation also need a free GITLEAKS_LICENSE\n      - name: Dependencies\n        run: pip install pip-audit &amp;&amp; pip-audit -r requirements.txt\n      - name: Terraform and Kubernetes config\n        run: |\n          curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sh -s -- -b /usr/local/bin\n          trivy config --severity HIGH,CRITICAL --exit-code 1 .\n      - name: Image\n        run: |\n          docker build -t app:${{ github.sha }} .\n          trivy image --severity HIGH,CRITICAL --ignore-unfixed --exit-code 1 app:${{ github.sha }}</code></pre>\n<p>Make the security job a <b>required check</b> on the main branch (branch protection), and a pull request can't merge until it's green.</p>\n\n<h4>Common mistakes</h4>\n<ul>\n<li><b>Scanning but never failing the build.</b> A report nobody reads changes nothing. Fail on what you can act on (high severity, fix available) and track the rest.</li>\n<li><b>Failing on everything on day one.</b> The team learns to ignore red builds. Start strict on new findings only, then work through the old ones.</li>\n<li><b>Secrets in logs.</b> <code>echo $TOKEN</code> or <code>set -x</code> in a CI script prints them. GitHub masks secrets it knows about, but not values derived from them.</li>\n<li><b>One admin key for everything.</b> Separate credentials per environment and per job, each with the narrowest permissions that work.</li>\n<li><b>Forgetting the runtime.</b> A clean scan at build time doesn't stay clean. Rebuild and redeploy regularly so base images pick up fixes.</li>\n</ul>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=MIWH2CpVyXs&amp;t=444s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · The ONLY Continuous Integration (CI) Tutorial <span class=\"learn-sources-part\">· Shifting testing left (7:24)</span></a><a href=\"https://www.youtube.com/watch?v=MIWH2CpVyXs&amp;t=681s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · The ONLY Continuous Integration (CI) Tutorial <span class=\"learn-sources-part\">· A CI pipeline with code quality checks (11:21)</span></a><a href=\"https://www.youtube.com/watch?v=R8_veQiYBjI&amp;t=1475s\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · GitHub Actions Tutorial <span class=\"learn-sources-part\">· Build an image and push it to a private registry (24:35)</span></a></div>\n","devops/gitops-with-argo-cd":"\n<p class=\"learn-lead\">In the pipelines so far, CI pushes each new version into the cluster. GitOps flips that around: a Git repository describes exactly what should run, and an agent inside the cluster keeps the cluster matching it. Deploying becomes a commit, rolling back becomes a revert, and every change has a reviewer and a history.</p>\n\n<h4>Push versus pull deploys</h4>\n<p>In a <b>push</b> deploy, the CI job runs <code>kubectl apply</code> or <code>helm upgrade</code> against the cluster. That works, but CI needs admin credentials for every cluster, and nothing notices if someone later edits the cluster by hand.</p>\n<p>In a <b>pull</b> (GitOps) deploy, an agent such as <b>Argo CD</b> or <b>Flux</b> runs inside the cluster, watches a Git repository and applies whatever it says. CI never touches the cluster; it only commits to Git. If the cluster drifts from Git, the agent sees it and can put it back.</p>\n<p>Two principles carry the whole idea: <b>Git is the single source of truth</b> for what runs, and <b>the cluster is reconciled continuously</b>, not just at deploy time.</p>\n\n\n<figure class=\"learn-diagram dg\" data-dg=\"do-gitops\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 250\" role=\"img\" aria-label=\"Push deploy: CI with cluster admin runs kubectl apply. Pull deploy: CI only commits to a config repo, and Argo CD inside the cluster pulls and applies it\" style=\"--dgw:680px\"><defs><marker id=\"do-gitops--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker><marker id=\"do-gitops--ok\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk ok\" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><text class=\"tb\" x=\"165\" y=\"20\" text-anchor=\"middle\" font-size=\"13\">push deploy</text><rect class=\"b bad\" x=\"10\" y=\"40\" width=\"130\" height=\"52\" rx=\"6\"/><text class=\"tb\" x=\"75\" y=\"63.2\" text-anchor=\"middle\" font-size=\"13\">CI</text><text class=\"t2\" x=\"75\" y=\"77.7\" text-anchor=\"middle\" font-size=\"10\">has cluster admin</text><rect class=\"b\" x=\"220\" y=\"40\" width=\"110\" height=\"52\" rx=\"6\"/><text class=\"tb\" x=\"275\" y=\"70.2\" text-anchor=\"middle\" font-size=\"13\">cluster</text><path class=\"ln\" d=\"M142,66 L218,66\" marker-end=\"url(#do-gitops--n)\"/><text class=\"tc\" x=\"175\" y=\"112\" text-anchor=\"middle\" font-size=\"11\">kubectl apply</text><text class=\"bad\" x=\"165\" y=\"150\" text-anchor=\"middle\" font-size=\"11\">hand edits go unnoticed</text><text class=\"tb\" x=\"520\" y=\"20\" text-anchor=\"middle\" font-size=\"13\">pull deploy (GitOps)</text><rect class=\"b\" x=\"370\" y=\"40\" width=\"110\" height=\"52\" rx=\"6\"/><text class=\"tb\" x=\"425\" y=\"63.2\" text-anchor=\"middle\" font-size=\"13\">CI</text><text class=\"t2\" x=\"425\" y=\"77.7\" text-anchor=\"middle\" font-size=\"10\">commits a tag</text><rect class=\"b hi\" x=\"560\" y=\"40\" width=\"110\" height=\"52\" rx=\"6\"/><text class=\"tb ta\" x=\"615\" y=\"63.2\" text-anchor=\"middle\" font-size=\"13\">config repo</text><text class=\"t2\" x=\"615\" y=\"77.7\" text-anchor=\"middle\" font-size=\"10\">the truth</text><path class=\"ln\" d=\"M482,66 L558,66\" marker-end=\"url(#do-gitops--n)\"/><text class=\"tc\" x=\"520\" y=\"112\" text-anchor=\"middle\" font-size=\"11\">git push</text><rect class=\"g ok\" x=\"370\" y=\"128\" width=\"300\" height=\"112\" rx=\"8\"/><text class=\"tg ok\" x=\"380\" y=\"144\" font-size=\"11\">cluster</text><rect class=\"b ok\" x=\"386\" y=\"164\" width=\"110\" height=\"56\" rx=\"6\"/><text class=\"tb\" x=\"441\" y=\"189.2\" text-anchor=\"middle\" font-size=\"13\">Argo CD</text><text class=\"t2\" x=\"441\" y=\"203.7\" text-anchor=\"middle\" font-size=\"10\">watches Git</text><rect class=\"b\" x=\"560\" y=\"164\" width=\"100\" height=\"56\" rx=\"6\"/><text class=\"tb\" x=\"610\" y=\"196.2\" text-anchor=\"middle\" font-size=\"13\">your apps</text><path class=\"ln ok\" d=\"M441,162 L441,140 L600,140 L600,94\" marker-end=\"url(#do-gitops--ok)\"/><text class=\"ok\" x=\"612\" y=\"124\" text-anchor=\"start\" font-size=\"11\">pulls</text><path class=\"ln\" d=\"M498,192 L558,192\" marker-end=\"url(#do-gitops--n)\"/><text class=\"tl\" x=\"528\" y=\"184\" text-anchor=\"middle\" font-size=\"10\">applies</text></svg></div><figcaption>With GitOps, CI never holds cluster credentials, and the cluster keeps matching Git: a change made by hand is noticed and undone.</figcaption></figure>\n<h4>The pieces</h4>\n<ul>\n<li><b>A config repository</b> with the Kubernetes manifests, Helm values or Kustomize overlays for each app and environment. Teams usually keep it separate from the app's code, so a config change doesn't trigger an app build and the history reads like a deploy log.</li>\n<li><b>Argo CD</b>, installed in the cluster, with a web UI and a CLI.</li>\n<li><b>An Application</b>: an Argo CD object that says \"keep this path of this repo applied to this namespace\".</li>\n</ul>\n\n<h4>Install Argo CD on your practice cluster</h4>\n<p>Use the kind cluster from Kubernetes chapter 6:</p>\n<pre><code>$ kubectl create namespace argocd\n$ kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml\n$ kubectl -n argocd get pods                       # wait until every pod is Running\n\n# the first admin password, then the UI on https://localhost:8080 (accept the self-signed certificate)\n$ kubectl -n argocd get secret argocd-initial-admin-secret -o jsonpath=\"{.data.password}\" | base64 -d; echo\n$ kubectl port-forward svc/argocd-server -n argocd 8080:443</code></pre>\n<p>Log in as <code>admin</code>. The <code>argocd</code> CLI works too: <code>argocd login localhost:8080 --username admin --insecure</code>.</p>\n\n<h4>Your first Application</h4>\n<p>Argo CD's own example repository has a small app called guestbook. This manifest tells Argo CD to keep it running in a <code>guestbook</code> namespace:</p>\n<pre><code># guestbook-app.yaml\napiVersion: argoproj.io/v1alpha1\nkind: Application\nmetadata:\n  name: guestbook\n  namespace: argocd                 # Applications live in Argo CD's namespace\nspec:\n  project: default\n  source:\n    repoURL: https://github.com/argoproj/argocd-example-apps.git\n    targetRevision: HEAD            # a branch, a tag or a commit\n    path: guestbook                 # the folder with the manifests\n  destination:\n    server: https://kubernetes.default.svc   # this same cluster\n    namespace: guestbook\n  syncPolicy:\n    automated:\n      prune: true                   # delete things that were removed from Git\n      selfHeal: true                # undo changes made by hand in the cluster\n    syncOptions:\n      - CreateNamespace=true\n\n$ kubectl apply -f guestbook-app.yaml\n$ kubectl -n guestbook get pods                    # Argo CD created them, not you</code></pre>\n<p>In the UI the app shows two statuses: <b>Synced / OutOfSync</b> (does the cluster match Git?) and <b>Healthy / Progressing / Degraded</b> (are the resources actually working?).</p>\n\n<h4>Drift and self-healing</h4>\n<p>Try changing the cluster behind Argo CD's back:</p>\n<pre><code>$ kubectl -n guestbook scale deployment guestbook-ui --replicas=5\n$ kubectl -n guestbook get deployment guestbook-ui -w     # within moments it goes back to what Git says</code></pre>\n<p>With <code>selfHeal</code> on, a hand-made change lasts seconds. That's the point: the only way to change production is a reviewed commit. Without <code>selfHeal</code>, the app just turns OutOfSync and waits for you to sync it.</p>\n\n<h4>How a new version gets deployed</h4>\n<figure class=\"learn-diagram dg\" data-dg=\"do-gitops-flow\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 160\" role=\"img\" aria-label=\"A release under GitOps: merge, CI builds and pushes the image, the new tag is committed to the config repo, and Argo CD syncs it into the cluster\" style=\"--dgw:680px\"><defs><marker id=\"do-gitops-flow--n\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk \" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"b\" x=\"10\" y=\"30\" width=\"118\" height=\"56\" rx=\"6\"/><text class=\"tb\" x=\"69\" y=\"55.2\" text-anchor=\"middle\" font-size=\"13\">merge</text><text class=\"t2\" x=\"69\" y=\"69.7\" text-anchor=\"middle\" font-size=\"10\">app repo</text><rect class=\"b\" x=\"144\" y=\"30\" width=\"118\" height=\"56\" rx=\"6\"/><text class=\"tb\" x=\"203\" y=\"55.2\" text-anchor=\"middle\" font-size=\"13\">CI</text><text class=\"t2\" x=\"203\" y=\"69.7\" text-anchor=\"middle\" font-size=\"10\">test, build</text><path class=\"ln\" d=\"M130,58 L142,58\" marker-end=\"url(#do-gitops-flow--n)\"/><rect class=\"b warn\" x=\"278\" y=\"30\" width=\"118\" height=\"56\" rx=\"6\"/><text class=\"tb\" x=\"337\" y=\"55.2\" text-anchor=\"middle\" font-size=\"13\">registry</text><text class=\"t2\" x=\"337\" y=\"69.7\" text-anchor=\"middle\" font-size=\"10\">:3f9c2a1</text><path class=\"ln\" d=\"M264,58 L276,58\" marker-end=\"url(#do-gitops-flow--n)\"/><rect class=\"b hi\" x=\"412\" y=\"30\" width=\"118\" height=\"56\" rx=\"6\"/><text class=\"tb ta\" x=\"471\" y=\"55.2\" text-anchor=\"middle\" font-size=\"13\">config repo</text><text class=\"t2\" x=\"471\" y=\"69.7\" text-anchor=\"middle\" font-size=\"10\">new tag</text><path class=\"ln\" d=\"M398,58 L410,58\" marker-end=\"url(#do-gitops-flow--n)\"/><rect class=\"b ok\" x=\"546\" y=\"30\" width=\"118\" height=\"56\" rx=\"6\"/><text class=\"tb\" x=\"605\" y=\"55.2\" text-anchor=\"middle\" font-size=\"13\">Argo CD</text><text class=\"t2\" x=\"605\" y=\"69.7\" text-anchor=\"middle\" font-size=\"10\">syncs</text><path class=\"ln\" d=\"M532,58 L544,58\" marker-end=\"url(#do-gitops-flow--n)\"/><text class=\"ta tb\" x=\"340\" y=\"130\" text-anchor=\"middle\" font-size=\"12\">roll back: git revert on the config repo</text></svg></div><figcaption>Every deploy and every rollback is a commit, with a reviewer and a timestamp.</figcaption></figure>\n\n<ol>\n<li>A developer merges a change to the app repository.</li>\n<li>CI tests it, builds the image and pushes <code>shop-api:3f9c2a1</code> to the registry, exactly as before.</li>\n<li>CI (or a bot such as Argo CD Image Updater) commits the new tag into the config repository, often through a pull request for production.</li>\n<li>Argo CD notices the commit (it checks about every 3 minutes by default, or straight away with a webhook) and rolls the Deployment out.</li>\n</ol>\n<p><b>Rolling back</b> is <code>git revert</code> on the config repository: the old tag comes back, and Argo CD applies it. The history shows who deployed what and when, and who rolled it back.</p>\n\n<h4>More than one app or environment</h4>\n<ul>\n<li>A common layout is one folder per environment in the config repo (<code>envs/staging</code>, <code>envs/production</code>), each an overlay with its own replicas and image tag, and one Application per folder.</li>\n<li>The <b>app of apps</b> pattern is one Application whose folder contains other Application manifests, so a whole cluster is bootstrapped from one object.</li>\n<li><b>ApplicationSets</b> generate Applications from a template, for example one per cluster or one per folder.</li>\n</ul>\n<p><b>Flux</b> is the other big GitOps tool. Both Argo CD and Flux are graduated CNCF projects; Argo CD is known for its UI, Flux for being a set of small controllers you drive entirely from Git.</p>\n\n<h4>Common problems</h4>\n<ul>\n<li><b>Stuck OutOfSync on a field you never set</b>: something else in the cluster (an autoscaler, a mutating webhook) changes it. Tell Argo CD to ignore that field with <code>ignoreDifferences</code>, or let the HPA own <code>replicas</code> by leaving it out of the manifest.</li>\n<li><b>\"repository not accessible\"</b>: private repos need credentials. Add them with <code>argocd repo add</code> using a deploy key or token.</li>\n<li><b>Rollback button greyed out</b>: Argo CD won't roll back while automated sync is on, because Git would win again a moment later. Revert in Git instead.</li>\n<li><b>Secrets in the config repo</b>: never commit plain Kubernetes Secrets. Use Sealed Secrets, SOPS, or the External Secrets Operator to pull them from a secrets manager.</li>\n</ul>\n","devops/terraform-in-practice-variables-modules-and-environments":"\n<p class=\"learn-lead\">Chapter 5 built one bucket from one file. Real infrastructure has a dev and a production copy that should differ only in size and names, pieces that repeat, resources that already exist, and a team that changes it through pull requests. This chapter covers the Terraform features that make that manageable.</p>\n\n<h4>Variables, outputs and locals</h4>\n<p><b>Variables</b> are a configuration's inputs, <b>outputs</b> are what it reports back, and <b>locals</b> are named values you compute inside it:</p>\n<pre><code># variables.tf\nvariable \"env\" {\n  type        = string\n  description = \"dev, staging or prod\"\n  validation {\n    condition     = contains([\"dev\", \"staging\", \"prod\"], var.env)\n    error_message = \"env must be dev, staging or prod.\"\n  }\n}\nvariable \"instance_type\" {\n  type    = string\n  default = \"t3.micro\"\n}\nvariable \"db_password\" {\n  type      = string\n  sensitive = true                  # hidden in plan output\n}\n\n# main.tf\nlocals {\n  name = \"shop-${var.env}\"\n  tags = { project = \"shop\", env = var.env, managed_by = \"terraform\" }\n}\nresource \"aws_s3_bucket\" \"assets\" {\n  bucket = \"${local.name}-assets\"\n  tags   = local.tags\n}\n\n# outputs.tf\noutput \"assets_bucket\" {\n  value = aws_s3_bucket.assets.bucket\n}</code></pre>\n<p>Values come from, in rising priority: the <code>default</code>, a <code>terraform.tfvars</code> or <code>*.auto.tfvars</code> file (loaded automatically), <code>-var-file=prod.tfvars</code>, and <code>-var \"env=prod\"</code> on the command line. Environment variables named <code>TF_VAR_db_password</code> also work, which is how CI passes secrets without writing them to a file.</p>\n\n<h4>Many of the same thing: count and for_each</h4>\n<pre><code># count: N copies, numbered 0, 1, 2...\nresource \"aws_instance\" \"web\" {\n  count         = 3\n  ami           = data.aws_ami.ubuntu.id\n  instance_type = var.instance_type\n  tags          = { Name = \"web-${count.index}\" }\n}\n\n# for_each: one per key, named by the key\nresource \"aws_s3_bucket\" \"store\" {\n  for_each = toset([\"logs\", \"backups\", \"uploads\"])\n  bucket   = \"${local.name}-${each.key}\"\n}</code></pre>\n<p>Prefer <code>for_each</code> for anything with a name. With <code>count</code>, removing the middle item renumbers everything after it, and Terraform destroys and recreates resources that didn't need to change. With <code>for_each</code>, each resource is tracked by its key (<code>aws_s3_bucket.store[\"logs\"]</code>), so removing one touches only that one.</p>\n\n\n<figure class=\"learn-diagram dg\" data-dg=\"do-tf-count\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 220\" role=\"img\" aria-label=\"Removing the middle item: with count the later items are renumbered so uploads is replaced and destroyed; with for_each only backups is destroyed and the others are kept\" style=\"--dgw:680px\"><text class=\"tb\" x=\"160\" y=\"20\" text-anchor=\"middle\" font-size=\"12\">count: remove &quot;backups&quot;</text><rect class=\"b ok\" x=\"10\" y=\"36\" width=\"150\" height=\"46\" rx=\"6\"/><text class=\"tb tm\" x=\"85\" y=\"62.8\" text-anchor=\"middle\" font-size=\"12\">[0] logs</text><text class=\"ok\" x=\"170\" y=\"64\" text-anchor=\"start\" font-size=\"11\">kept</text><rect class=\"b bad\" x=\"10\" y=\"94\" width=\"150\" height=\"46\" rx=\"6\"/><text class=\"tb tm\" x=\"85\" y=\"120.8\" text-anchor=\"middle\" font-size=\"12\">[1] uploads</text><text class=\"bad\" x=\"170\" y=\"122\" text-anchor=\"start\" font-size=\"11\">was backups: replaced!</text><rect class=\"b bad\" x=\"10\" y=\"152\" width=\"150\" height=\"46\" rx=\"6\"/><text class=\"tb tm\" x=\"85\" y=\"178.8\" text-anchor=\"middle\" font-size=\"12\">[2] uploads</text><text class=\"bad\" x=\"170\" y=\"180\" text-anchor=\"start\" font-size=\"11\">destroyed</text><text class=\"tb\" x=\"510\" y=\"20\" text-anchor=\"middle\" font-size=\"12\">for_each: remove &quot;backups&quot;</text><rect class=\"b ok\" x=\"360\" y=\"36\" width=\"150\" height=\"46\" rx=\"6\"/><text class=\"tb tm\" x=\"435\" y=\"62.8\" text-anchor=\"middle\" font-size=\"12\">[&quot;logs&quot;]</text><text class=\"ok\" x=\"520\" y=\"64\" text-anchor=\"start\" font-size=\"11\">kept</text><rect class=\"b warn\" x=\"360\" y=\"94\" width=\"150\" height=\"46\" rx=\"6\"/><text class=\"tb tm\" x=\"435\" y=\"120.8\" text-anchor=\"middle\" font-size=\"12\">[&quot;backups&quot;]</text><text class=\"warn\" x=\"520\" y=\"122\" text-anchor=\"start\" font-size=\"11\">destroyed, as asked</text><rect class=\"b ok\" x=\"360\" y=\"152\" width=\"150\" height=\"46\" rx=\"6\"/><text class=\"tb tm\" x=\"435\" y=\"178.8\" text-anchor=\"middle\" font-size=\"12\">[&quot;uploads&quot;]</text><text class=\"ok\" x=\"520\" y=\"180\" text-anchor=\"start\" font-size=\"11\">kept</text></svg></div><figcaption>count tracks resources by position, for_each by name. Removing one name only ever touches that one resource.</figcaption></figure>\n<h4>Data sources: read what already exists</h4>\n<p>A <code>data</code> block looks something up instead of creating it: the newest Ubuntu image, the current account ID, a VPC another team manages.</p>\n<pre><code>data \"aws_ami\" \"ubuntu\" {\n  most_recent = true\n  owners      = [\"099720109477\"]                 # Canonical, the publisher of Ubuntu\n  filter {\n    name   = \"name\"\n    values = [\"ubuntu/images/hvm-ssd-gp3/ubuntu-noble-24.04-amd64-server-*\"]\n  }\n}\ndata \"aws_caller_identity\" \"current\" {}\n\noutput \"account_id\" { value = data.aws_caller_identity.current.account_id }</code></pre>\n\n<h4>Modules: write it once, use it everywhere</h4>\n<p>A <b>module</b> is just a folder of <code>.tf</code> files with variables and outputs. Every configuration is already a module (the root module); you can call others from it:</p>\n<pre><code>modules/\n  web_service/\n    variables.tf      # name, instance_type, instance_count, vpc_id...\n    main.tf           # the security group, instances, load balancer target group\n    outputs.tf        # the load balancer DNS name\nenvs/\n  dev/main.tf\n  prod/main.tf\n\n# envs/prod/main.tf\nmodule \"api\" {\n  source         = \"../../modules/web_service\"\n  name           = \"shop-api-prod\"\n  instance_type  = \"t3.medium\"\n  instance_count = 3\n}\noutput \"api_url\" { value = module.api.url }</code></pre>\n<p>Run <code>terraform init</code> again after adding or changing a module's <code>source</code>. Public modules from the Terraform Registry work the same way with <code>source = \"terraform-aws-modules/vpc/aws\"</code> and a <code>version</code> constraint; read one before you use it, since you're taking on all of its choices.</p>\n\n<h4>Environments: one folder each</h4>\n<figure class=\"learn-diagram dg\" data-dg=\"do-tf-envs\"><div class=\"dg-scroll\"><svg viewBox=\"0 0 680 250\" role=\"img\" aria-label=\"Shared modules for web_service, network and database, used by envs/dev and envs/prod, which pass different sizes and each keep their own state\" style=\"--dgw:680px\"><defs><marker id=\"do-tf-envs--hi\" markerWidth=\"9\" markerHeight=\"9\" refX=\"7\" refY=\"4\" orient=\"auto\"><path class=\"mk hi\" d=\"M0,0 L8,4 L0,8 z\"/></marker></defs><rect class=\"g hi\" x=\"10\" y=\"10\" width=\"250\" height=\"230\" rx=\"8\"/><text class=\"tg hi\" x=\"20\" y=\"26\" font-size=\"11\">modules/</text><rect class=\"b hi\" x=\"26\" y=\"46\" width=\"218\" height=\"52\" rx=\"6\"/><text class=\"tb ta tm\" x=\"135\" y=\"69.2\" text-anchor=\"middle\" font-size=\"13\">web_service</text><text class=\"t2\" x=\"135\" y=\"83.7\" text-anchor=\"middle\" font-size=\"10\">variables, main, outputs</text><rect class=\"b\" x=\"26\" y=\"110\" width=\"218\" height=\"52\" rx=\"6\"/><text class=\"tb tm\" x=\"135\" y=\"133.2\" text-anchor=\"middle\" font-size=\"13\">network</text><text class=\"t2\" x=\"135\" y=\"147.7\" text-anchor=\"middle\" font-size=\"10\">VPC, subnets</text><rect class=\"b\" x=\"26\" y=\"174\" width=\"218\" height=\"52\" rx=\"6\"/><text class=\"tb tm\" x=\"135\" y=\"197.2\" text-anchor=\"middle\" font-size=\"13\">database</text><text class=\"t2\" x=\"135\" y=\"211.7\" text-anchor=\"middle\" font-size=\"10\">RDS, backups</text><rect class=\"g\" x=\"330\" y=\"20\" width=\"340\" height=\"100\" rx=\"8\"/><text class=\"tg \" x=\"340\" y=\"36\" font-size=\"11\">envs/dev</text><rect class=\"b\" x=\"346\" y=\"54\" width=\"150\" height=\"52\" rx=\"6\"/><text class=\"tb tm\" x=\"421\" y=\"77.2\" text-anchor=\"middle\" font-size=\"13\">main.tf</text><text class=\"t2\" x=\"421\" y=\"91.7\" text-anchor=\"middle\" font-size=\"10\">1 x t3.micro</text><rect class=\"b warn\" x=\"510\" y=\"54\" width=\"144\" height=\"52\" rx=\"6\"/><text class=\"tb\" x=\"582\" y=\"77.2\" text-anchor=\"middle\" font-size=\"13\">own state</text><text class=\"t2\" x=\"582\" y=\"91.7\" text-anchor=\"middle\" font-size=\"10\">own backend</text><path class=\"ln hi\" d=\"M344,80 L262,72\" marker-end=\"url(#do-tf-envs--hi)\"/><text class=\"ta\" x=\"300\" y=\"50\" text-anchor=\"middle\" font-size=\"11\">uses</text><rect class=\"g ok\" x=\"330\" y=\"140\" width=\"340\" height=\"100\" rx=\"8\"/><text class=\"tg ok\" x=\"340\" y=\"156\" font-size=\"11\">envs/prod</text><rect class=\"b\" x=\"346\" y=\"174\" width=\"150\" height=\"52\" rx=\"6\"/><text class=\"tb tm\" x=\"421\" y=\"197.2\" text-anchor=\"middle\" font-size=\"13\">main.tf</text><text class=\"t2\" x=\"421\" y=\"211.7\" text-anchor=\"middle\" font-size=\"10\">3 x t3.medium</text><rect class=\"b warn\" x=\"510\" y=\"174\" width=\"144\" height=\"52\" rx=\"6\"/><text class=\"tb\" x=\"582\" y=\"197.2\" text-anchor=\"middle\" font-size=\"13\">own state</text><text class=\"t2\" x=\"582\" y=\"211.7\" text-anchor=\"middle\" font-size=\"10\">own backend</text><path class=\"ln hi\" d=\"M344,200 L262,140\" marker-end=\"url(#do-tf-envs--hi)\"/></svg></div><figcaption>One copy of the logic, one folder per environment. Dev and prod differ only in the values they pass in, and can never touch each other's state.</figcaption></figure>\n\n<p>The simplest layout that stays safe is a folder per environment, each with its own backend (its own state file) and a small <code>main.tf</code> that calls the shared modules. Dev and prod can't touch each other's state, plans are easy to read, and prod can pin an older module version while dev tries a new one.</p>\n<p>Terraform also has <b>workspaces</b> (<code>terraform workspace new dev</code>), several state files for one folder of code, with <code>terraform.workspace</code> holding the current name. They're handy for short-lived copies, but it's easy to run <code>apply</code> in the wrong one, so most teams use separate folders for real environments.</p>\n\n<h4>Importing and moving without destroying</h4>\n<p>Resources made by hand can be brought under Terraform with an <code>import</code> block (Terraform 1.5 and later). Terraform can even write the resource block for you:</p>\n<pre><code>import {\n  to = aws_s3_bucket.legacy\n  id = \"shop-old-uploads\"            # the bucket's real name\n}\n\n$ terraform plan -generate-config-out=generated.tf   # writes a starting resource block\n$ terraform apply                                    # now it's in state; tidy generated.tf by hand</code></pre>\n<p>Renaming a resource in code normally means \"destroy the old one, create a new one\". A <code>moved</code> block tells Terraform it's the same thing under a new address:</p>\n<pre><code>moved {\n  from = aws_s3_bucket.assets\n  to   = aws_s3_bucket.store[\"assets\"]\n}</code></pre>\n\n<h4>Guard rails with lifecycle</h4>\n<pre><code>resource \"aws_db_instance\" \"main\" {\n  # ...\n  lifecycle {\n    prevent_destroy       = true                # any plan that would delete it fails\n    ignore_changes        = [tags[\"last_backup\"]]   # changed by something else, don't fight it\n  }\n}</code></pre>\n\n<h4>Terraform in a team: plan in the PR, apply on merge</h4>\n<ol>\n<li>Every pull request runs <code>terraform fmt -check</code>, <code>terraform validate</code>, a linter such as <b>tflint</b>, a config scan (<code>trivy config</code>, see DevOps chapter 11) and <code>terraform plan</code>, and posts the plan as a comment.</li>\n<li>The reviewer reads the plan, not just the code: \"3 to add, 0 to change, 0 to destroy\" is the line that matters.</li>\n<li>After merge, CI runs <code>terraform apply</code> on that same plan, using OIDC credentials (no stored keys) and the shared, locked remote state from chapter 5.</li>\n</ol>\n<p>Nobody runs <code>apply</code> from a laptop against prod. That one rule prevents most Terraform disasters.</p>\n\n<h4>Common mistakes</h4>\n<ul>\n<li><b>Hard-coding names and sizes</b> so dev and prod need separate copies of the code. Make them variables and keep one module.</li>\n<li><b>Using count for named things</b>, then watching Terraform rebuild half of them after one deletion. Use for_each.</li>\n<li><b>Secrets in .tfvars files committed to Git.</b> Pass them as <code>TF_VAR_</code> environment variables from the CI secret store, or read them from a secrets manager with a data source. Remember the state file still contains them, so keep state encrypted and private.</li>\n<li><b>Renaming without a moved block</b>, and a \"simple refactor\" plan wants to destroy a database. Always read the plan.</li>\n<li><b>Huge root modules</b> where one plan takes ten minutes and touches everything. Split by lifetime and owner: network, data, apps.</li>\n</ul>\n<div class=\"learn-sources\"><span class=\"learn-sources-title\">Go deeper in your Resources</span><a href=\"https://www.youtube.com/watch?v=l5k1ai_GBDE\" target=\"_blank\" rel=\"noopener noreferrer\">TechWorld with Nana · Terraform explained in 15 mins</a><a href=\"https://www.youtube.com/watch?v=7xngnjfIlK4\" target=\"_blank\" rel=\"noopener noreferrer\">DevOps Directive · Complete Terraform Course, beginner to pro</a></div>\n"}