<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="4.4.1">Jekyll</generator><link href="https://e-choness.github.io/portfolio-site/feed.xml" rel="self" type="application/atom+xml" /><link href="https://e-choness.github.io/portfolio-site/" rel="alternate" type="text/html" /><updated>2026-11-26T17:42:37+00:00</updated><id>https://e-choness.github.io/portfolio-site/feed.xml</id><title type="html">Echo Yin</title><subtitle>Echo Yin, Senior A.I. Engineer in Calgary. Building governed, observable AI systems and the tools around them.</subtitle><author><name>Echo Yin</name></author><entry><title type="html">The Clean Envelope: Debugging Production Pipelines Without Touching PII</title><link href="https://e-choness.github.io/portfolio-site/blog/2026/07/14/PII-masking/" rel="alternate" type="text/html" title="The Clean Envelope: Debugging Production Pipelines Without Touching PII" /><published>2026-07-14T21:00:00+00:00</published><updated>2026-07-14T21:00:00+00:00</updated><id>https://e-choness.github.io/portfolio-site/blog/2026/07/14/PII-masking</id><content type="html" xml:base="https://e-choness.github.io/portfolio-site/blog/2026/07/14/PII-masking/"><![CDATA[<h2 id="debugging-production-data-pipelines-without-touching-pii">Debugging Production Data Pipelines Without Touching PII</h2>

<p>Every enterprise data team eventually hits this wall: a customer reports “your data loader crashed on our data,” and the two standard debugging moves—asking for logs, asking for a data sample—are both illegal. If the pipeline touches financial records, health data, or SSNs, the customer legally cannot hand you a sample, and you legally cannot persist it in your logs.</p>

<p>This post breaks down a design philosophy for solving this: capture <em>diagnostic signal</em> without ever capturing <em>PII</em>. We’ll use a real bug, <a href="https://github.com/apache/arrow-adbc/issues/2084">Apache Arrow ADBC #2084</a>, as a case study, then build up the cryptographic architecture needed to make deterministic tracing safe at scale.</p>

<h2 id="the-core-problem">The Core Problem</h2>

<p>Two debugging needs collide with two compliance constraints:</p>

<ul>
  <li>Engineers need <strong>reproducible signal</strong> (what shape of data broke the system?) and <strong>traceability</strong> (can I follow one user’s request across five microservices?).</li>
  <li>Compliance needs <strong>zero PII at rest</strong> and <strong>no way to reverse-engineer identity</strong> from what <em>is</em> stored.</li>
</ul>

<p>Naive masking tries to satisfy both by blanking out values it detects as sensitive. This usually destroys the signal engineers actually need.</p>

<h2 id="case-study-apache-arrow-adbc-2084">Case Study: Apache Arrow ADBC #2084</h2>

<p>In this <a href="https://github.com/apache/arrow-adbc/issues/2084">GitHub issue</a>, a data pipeline pushed a stream into Snowflake via the ADBC driver. It crashed because the Snowflake driver didn’t support binding fixed-point <code class="language-plaintext highlighter-rouge">DECIMAL</code> types in parameterized queries.</p>

<p>A naive masking system, terrified of leaking <code class="language-plaintext highlighter-rouge">transaction_amount</code>, would blank the query:</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">SELECT</span> <span class="o">*</span> <span class="k">FROM</span> <span class="n">revenue_table</span> <span class="k">WHERE</span> <span class="n">customer_id</span> <span class="o">=</span> <span class="o">***</span> <span class="k">AND</span> <span class="n">transaction_amount</span> <span class="o">=</span> <span class="o">***</span>
</code></pre></div></div>

<p>This tells the engineer nothing. The actual fix requires knowing the <em>shape</em> of the data, not its <em>value</em>. A metadata-first diagnostic system instead emits this:</p>

<div class="language-json highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span><span class="w">
  </span><span class="nl">"event"</span><span class="p">:</span><span class="w"> </span><span class="s2">"database_bind_parameter_failed"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"driver"</span><span class="p">:</span><span class="w"> </span><span class="s2">"adbc_driver_snowflake"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"error_class"</span><span class="p">:</span><span class="w"> </span><span class="s2">"NotSupportedError"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"param_index"</span><span class="p">:</span><span class="w"> </span><span class="mi">0</span><span class="p">,</span><span class="w">
  </span><span class="nl">"metadata"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
    </span><span class="nl">"data_type"</span><span class="p">:</span><span class="w"> </span><span class="s2">"DECIMAL"</span><span class="p">,</span><span class="w">
    </span><span class="nl">"precision"</span><span class="p">:</span><span class="w"> </span><span class="mi">38</span><span class="p">,</span><span class="w">
    </span><span class="nl">"scale"</span><span class="p">:</span><span class="w"> </span><span class="mi">9</span><span class="p">,</span><span class="w">
    </span><span class="nl">"total_rows"</span><span class="p">:</span><span class="w"> </span><span class="mi">4000000</span><span class="p">,</span><span class="w">
    </span><span class="nl">"null_percentage"</span><span class="p">:</span><span class="w"> </span><span class="mf">2.0</span><span class="w">
  </span><span class="p">}</span><span class="w">
</span><span class="p">}</span><span class="w">
</span></code></pre></div></div>

<p>Now the engineer immediately sees the real story: the driver chokes on a <code class="language-plaintext highlighter-rouge">DECIMAL(38,9)</code> during a 4-million-row bulk bind. Not a single financial value left memory. This is the pattern the rest of this post generalizes.</p>

<h2 id="key-concepts-defined-plainly">Key Concepts, Defined Plainly</h2>

<p>A few terms do a lot of work in this design. Worth being precise about them:</p>

<ul>
  <li><strong>Structured events vs. raw text logs</strong>: text logs are strings with variables jammed in; structured events are JSON objects with predictable keys and tightly typed values—much easier to redact selectively.</li>
  <li><strong>Data shape / metadata</strong>: describing structure instead of content. Instead of logging <code class="language-plaintext highlighter-rouge">$1,234,567.89</code>, you log “positive decimal, precision 9, scale 2.”</li>
  <li><strong>Deterministic tokenization</strong>: the same input always produces the same token (<code class="language-plaintext highlighter-rouge">"Alice Smith"</code> → <code class="language-plaintext highlighter-rouge">token_94af2</code>, everywhere). This preserves join-ability across microservices without exposing the real value.</li>
  <li><strong>Redact-at-capture vs. redact-at-view</strong>: capture-time redaction cleans data in memory before it touches disk; view-time redaction stores raw data and blocks it at the dashboard layer. Capture-time is safer; view-time is more forgiving of mistakes.</li>
  <li><strong>Fingerprinting via frequency analysis</strong>: the core weakness of naive deterministic tokens. If <code class="language-plaintext highlighter-rouge">token_94af2</code> appears 1M times and every other token appears twice, and you know your biggest customer is 40% of traffic, the token is de-anonymized by pure statistics.</li>
</ul>

<h2 id="the-basic-architecture">The Basic Architecture</h2>

<pre><code class="language-mermaid">flowchart TD
    A[Data Pipeline Exception] --&gt; B[In-Memory Diagnostic Handler]
    B --&gt; C[Field Classification&lt;br/&gt;Presidio]
    C --&gt; D[Tokenize Tracking IDs&lt;br/&gt;Keyed HMAC]
    C --&gt; E[Extract Data Shape&lt;br/&gt;type/precision/scale/nulls]
    D --&gt; F[Structured JSON Envelope]
    E --&gt; F
    F --&gt; G[Log Aggregator&lt;br/&gt;Zero PII surface area]
</code></pre>

<p><strong>Implementation steps:</strong></p>

<ol>
  <li><strong>Intercept in memory.</strong> Wrap data execution loops in a diagnostic handler. On exception, halt before anything hits a text logger.</li>
  <li><strong>Classify fields.</strong> Run column headers, parameters, and variable names through a classifier like Microsoft Presidio to flag PII.</li>
  <li><strong>Tokenize tracking IDs.</strong> For fields you need to trace (tenant ID, session ID), run them through a keyed HMAC for a consistent, non-reversible token.</li>
  <li><strong>Extract data shape.</strong> For the data block that crashed, strip literal values entirely. Keep type, precision, scale, string length, null percentage.</li>
  <li><strong>Emit the clean envelope.</strong> Assemble tokens and shape metadata into structured JSON. Ship it—your storage layer now has zero compliance surface area.</li>
</ol>

<h2 id="the-trade-offs-youre-actually-signing-up-for">The Trade-Offs You’re Actually Signing Up For</h2>

<p>This design isn’t free. Three tensions matter:</p>

<p><strong>1. Security vs. future visibility.</strong> Redact-at-capture means a breached log server leaks nothing—but it also means destroyed signal is gone forever. If your classifier misclassifies a technical error code as PII and blanks it, you cannot go back and un-redact it. You never saved it.</p>

<p><strong>2. Traceability vs. cryptanalysis.</strong> Deterministic tokens let you grep <code class="language-plaintext highlighter-rouge">token_a71x</code> across five services and follow a broken request end to end. But that same determinism leaks equality patterns—frequency analysis on a leaked log dump can reverse-engineer identity from volume alone.</p>

<p><strong>3. Execution overhead vs. simplicity.</strong> Text logging is just <code class="language-plaintext highlighter-rouge">printf</code> to a file descriptor. This design runs classification, computes null percentages, and executes cryptographic hashes—right when your system is already under strain from the error that triggered it.</p>

<p>The central paradox: fully random tokens (like password salts) kill determinism, breaking join-ability. Fully deterministic tokens are traceable but statistically attackable. You need to <em>constrain the scope</em> of determinism, not eliminate it.</p>

<h2 id="four-cryptographic-defenses-against-fingerprinting">Four Cryptographic Defenses Against Fingerprinting</h2>

<h3 id="1-context-scoped-tweaking-aes-siv">1. Context-Scoped Tweaking (AES-SIV)</h3>

<p>Standard encryption uses a random IV, so the same plaintext encrypts differently each time—killing determinism. <strong>AES-SIV</strong> (RFC 5297) instead derives its IV synthetically from the plaintext <em>plus</em> Additional Authenticated Data (AAD)—a “context tweak.”</p>

<p>Use a stable boundary like <code class="language-plaintext highlighter-rouge">Tenant_ID</code> as the AAD. The same PII value tokenizes identically <em>within</em> a tenant, but differently <em>across</em> tenants. An attacker can no longer run one unified frequency analysis over your global log store—each tenant’s distribution is cryptographically isolated.</p>

<h3 id="2-time-bounded-sliding-windows">2. Time-Bounded Sliding Windows</h3>

<p>Frequency analysis needs volume to work. Shrink an attacker’s window by deriving keys per time epoch via HKDF:</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Key_week = HKDF(Master_Secret, "2026-Week-29")
</code></pre></div></div>

<p>Tokens stay deterministic <em>within</em> the week—active incidents trace cleanly—but roll over on schedule. A multi-month leaked log dump becomes nearly useless because the statistical fingerprint shifts every seven days.</p>

<h3 id="3-token-pooling-salt-bucketing">3. Token Pooling (Salt-Bucketing)</h3>

<p>Low-entropy fields (<code class="language-plaintext highlighter-rouge">SUCCESS</code>/<code class="language-plaintext highlighter-rouge">FAILED</code>, gender, state codes) are trivially fingerprinted—if 95% of tokens are <code class="language-plaintext highlighter-rouge">token_x</code>, you know exactly what it means. Token pooling maps a value to a <em>deterministic bucket</em> of, say, five valid tokens for <code class="language-plaintext highlighter-rouge">FAILED</code>, chosen by a secondary stable attribute (e.g., last digit of a transaction ID). This flattens the frequency spike into a smooth curve while engineers can still query the whole pool.</p>

<h3 id="4-ephemeral-keys-and-crypto-shredding">4. Ephemeral Keys and Crypto-Shredding</h3>

<p>For high-severity incidents, spin up an incident-specific key from your KMS. Use it to tokenize logs for the incident’s lifecycle. Once the ticket closes or a retention period (e.g., 14 days) expires, <strong>delete the key from the KMS</strong>—permanently. The tokens remain in cold storage, but they’re now mathematically decoupled from any real-world mapping. No key, no reversal, ever.</p>

<h3 id="strategy-comparison">Strategy Comparison</h3>

<table>
  <thead>
    <tr>
      <th>Strategy</th>
      <th>Traceability Scope</th>
      <th>Frequency Protection</th>
      <th>Complexity</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Context-Scoped Tweaking</td>
      <td>Full, within tenant boundary</td>
      <td>High (blocks cross-tenant analysis)</td>
      <td>Medium</td>
    </tr>
    <tr>
      <td>Time-Bounded Windows</td>
      <td>Active during operational window</td>
      <td>High (breaks long-term baselines)</td>
      <td>Low</td>
    </tr>
    <tr>
      <td>Token Pooling</td>
      <td>Grouped (query the whole pool)</td>
      <td>Medium (flattens low-entropy spikes)</td>
      <td>High</td>
    </tr>
    <tr>
      <td>Crypto-Shredding</td>
      <td>Transient, gone after key deletion</td>
      <td>Absolute (post-deletion = pure noise)</td>
      <td>High</td>
    </tr>
  </tbody>
</table>

<p><strong>The sweet spot</strong>: combine AES-SIV (isolate per tenant) with time-bounded windows (rotate keys so history decays into noise).</p>

<h2 id="the-hard-part-rotating-keys-without-breaking-everything">The Hard Part: Rotating Keys Without Breaking Everything</h2>

<p>Time-bounded keys sound simple until you hit the <strong>midnight race condition</strong>. Server A’s clock runs 3 seconds fast; Server B’s runs 3 seconds slow. At a hard cutover, A is encrypting with tomorrow’s key while B is still on today’s. Add network delay and queued retries, and a naive rotation turns into a storm of decryption failures.</p>

<p>The fix rests on three principles: <strong>epoch-based derivation</strong>, <strong>self-describing tokens</strong>, and a <strong>sliding three-key cache</strong>.</p>

<pre><code class="language-mermaid">flowchart TB
    subgraph KMS[Distributed KMS Key Ring]
        R[Root Master Secret]
    end
    R --&gt;|HKDF derive| KP[Key_Prev · Epoch i-1]
    R --&gt;|HKDF derive| KC[Key_Curr · Epoch i]
    R --&gt;|HKDF derive| KN[Key_Next · Epoch i+1]
    subgraph Cache[Local Memory Cache — Sliding Window]
        KP
        KC
        KN
    end
    KP -.grace period reads.-&gt; Log[Log Pipeline]
    KC --&gt;|default writes| Log
    KN -.clock-drift cushion.-&gt; Log
</code></pre>

<h3 id="epoch-derivation">Epoch derivation</h3>

<p>Given epoch length <code class="language-plaintext highlighter-rouge">E</code> (e.g., 86400 seconds for daily rotation) and Unix timestamp <code class="language-plaintext highlighter-rouge">t</code>:</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>i   = floor(t / E)
K_i = HKDF(Root_Master_Secret, "log-tokenization-context" || i)
</code></pre></div></div>

<p>Services derive <code class="language-plaintext highlighter-rouge">K_i</code> locally from a periodically-fetched root secret—no KMS round-trip per log line.</p>

<h3 id="self-describing-tokens">Self-describing tokens</h3>

<p>Never assume a log’s timestamp tells you which key encrypted it—queued messages can sit for minutes. Instead, every token carries its epoch as a plaintext prefix:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>tok:19532:a8f9c2d103b4e...
│    │     └─ deterministic ciphertext
│    └─────── epoch index <span class="o">(</span>days since Unix epoch<span class="o">)</span>
└──────────── token <span class="nb">type </span>identifier
</code></pre></div></div>

<p>A consumer reading <code class="language-plaintext highlighter-rouge">tok:19532:...</code> doesn’t care what its own clock says—it fetches <code class="language-plaintext highlighter-rouge">K_19532</code> and moves on.</p>

<h3 id="the-three-key-sliding-cache">The three-key sliding cache</h3>

<p>Every service keeps exactly three keys warm in memory:</p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">K_(i-1)</code> — past key, for late-arriving or retried logs</li>
  <li><code class="language-plaintext highlighter-rouge">K_i</code> — current key, default for new writes</li>
  <li><code class="language-plaintext highlighter-rouge">K_(i+1)</code> — future key, pre-warmed for clock-drifted callers</li>
</ul>

<pre><code class="language-mermaid">sequenceDiagram
    participant App as Service
    participant Cache as Local Key Cache
    participant KMS as KMS/HKDF

    App-&gt;&gt;Cache: Need K_i for epoch i
    alt Key missing
        Cache-&gt;&gt;KMS: Derive K_i-1, K_i, K_i+1
        KMS--&gt;&gt;Cache: Return keys
    end
    Cache--&gt;&gt;App: K_i (or K_i+1 if inbound payload already drifted)
    App-&gt;&gt;App: Tokenize value, prefix with epoch
    App-&gt;&gt;Log: Emit tok:epoch:ciphertext
</code></pre>

<h3 id="runtime-flow-at-a-key-boundary">Runtime flow at a key boundary</h3>

<ol>
  <li>Compute current epoch <code class="language-plaintext highlighter-rouge">i = floor(t / E)</code> from local clock.</li>
  <li>Check cache for <code class="language-plaintext highlighter-rouge">K_(i-1)</code>, <code class="language-plaintext highlighter-rouge">K_i</code>, <code class="language-plaintext highlighter-rouge">K_(i+1)</code>; background-fetch any missing ones (never block the main thread).</li>
  <li>If within a drift cushion (e.g., &lt;10 seconds to boundary) and an inbound payload already uses <code class="language-plaintext highlighter-rouge">K_(i+1)</code>, switch to <code class="language-plaintext highlighter-rouge">K_(i+1)</code> to match the caller.</li>
  <li>Tokenize with the selected epoch’s key; prefix as <code class="language-plaintext highlighter-rouge">tok:epoch:value</code>.</li>
  <li>Emit the log. Even with a 10-minute queue delay, the consumer reads the epoch prefix and fetches the matching key—no ambiguity.</li>
</ol>

<h2 id="searching-across-epoch-boundaries">Searching Across Epoch Boundaries</h2>

<p>Key rotation creates a read-side puzzle: how do you search for one customer across a 3-day window when their token changes daily? The search client derives the target keys for the selected date range and expands into a multi-token <code class="language-plaintext highlighter-rouge">OR</code> query:</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">-- Searching for "Alice Smith" across epochs 19531–19533</span>
<span class="k">SELECT</span> <span class="o">*</span> <span class="k">FROM</span> <span class="n">application_logs</span>
<span class="k">WHERE</span> <span class="n">token</span> <span class="k">IN</span> <span class="p">(</span>
  <span class="s1">'tok:19531:8fa32...'</span><span class="p">,</span>
  <span class="s1">'tok:19532:2bc91...'</span><span class="p">,</span>
  <span class="s1">'tok:19533:7df40...'</span>
<span class="p">);</span>
</code></pre></div></div>

<p>The dashboard hides this complexity—user types a name, picks a date range, and the client computes the matching tokens behind the scenes. Since these are exact-match string lookups, database indices handle it at full speed.</p>

<h2 id="putting-it-together">Putting It Together</h2>

<p>The full stack, end to end:</p>

<pre><code class="language-mermaid">flowchart LR
    subgraph capture["At the exception"]
        direction TB
        A[Pipeline Exception] --&gt; B[Presidio Field Classification]
        B --&gt; C{PII field?}
        C --&gt;|Tracking ID| D[AES-SIV tokenize · tenant AAD tweak · epoch-derived key]
        C --&gt;|Data value| E[Strip value, extract shape metadata]
        D --&gt; F[tok:epoch:ciphertext]
        E --&gt; G[type/precision/scale/nulls]
        F --&gt; H[Structured JSON Envelope]
        G --&gt; H
    end
    subgraph decay["Afterwards"]
        direction TB
        I[Log Aggregator] --&gt; J[14-day retention]
        J --&gt; K[Crypto-shred incident key]
        K --&gt; L[Logs decay to noise]
    end
    capture --&gt; decay
</code></pre>

<p>None of these pieces work well alone—metadata-only logging loses traceability, deterministic tokens alone are fingerprintable, and time rotation alone breaks without epoch tagging. Stacked together, you get a system where engineers can debug real production incidents in real time, and six months later the same logs are cryptographically inert.</p>]]></content><author><name>Echo Yin</name></author><category term="ai" /><category term="data-engineering" /><category term="observability" /><category term="architecture" /><summary type="html"><![CDATA[When a production data pipeline crashes on regulated customer data, engineers can't ask for logs and customers can't share samples. This is a design for capturing debuggable signal — deterministic tokenization, structural metadata over raw values, and a key-rotation architecture that lets historical logs decay into cryptographic noise — plus the trade-offs it deliberately accepts.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://e-choness.github.io/portfolio-site/assets/images/blogs/pii-masking.webp" /><media:content medium="image" url="https://e-choness.github.io/portfolio-site/assets/images/blogs/pii-masking.webp" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">The Honest Parts: Residency, Tenancy, and Saying No</title><link href="https://e-choness.github.io/portfolio-site/blog/2026/05/27/the-honest-parts-residency-tenancy-scope/" rel="alternate" type="text/html" title="The Honest Parts: Residency, Tenancy, and Saying No" /><published>2026-05-27T09:00:00+00:00</published><updated>2026-05-27T09:00:00+00:00</updated><id>https://e-choness.github.io/portfolio-site/blog/2026/05/27/the-honest-parts-residency-tenancy-scope</id><content type="html" xml:base="https://e-choness.github.io/portfolio-site/blog/2026/05/27/the-honest-parts-residency-tenancy-scope/"><![CDATA[<p>Most of building Aegis was deciding what to build. But the decisions I’m most confident about, looking back, were decisions to <em>not</em> build something or to build it while being loud about its limits. In a governance tool, overclaiming is the cardinal sin: a guarantee you can’t actually keep is worse than an absent feature, because someone will build on top of it and find out the hard way that the floor wasn’t there. This post is about three places where the honest answer shaped the design more than the ambitious one would have.</p>

<h2 id="you-cannot-detect-where-inference-happens">You cannot detect where inference happens</h2>

<p>Aegis can enforce data residency as a policy like “data classified RESTRICTED must not reach a provider outside this jurisdiction.” The naive implementation is to detect where each provider runs inference and block the disallowed ones. That implementation is impossible, and pretending otherwise would be the single most dangerous thing the framework could do.</p>

<p>Geolocating a provider’s API endpoint tells you where the nearest edge node or load balancer sits, not where the GPUs that run the model actually are. Providers route internally however they like, across regions you never see. There is no request you can make from application code that returns a trustworthy “this specific inference executed in region X.” Any product claiming to <em>detect</em> processing location is reporting a number it effectively invented, and a security reviewer will see through it the moment they think about the network path.</p>

<p>So Aegis doesn’t detect. It enforces what’s <em>declared</em>, verifies what’s <em>verifiable</em>, and labels which is which. Four layers, fail-closed by default:</p>

<pre><code class="language-mermaid">flowchart LR
    subgraph eligible["Which providers are eligible?"]
        direction TB
        REQ[Request + classification label] --&gt; POL@{ shape: hex, label: "Policy on?" }
        POL -- no --&gt; ANY[All providers eligible]
        POL -- yes --&gt; FILTER[Filter by declared region]
        FILTER --&gt; UNK@{ shape: hex, label: "Unknown region?" }
        UNK -- yes --&gt; DROP[Drop it: fail closed]
        UNK -- no --&gt; OK[Eligible compliant set]
        DROP --&gt; OK
    end
    subgraph decide["Route or block"]
        direction TB
        EMPTY@{ shape: hex, label: "Set empty?" }
        EMPTY -- yes --&gt; BLOCK[Block + audit]
        EMPTY -- no --&gt; ROUTE[Route to compliant provider]
    end
    eligible --&gt; decide
</code></pre>

<ol>
  <li><strong>Declared metadata.</strong> Every provider profile carries <code class="language-plaintext highlighter-rouge">residency: {region, jurisdiction, source_url}</code>, sourced from the provider’s own documentation. Unset means <code class="language-plaintext highlighter-rouge">unknown</code>.</li>
  <li><strong>Endpoint validation.</strong> Some providers encode region verifiably in the endpoint itself — Azure hostnames, Bedrock regions, Vertex locations, OpenAI’s regional endpoints. <code class="language-plaintext highlighter-rouge">aegis policy lint</code> parses these and flags any mismatch between what you <em>declared</em> and what the URL actually <em>says</em>. This is the only genuinely verifiable signal, so it’s used everywhere it exists.</li>
  <li><strong>Fail-closed routing.</strong> With a residency policy active, the router filters the candidate set before selection, and <code class="language-plaintext highlighter-rouge">unknown</code> is treated as non-compliant. A blocked route is an audited event, never a silent fallback to whatever provider happens to be healthy.</li>
  <li><strong>Advisory runtime checks.</strong> Optional endpoint geolocation, reported as telemetry and labeled explicitly: <em>advisory only — not proof of processing location.</em> It’s a smoke detector, not a guarantee, and it says so.</li>
</ol>

<p>And then the part most tools won’t put in writing: the real enforcement boundary is your network, not the application. A hard “data never leaves this jurisdiction” guarantee ultimately lives at the DNS and egress-allowlist layer, outside anything an application framework can promise. The Aegis docs say this plainly and show you how to pair the residency pack with network egress controls.</p>

<p>This honesty is not a weakness in the pitch; it <em>is</em> the pitch. “We enforce what’s declared, verify what’s verifiable, fail closed on the unknown, and here’s exactly where our boundary ends” is a paragraph a compliance reviewer can actually trust and defend. “We guarantee data residency” is a sentence they’ll correctly stop trusting the instant they think about how inference routing works. <strong>A framework that’s honest about its limits is more useful for compliance than one that papers over them</strong>, because compliance, in the end, is the business of being able to defend your claims under scrutiny.</p>

<h2 id="the-multi-tenancy-i-didnt-build">The multi-tenancy I didn’t build</h2>

<p>Aegis is principal-aware. Virtual API keys resolve to a <code class="language-plaintext highlighter-rouge">Principal</code> carrying an id, a team, and a set of labels, and every run is attributed to one. Budgets meter against the principal, audit attributes to it, approval authority is checked against it. That’s identity level L2 on a ladder I found worth naming explicitly during design, because naming it kept the scope argument honest:</p>

<ul>
  <li><strong>L0 — anonymous.</strong> Single user, local dev, no auth. <code class="language-plaintext highlighter-rouge">aegis dev</code> on localhost.</li>
  <li><strong>L1 — authenticated.</strong> Keys resolve to a principal attached to every run.</li>
  <li><strong>L2 — policy-per-principal.</strong> Existing policy packs read the principal: budgets per team, allowed routes per key, residency constraints per label. <strong>This is what ships today.</strong></li>
  <li><strong>L3 — full multi-tenancy.</strong> Isolated organizations, tenant admins, per-tenant config and data. <strong>Explicitly out of scope.</strong></li>
</ul>

<p>The temptation was to build L3. From L2 it looks like a small step: just add a <code class="language-plaintext highlighter-rouge">tenant_id</code> column, right? It is not a small step. It is a phase change from <em>framework</em> to <em>platform</em>, and I want to lay out why, because the analysis is what justified the “no.”</p>

<p>At L3, identity inverts: tenants self-manage their users and bring their own identity providers, so a single authenticator becomes a per-tenant authenticator multiplexer. Configuration stops being a file and becomes versioned per-tenant data behind an admin API, with platform-level policy floors that must merge with and override tenant policy. Every table, cache, checkpoint, and RAG collection grows a partition key, and that key needs <em>provable</em> isolation, because the number-one threat in a multi-tenant system is cross-tenant leakage, which means every shared cache and every reused compiled graph needs an isolation test. Fairness and quotas appear, so one tenant’s batch job can’t starve another’s interactive traffic. Cost tracking graduates from useful telemetry to billing-grade metering with reconciliation. The test matrix roughly doubles, because every feature now needs an isolation variant.</p>

<p>Honest sizing: L3 is comparable in total effort to the entire rest of the framework. Bolting it on as “one more feature” is how you ship something that is neither a good framework nor a real platform — the worst of both, and late.</p>

<p>So I deferred it. But (and this is the distinction that matters) I designed the <em>seams</em> rather than designing it out. <code class="language-plaintext highlighter-rouge">Principal.labels</code> is exactly where a tenant id would live and become the partition key. RAG already partitions by namespace. Policy is already evaluated per principal. Routes already compile independently of each other. If L3 ever arrives, it arrives as addition along seams that already exist, not as a rewrite. <strong>Deferring a feature and designing it out are different acts: the first leaves seams, the second burns bridges.</strong> Knowing which one you’re doing is the difference between a roadmap and a regret.</p>

<h2 id="the-non-goals-list-is-load-bearing">The non-goals list is load-bearing</h2>

<p>Aegis’s design spec has a section as long as its feature list: what it deliberately is <em>not</em>.</p>

<p>Not a SaaS — self-hosted by design, so your prompts and keys stay on your infrastructure. Not multi-tenant, see above. Not an inference server — no bundled local models, just a clean provider slot left open for them (Ollama and friends connect today through the OpenAI-compatible provider type). Not an observability stack: OpenTelemetry at the core, Prometheus and the rest as optional exporter plugins. Not an agent-framework competitor. It’s built on LangGraph and governs agents; it doesn’t try to replace the thing it stands on. Not a guardrail research project: it composes the best existing scanners behind one contract; it doesn’t invent novel detectors.</p>

<p>For an open-source project, the non-goals are not a disclaimer you write at the end. They’re the scope contract, and every line traces back to a decision that kept the kernel small. “No bundled inference” is <em>why</em> the provider contract has a clean local-model slot that nobody is forced to fill. “Not an observability stack” is <em>why</em> telemetry is a plugin family instead of a hard dependency that drags Prometheus into every install. Each “not” is a dependency that never entered the tree and a maintenance burden nobody signed up for. The feature list tells you what the project does; the non-goals tell you what it will still be able to do well in two years, because they’re the reason it didn’t accrete its way into an unmaintainable everything-platform.</p>

<h2 id="what-this-taught-me">What this taught me</h2>

<p>The reflex, when you’re building a tool that makes guarantees, is to maximize what you promise. The opposite reflex is the correct one. The credibility of everything Aegis <em>does</em> enforce (composable guardrails, fail-closed routing, audited verdicts, principal-scoped budgets, governed tool traffic) rests on being unambiguous about the things it can’t enforce and won’t pretend to.</p>

<p>Saying no precisely is a feature. It’s just one that never shows up in a changelog, which is exactly why it’s easy to undervalue and worth writing down. If you’re building in this space, write your non-goals before your features. The non-goals are the ones you’ll be grateful for later.</p>]]></content><author><name>Echo Yin</name></author><category term="ai" /><category term="ai" /><category term="llm" /><category term="compliance" /><category term="data-residency" /><category term="architecture" /><category term="scope" /><summary type="html"><![CDATA[You cannot reliably detect where an LLM runs inference. Any product claiming otherwise is overclaiming. This is about the Aegis design decisions that required admitting limits — the residency model built on declared metadata and fail-closed routing, the multi-tenancy deliberately deferred, and why the non-goals list is as load-bearing as the feature list.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://e-choness.github.io/portfolio-site/assets/images/blogs/residency-tenancy.webp" /><media:content medium="image" url="https://e-choness.github.io/portfolio-site/assets/images/blogs/residency-tenancy.webp" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Guardrails That Tell You the Truth About Streaming</title><link href="https://e-choness.github.io/portfolio-site/blog/2026/05/20/guardrails-that-tell-you-the-truth/" rel="alternate" type="text/html" title="Guardrails That Tell You the Truth About Streaming" /><published>2026-05-20T09:00:00+00:00</published><updated>2026-05-20T09:00:00+00:00</updated><id>https://e-choness.github.io/portfolio-site/blog/2026/05/20/guardrails-that-tell-you-the-truth</id><content type="html" xml:base="https://e-choness.github.io/portfolio-site/blog/2026/05/20/guardrails-that-tell-you-the-truth/"><![CDATA[<p>A guardrail that silently does less than you think is worse than no guardrail, because you’ve stopped watching the thing you believe is being watched for you. The hardest design problem in rebuilding Aegis wasn’t writing scanners — good ones already exist, and reinventing them would have been hubris. It was designing a contract that stays honest about what it can actually guarantee, especially in the one place where honesty is expensive: streaming.</p>

<p>This post walks through the guardrail model from the verdict type up to tool governance, because the interesting decisions compound.</p>

<h2 id="four-verdicts-not-a-boolean">Four verdicts, not a boolean</h2>

<p>The obvious guardrail interface returns a boolean: allowed, or not. It is also wrong, because real policies need more than two outcomes. A guard in Aegis returns one of four verdicts:</p>

<ul>
  <li><strong>allow</strong> — continue unchanged.</li>
  <li><strong>sanitize</strong> — continue, but with mutated state: mask a value, redact a span, strip a header. Sanitize deltas from multiple guards compose in order.</li>
  <li><strong>block</strong> — terminal. The stage short-circuits, the client gets a refusal, the audit log gets the reason.</li>
  <li><strong>require_approval</strong> — the run pauses and waits for a human.</li>
</ul>

<pre><code class="language-mermaid">flowchart TD
    G[Guard node] --&gt; A[allow&lt;br/&gt;continue as-is]
    G --&gt; S[sanitize&lt;br/&gt;mutate, continue]
    G --&gt; B[block&lt;br/&gt;refuse + audit]
    G --&gt; R[require_approval&lt;br/&gt;interrupt, pause]
    A --&gt; N[Next node]
    S --&gt; N
    R --&gt; H[Human decision]
    H -- approved --&gt; N
    H -- denied --&gt; B
</code></pre>

<p>That fourth verdict is the one most systems lack, and it quietly changes what a guardrail <em>is</em>. A guard is no longer a gate that’s open or shut; it’s a participant that can escalate. “This looks like a bulk export of customer records — don’t block it, but pause and get a human to sign off” is now a policy you express directly, in one verdict, instead of building an approval system on the side.</p>

<p>A design decision that paid off repeatedly: the branching logic lives in the spine, not in the guards. A guard’s only job is to look at content and return a verdict. The pipeline decides what each verdict <em>means</em>: short-circuit on block, compose on sanitize, interrupt on approval. This keeps third-party guards small, even one that supports streaming (the <code class="language-plaintext highlighter-rouge">scan_chunk</code>/<code class="language-plaintext highlighter-rouge">finalize</code> pair is explained below):</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">BlockCompetitors</span><span class="p">:</span>
    <span class="n">name</span> <span class="o">=</span> <span class="sh">"</span><span class="s">block_competitors</span><span class="sh">"</span>
    <span class="n">streaming</span> <span class="o">=</span> <span class="sh">"</span><span class="s">incremental</span><span class="sh">"</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="n">self</span><span class="p">,</span> <span class="n">competitors</span><span class="p">:</span> <span class="nb">list</span><span class="p">[</span><span class="nb">str</span><span class="p">]):</span>
        <span class="n">self</span><span class="p">.</span><span class="n">competitors</span> <span class="o">=</span> <span class="p">[</span><span class="n">c</span><span class="p">.</span><span class="nf">lower</span><span class="p">()</span> <span class="k">for</span> <span class="n">c</span> <span class="ow">in</span> <span class="n">competitors</span><span class="p">]</span>

    <span class="k">def</span> <span class="nf">_check</span><span class="p">(</span><span class="n">self</span><span class="p">,</span> <span class="n">text</span><span class="p">:</span> <span class="nb">str</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="n">Verdict</span><span class="p">:</span>
        <span class="k">if</span> <span class="nf">any</span><span class="p">(</span><span class="n">c</span> <span class="ow">in</span> <span class="n">text</span><span class="p">.</span><span class="nf">lower</span><span class="p">()</span> <span class="k">for</span> <span class="n">c</span> <span class="ow">in</span> <span class="n">self</span><span class="p">.</span><span class="n">competitors</span><span class="p">):</span>
            <span class="k">return</span> <span class="n">Verdict</span><span class="p">.</span><span class="nf">block</span><span class="p">(</span><span class="sh">"</span><span class="s">competitor mention</span><span class="sh">"</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">Verdict</span><span class="p">.</span><span class="nf">allow</span><span class="p">()</span>

    <span class="k">async</span> <span class="k">def</span> <span class="nf">scan</span><span class="p">(</span><span class="n">self</span><span class="p">,</span> <span class="n">state</span><span class="p">:</span> <span class="n">RunState</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="n">Verdict</span><span class="p">:</span>
        <span class="c1"># Ingress, and egress on buffered routes: the whole conversation
</span>        <span class="k">return</span> <span class="n">self</span><span class="p">.</span><span class="nf">_check</span><span class="p">(</span><span class="sh">"</span><span class="s"> </span><span class="sh">"</span><span class="p">.</span><span class="nf">join</span><span class="p">(</span><span class="n">m</span><span class="p">.</span><span class="n">content</span> <span class="k">for</span> <span class="n">m</span> <span class="ow">in</span> <span class="n">state</span><span class="p">.</span><span class="n">messages</span><span class="p">))</span>

    <span class="k">async</span> <span class="k">def</span> <span class="nf">scan_chunk</span><span class="p">(</span><span class="n">self</span><span class="p">,</span> <span class="n">chunk</span><span class="p">:</span> <span class="nb">str</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="n">Verdict</span><span class="p">:</span>
        <span class="c1"># Streaming: every delta, before it reaches the client
</span>        <span class="k">return</span> <span class="n">self</span><span class="p">.</span><span class="nf">_check</span><span class="p">(</span><span class="n">chunk</span><span class="p">)</span>

    <span class="k">async</span> <span class="k">def</span> <span class="nf">finalize</span><span class="p">(</span><span class="n">self</span><span class="p">,</span> <span class="n">accumulated</span><span class="p">:</span> <span class="nb">str</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="n">Verdict</span><span class="p">:</span>
        <span class="c1"># Streaming: the full text, which also catches a name split across two chunks
</span>        <span class="k">return</span> <span class="n">self</span><span class="p">.</span><span class="nf">_check</span><span class="p">(</span><span class="n">accumulated</span><span class="p">)</span>
</code></pre></div></div>

<p>Guards are structural: there’s no base class to inherit, only the <code class="language-plaintext highlighter-rouge">Guardrail</code> protocol to satisfy, which is the entry-point discovery from the previous post doing its job.</p>

<p>Every verdict — including <code class="language-plaintext highlighter-rouge">allow</code> — is written to an append-only event log. “Which guard allowed this?” is always answerable after the fact. In a governance system the audit trail isn’t a feature you add; it’s a property of how verdicts flow, and designing it in from the verdict type up is much cheaper than bolting it on.</p>

<h2 id="the-streaming-problem">The streaming problem</h2>

<p>Here is the tension that took the longest to resolve, and the reason this post exists.</p>

<p>Egress guards want the <em>complete</em> model output before they judge it. A toxicity classifier cannot score half a sentence; a groundedness check needs the whole answer to compare against sources. But streaming wants to emit each token the instant it’s generated, because that’s the entire reason users like streaming. These two desires are in direct opposition, and most systems resolve the conflict by quietly picking one side and never mentioning it.</p>

<p>I had three options and spent real time on each.</p>

<p><strong>Always buffer.</strong> Wait for the full response, scan it, then send it all at once. This gives full guard fidelity and a product that feels broken next to every provider that streams. Acceptable as a <em>mode</em>; unacceptable as the only behavior.</p>

<p><strong>Always stream with windowed scanning.</strong> Release tokens a small window behind generation, scan incrementally as you go, do a final pass at the end. Good UX. But it silently weakens any guard that fundamentally needs full context, and this is the part that kept me up: the user has <em>no idea</em> their policy is now running at reduced fidelity. The dangerous failure here is not the weakened scan. It’s that the weakening is invisible. You think you have a groundedness guarantee; you have a guess.</p>

<p><strong>Capability negotiation.</strong> The option I shipped, and the one consistent with the rest of the architecture.</p>

<h2 id="making-the-trade-off-visible">Making the trade-off visible</h2>

<p>Every guardrail declares a capability as part of its contract: <code class="language-plaintext highlighter-rouge">streaming: none | incremental</code>. An incremental guard implements <code class="language-plaintext highlighter-rouge">scan_chunk()</code> for the streaming path plus a mandatory <code class="language-plaintext highlighter-rouge">finalize()</code> full-text pass at the end. A non-incremental guard implements only <code class="language-plaintext highlighter-rouge">scan()</code> and, by declaring so, states plainly that it needs the whole output.</p>

<p>At compile time — not per request — the graph assembler inspects each route’s egress guards and computes the streaming mode for that route:</p>

<ul>
  <li><strong>All egress guards incremental</strong> → the route streams, with a hold-back window so tokens are released slightly behind generation. If <code class="language-plaintext highlighter-rouge">finalize()</code> catches a violation that the incremental passes missed, the stream truncates and a violation event is logged.</li>
  <li><strong>Any guard non-incremental</strong> → the route buffers.</li>
</ul>

<pre><code class="language-mermaid">sequenceDiagram
    participant C as Client
    participant G as Aegis route
    participant P as Provider
    Note over G: compile time — is every egress guard incremental?
    C-&gt;&gt;G: request (stream: true)
    P--&gt;&gt;G: token
    G-&gt;&gt;G: scan_chunk()
    G--&gt;&gt;C: token (held-back window)
    P--&gt;&gt;G: token
    G-&gt;&gt;G: scan_chunk()
    G--&gt;&gt;C: token
    P--&gt;&gt;G: [done]
    G-&gt;&gt;G: finalize() full-text pass
    alt finalize clean
        G--&gt;&gt;C: [done]
    else late violation
        G--&gt;&gt;C: truncate + violation event
    end
</code></pre>

<p>The critical property is that the trade-off is <em>visible</em>. <code class="language-plaintext highlighter-rouge">aegis policy lint</code> reports every downgrade before anything runs:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>AEG-POL-007  Route 'default' cannot stream: guardrail 'toxicity_ml'
             declares streaming=none. Responses on this route will
             be buffered.
</code></pre></div></div>

<p>You are still completely free to put a full-context toxicity scanner on a route. You just learn, at lint time, that it costs you streaming on that route, and then you decide, with the cost in front of you. The trade-off is yours, made with eyes open, instead of a silent degradation you reverse-engineer from a production incident three weeks later.</p>

<p>The principle generalizes well beyond streaming, and it’s the through-line of the whole project: <strong>when a configuration weakens a guarantee, the tooling should say so out loud.</strong> Silent best-effort is the enemy of a governance tool, because the entire value proposition is that you can trust what it claims.</p>

<h2 id="honoring-the-wire-even-when-buffering">Honoring the wire even when buffering</h2>

<p>One more constraint shaped the implementation. A buffered route still has to answer clients that asked for <code class="language-plaintext highlighter-rouge">stream: true</code>, because Aegis exposes an OpenAI-compatible endpoint, and every OpenAI client in the world sends that flag and expects server-sent events back.</p>

<p>So a buffered route scans the full output, then emits it as valid OpenAI SSE frames after the fact. The client perceives higher latency; it never perceives a protocol error. This matters more than it sounds: compatibility is a contract you keep even when your internals can’t fully honor the spirit of the request. Breaking the wire format to signal an internal limitation just converts your problem into a problem for every downstream tool that integrated against the standard. Keep the wire; pay the latency; lint the reason.</p>

<h2 id="governing-the-traffic-everyone-ignores">Governing the traffic everyone ignores</h2>

<p>The payoff for getting the contract right shows up somewhere most gateways never look: tool calls.</p>

<p>When the model decides to call a tool (over the Model Context Protocol, in Aegis’s case), that call is model <em>output</em>. It can carry a masked PII placeholder out to an external service (an exfiltration path), or it can be a destructive action (<code class="language-plaintext highlighter-rouge">delete_record</code>). So it passes a tool-call guard on the way out. The tool’s result is untrusted <em>input</em>, and tool output is the prime prompt-injection vector in agentic systems, because it’s content the model will read and act on that you didn’t write. So it passes a tool-result guard on the way back in.</p>

<pre><code class="language-mermaid">flowchart TD
    M[Model node] -- tool call --&gt; TG[Tool-call guard]
    TG -- exfil / approval check --&gt; MCP[MCP tool · external]
    MCP -- result --&gt; TR[Tool-result guard]
    TR -- injection scan --&gt; M
    M -- final answer --&gt; EG[Egress guards]
</code></pre>

<p>There is no new interface for any of this. Both positions invoke the same <code class="language-plaintext highlighter-rouge">Guardrail</code> contract, just at different points in the execute subgraph. Per-tool policy — “<code class="language-plaintext highlighter-rouge">delete_record</code> requires approval” — reuses the <code class="language-plaintext highlighter-rouge">require_approval</code> verdict and the same human-in-the-loop interrupt machinery from the main pipeline, unchanged. Retrieved RAG documents flow through that same tool-result chain, because a document you indexed last month is also untrusted content the moment it re-enters a prompt.</p>

<p>That’s the dividend of getting the verdict contract right early: governing a brand-new traffic surface became a matter of placing existing nodes in new positions, not writing new machinery. The four verdicts, the audit log, the approval interrupt, all of it composed.</p>

<p><a href="/portfolio-site/blog/2026/05/27/the-honest-parts-residency-tenancy-scope/">The last post in this series</a> is about the parts of the design that required saying <em>no</em>: the residency model I refused to overclaim, the multi-tenancy I deliberately didn’t build, and why drawing those lines clearly was as much a part of the engineering as anything that shipped.</p>]]></content><author><name>Echo Yin</name></author><category term="ai" /><category term="ai" /><category term="llm" /><category term="guardrails" /><category term="streaming" /><category term="safety" /><category term="architecture" /><summary type="html"><![CDATA[A guardrail that silently runs at reduced fidelity is worse than no guardrail, because you've stopped watching. The hardest design problem in the Aegis rewrite was keeping safety honest under streaming. Here is the four-verdict model, the capability negotiation that resolved the streaming conflict, and how the same contract ends up governing tool calls.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://e-choness.github.io/portfolio-site/assets/images/blogs/streaming-guardrails.webp" /><media:content medium="image" url="https://e-choness.github.io/portfolio-site/assets/images/blogs/streaming-guardrails.webp" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Rebuilding an AI Gateway as a Framework, Not a Product</title><link href="https://e-choness.github.io/portfolio-site/blog/2026/05/13/rebuilding-aegis-as-a-framework/" rel="alternate" type="text/html" title="Rebuilding an AI Gateway as a Framework, Not a Product" /><published>2026-05-13T09:00:00+00:00</published><updated>2026-05-13T09:00:00+00:00</updated><id>https://e-choness.github.io/portfolio-site/blog/2026/05/13/rebuilding-aegis-as-a-framework</id><content type="html" xml:base="https://e-choness.github.io/portfolio-site/blog/2026/05/13/rebuilding-aegis-as-a-framework/"><![CDATA[<p>The first version of Aegis worked. It routed LLM traffic across providers, masked PII, classified data by sensitivity, and enforced per-team budgets. It also had a fixed pipeline — classify, then mask, then route, then call the provider, then scan the output — hardcoded as a single call chain inside one orchestration service. Adding a guardrail meant editing that service. Swapping the PII engine meant editing that service. Supporting a new provider meant editing that service.</p>

<p>That is the failure mode of building a gateway as a <em>product</em>: every capability lives in the core, so every change is a core change. It ships fast and then ossifies. The second a user wants a guardrail you didn’t anticipate, they’re forking you.</p>

<p>The rewrite started from a different question. Not “what features should the gateway have?” but “what is the smallest thing the core must know, and can everything else be a plugin?” This post is about that question and what it took to answer it honestly.</p>

<h2 id="the-kernel-knows-nothing">The kernel knows nothing</h2>

<p>The organizing principle of Aegis v2 is a sentence I kept repeating during design reviews until it stopped sounding strange: <strong>the kernel knows nothing about what the pipeline does.</strong></p>

<p>It knows four things. How to discover plugins. How to validate typed configuration. How to resolve secrets. How to compile a request pipeline into an executable graph. That is the entire job of the core. There is no <code class="language-plaintext highlighter-rouge">classify()</code> call in it, no <code class="language-plaintext highlighter-rouge">mask()</code> step, no hardcoded list of providers, no mention of PII or budgets or residency. Those words do not appear in the kernel.</p>

<p>Everything with an opinion implements one of seven contracts:</p>

<table>
  <thead>
    <tr>
      <th>Contract</th>
      <th>Responsibility</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">ModelProvider</code></td>
      <td>complete / stream / embed against a backend</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">Guardrail</code></td>
      <td>scan content, return a verdict</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">VectorStoreProvider</code> / <code class="language-plaintext highlighter-rouge">EmbeddingProvider</code></td>
      <td>RAG storage and embeddings</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">SecretProvider</code></td>
      <td>resolve a secret reference at config load</td>
    </tr>
    <tr>
      <td>Telemetry exporter</td>
      <td>ship observability data somewhere</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">PipelineNode</code></td>
      <td>arbitrary middleware in the request graph</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">Authenticator</code></td>
      <td>resolve request credentials into a principal</td>
    </tr>
  </tbody>
</table>

<p>The whole system is layered around that contract set:</p>

<pre><code class="language-mermaid">flowchart TD
    subgraph IF[Interfaces]
        CLI[CLI]
        REST[REST API · native + OpenAI-compat]
        MCPS[MCP server]
        SDK[SDKs · Python + TypeScript]
        CLI ~~~ MCPS
        REST ~~~ SDK
    end
    AUTH[Auth middleware — resolves Principal]
    subgraph PR[Pipeline runtime — LangGraph]
        direction LR
        IN[Ingress guards] --&gt; RX[Route + execute] --&gt; EG[Egress guards]
    end
    subgraph K[Plugin kernel]
        REG[Registry · entry points]
        CFG[Typed config + secrets]
        ASM[Graph assembler]
        HK[Hooks · pluggy]
        REG ~~~ ASM
        CFG ~~~ HK
    end
    subgraph C[Seven plugin contracts]
        MP[ModelProvider]
        GP[Guardrail]
        RG[VectorStore / Embedding]
        SP[SecretProvider]
        TE[Telemetry exporter]
        PN[PipelineNode]
        AU[Authenticator]
        MP ~~~ TE
        GP ~~~ PN
        RG ~~~ AU
    end
    subgraph PP[Optional policy packs]
        CL[Classification]
        RES[Residency]
        BUD[Budgets]
        PII[PII mask]
        CL ~~~ BUD
        RES ~~~ PII
    end
    IF --&gt; AUTH --&gt; PR --&gt; K --&gt; C
    PP -. implements .-&gt; C
</code></pre>

<p>Read that diagram top to bottom and the dependency direction is the whole argument: interfaces depend on the runtime, the runtime depends on the kernel, the kernel depends on the contracts, and the governance features at the bottom point <em>up</em> at the contracts too, exactly like any third-party plugin would. Nothing in the core points down at them.</p>

<p>Discovery uses Python entry points, the same mechanism pytest and Flake8 use to find plugins. A third-party package declares an entry point in its <code class="language-plaintext highlighter-rouge">pyproject.toml</code>, and Aegis finds it at startup with zero core changes:</p>

<div class="language-toml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">[</span><span class="n">project</span><span class="k">.</span><span class="n">entry-points</span><span class="k">.</span><span class="s">"aegis.guardrails"</span><span class="k">]</span>
<span class="n">block-competitors</span> <span class="o">=</span><span class="w"> </span><span class="s">"block_competitors:BlockCompetitors"</span>
</code></pre></div></div>

<p>This is deliberately boring, and boring is the point. Entry points have worked at ecosystem scale for over a decade. A plugin author already knows the pattern. I did not want anyone learning a bespoke Aegis plugin system; I wanted them reusing one they already understood.</p>

<h2 id="the-test-that-the-abstraction-is-real">The test that the abstraction is real</h2>

<p>Here is the trap with every “everything is a plugin” architecture I’ve seen fail: the core team builds the real features with private, internal APIs, and the public plugin interface becomes a second-class afterthought that can’t actually express anything serious. You discover this the first time an outside developer tries to build a real plugin and hits a wall the core team never hit, because the core team wasn’t using the public door.</p>

<p>I wanted a structural defense against that, not a good intention. The rule became: <strong>Aegis’s own governance features are plugins.</strong> Data classification, residency enforcement, budgets, PII masking: none of them live in the core. They are optional policy packs that import <em>only</em> the public <code class="language-plaintext highlighter-rouge">aegis</code> contracts. And an import-linter contract in CI fails the build if a pack reaches for anything private.</p>

<p>This changes the abstraction from aspiration to proof. If our own flagship features cannot be built on the public contracts, the contracts are wrong, and the build goes red before anyone merges. The policy packs are an executable, continuously-checked proof that the plugin API is sufficient for real work. The day an outside developer writes a guardrail, they are using the exact same interface that our PII pack uses, because there is no other interface.</p>

<p>It also produced a nice side effect for installation. Because the packs are separate, the base install stays slim:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>pip install aegis-ai            # kernel + server + CLI
pip install aegis-ai[pii]       # adds Presidio + a spaCy model
pip install aegis-ai[llm-guard] # adds the transformer scanners
pip install aegis-ai[rag]       # adds the vector libraries
</code></pre></div></div>

<p>A framework whose base <code class="language-plaintext highlighter-rouge">pip install</code> drags in torch and spaCy before you’ve sent a single request has already lost the argument that its kernel is small. The extras map one-to-one onto packs, so the mental model is clean: install the pack, get its dependencies, and nothing else.</p>

<h2 id="why-the-pipeline-is-a-graph">Why the pipeline is a graph</h2>

<p>The old call chain had a subtler problem than rigidity. It couldn’t express conditional flow without nesting. “If the data is classified RESTRICTED, route only to a compliant provider” became an <code class="language-plaintext highlighter-rouge">if</code> statement buried three functions deep — invisible to anyone reading the configuration, impossible to point at in an audit, and untestable in isolation.</p>

<p>In v2 the request lifecycle is a LangGraph <code class="language-plaintext highlighter-rouge">StateGraph</code>. The compliance rule becomes an <em>edge</em> in a graph: a thing you can draw, lint, and show an auditor. A request flows through a staged spine (ingress guards, then route, then execute, then egress guards), and each stage is populated from ordered node lists in <code class="language-plaintext highlighter-rouge">aegis.yaml</code>. The assembler compiles one graph per route at startup, so there is no per-request assembly cost and misconfiguration is caught at load, not in production.</p>

<pre><code class="language-mermaid">flowchart TD
    REQ([Request]) --&gt; AUTH@{ shape: hex, label: "Auth" }
    AUTH -- no principal --&gt; R401([401])
    AUTH --&gt; IN[Ingress guards]
    IN -- block --&gt; REF1([Refused + audit])
    IN -- require_approval --&gt; HOLD([Paused — HITL])
    HOLD -- approved --&gt; RT
    IN -- allow / sanitize --&gt; RT[Route]
    RT -- no compliant provider --&gt; REF2([Refused + audit])
    RT --&gt; EX[Execute]
    EX -- tool call --&gt; TOOL[Tool-call guard → MCP tool → Tool-result guard]
    TOOL -- result --&gt; EX
    EX --&gt; EG[Egress guards]
    EG -- block --&gt; REF3([Refused + audit])
    EG -- allow / sanitize --&gt; RESP([Response + audit])
</code></pre>

<p>Making the pipeline a graph bought four things that would each have been a project on its own.</p>

<ul>
  <li><strong>Conditional routing:</strong> visible structure rather than nested branches. The residency branch in that diagram is a real edge, not buried logic.</li>
  <li><strong>Checkpointing:</strong> runs persist and survive a server restart.</li>
  <li><strong>Human-in-the-loop:</strong> a guardrail can <em>pause</em> a request via an interrupt instead of only blocking it, and the run resumes later.</li>
  <li><strong>Streaming:</strong> first-class, with the runtime handling token flow.</li>
</ul>

<p>It also collapsed two concepts I’d been treating as separate. A “gateway request” and an “agent run” are now the same abstraction: a traversal of a graph. Adding agentic workflows later isn’t a new subsystem; it’s more nodes on the same runtime. That kind of leverage only comes from picking the right core abstraction before you build features on top of it.</p>

<h2 id="nodes-talk-through-state-not-through-each-other">Nodes talk through state, not through each other</h2>

<p>One detail that made the plugin model actually composable: nodes never call each other. They communicate only through a typed <code class="language-plaintext highlighter-rouge">RunState</code> that flows through the graph: the run id, the authenticated principal, the messages, a free-form <code class="language-plaintext highlighter-rouge">labels</code> dictionary, a mask map kept in a channel that is never serialized into model-visible text, the selected route, an append-only event log, and usage accumulators.</p>

<p>The <code class="language-plaintext highlighter-rouge">labels</code> field is how packs cooperate without coupling. The classification pack writes <code class="language-plaintext highlighter-rouge">labels.classification = "restricted"</code>. The residency pack <em>reads</em> <code class="language-plaintext highlighter-rouge">labels.classification</code> to decide which providers are eligible. Neither imports the other. Neither knows the other exists. They coordinate through shared state the way two Unix programs coordinate through a pipe, which means you can add, remove, or replace either one without touching the other. A third-party node and a built-in node are indistinguishable to the runtime, because both are just functions from state to a state delta.</p>

<h2 id="what-id-tell-someone-starting-this">What I’d tell someone starting this</h2>

<p>Three things, in order of how much time they saved.</p>

<p><strong>Pick the core abstraction before the features.</strong> The early design sessions argued about whether the pipeline was a call chain, a middleware stack, or a graph, not about which guardrails to support. The graph decision made every later decision easier and several later decisions free. Feature decisions made first would have calcified into the wrong core, and you cannot refactor your way out of a wrong core abstraction; you rewrite. I know, because v2 is that rewrite.</p>

<p><strong>Make dogfooding structural, not aspirational.</strong> “We use our own public API” is a lovely sentiment that erodes the first time a deadline makes a private shortcut faster. An import-linter rule that fails the build does not erode under deadline pressure. If you want your plugin interface to stay honest, hand its enforcement to a machine.</p>

<p><strong>Adopt standards as interfaces where the standard is the value; wrap everything fast-moving.</strong> Aegis programs directly against LangGraph’s graph and checkpointer, the official MCP SDK, and OpenTelemetry, because adopting those interfaces means plugin authors inherit those ecosystems on purpose. But it <em>wraps</em> fast-moving libraries like LiteLLM and the guardrail engines behind its own contracts, each imported in exactly one module. When a wrapped library breaks, the fix is one file and nothing else in the codebase ever knew it existed. Knowing which dependencies to adopt and which to quarantine is most of what dependency hygiene actually is.</p>

<p><a href="/portfolio-site/blog/2026/05/20/guardrails-that-tell-you-the-truth/">The next post</a> is about the single hardest part of the build: designing a guardrail contract that is configurable, composable, <em>and</em> honest about what it can guarantee, especially when streaming and full-context scanning want exactly opposite things.</p>]]></content><author><name>Echo Yin</name></author><category term="ai" /><category term="ai" /><category term="llm" /><category term="architecture" /><category term="langgraph" /><category term="plugins" /><category term="gateway" /><summary type="html"><![CDATA[The first version of Aegis worked, and that was the problem. Every governance feature was hardcoded into one request path, so every change was a core change. This is the story of throwing out the architecture and rebuilding around a small kernel and seven plugin contracts — what that bought, what it cost, and the decisions I'd defend.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://e-choness.github.io/portfolio-site/assets/images/blogs/aegis-framework.webp" /><media:content medium="image" url="https://e-choness.github.io/portfolio-site/assets/images/blogs/aegis-framework.webp" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Advanced RAG: Hybrid Search with Sparse and Dense Retrieval Plus Cross Encoder Reranking</title><link href="https://e-choness.github.io/portfolio-site/blog/2025/12/29/advanced-rag/" rel="alternate" type="text/html" title="Advanced RAG: Hybrid Search with Sparse and Dense Retrieval Plus Cross Encoder Reranking" /><published>2025-12-29T04:26:10+00:00</published><updated>2025-12-29T04:26:10+00:00</updated><id>https://e-choness.github.io/portfolio-site/blog/2025/12/29/advanced-rag</id><content type="html" xml:base="https://e-choness.github.io/portfolio-site/blog/2025/12/29/advanced-rag/"><![CDATA[<p>In a <a href="/portfolio-site/blog/2025/01/16/building-local-rag-system/">previous guide</a>, we built a basic PDF question answering system in thirty minutes. Many developers noticed that while it handles straightforward queries well, it struggles when encountering specialized terminology, lengthy corporate documents, or phrasing that deviates from the source text. The system can pull the wrong data, miss critical context, or completely fail to surface relevant answers.</p>

<p>This behavior is not a flaw in your large language model. It is the natural limitation of using a single retrieval strategy. Whether you rely solely on dense retrieval using semantic vectors or sparse retrieval using keyword matching, both methods have distinct blind spots. Dense retrieval handles abstract meaning well but misses exact technical terms. Sparse retrieval nails specific keywords but fails if the user words the question differently.</p>

<p>This guide resolves that core pain point by upgrading your RAG architecture with advanced hybrid search combining sparse search, dense search, and cross encoder reranking to maximize precision. We will walk through the concepts and provide production ready code so your pipeline can simultaneously grasp abstract intent and lock onto exact keywords.</p>

<h2 id="why-single-retrieval-strategies-fall-short">Why Single Retrieval Strategies Fall Short</h2>

<p>Relying on one retrieval method leaves clear gaps in your data architecture.</p>

<p>Dense retrieval converts text into vector embeddings to measure semantic similarity. Think of it as searching for a document by its overall theme rather than its exact wording. This approach shines when users ask conversational questions using synonyms. If your document states that the company offers five days of annual leave and a user asks about vacation time, dense retrieval easily bridges that gap. However, dense retrieval struggles with rare technical jargon, specific product codes, or medical terminology. These unique terms often get diluted during vector encoding. It is also highly vulnerable to typos or text abbreviations, and its accuracy drops if key information sits right on the edge of a text chunk boundary.</p>

<p>Conversely, sparse retrieval tools like the BM25 algorithm evaluate keyword frequency and document statistics. This is like searching for information by matching exact words in a book index. It is incredibly stable and highly sensitive to unique terms. Even if a complex legal term appears only once in your document, sparse retrieval will find it instantly. It executes rapidly because it bypasses heavy vector computations. Yet, sparse retrieval lacks semantic awareness. If a document discusses compensation packages but the user asks about salary details, sparse retrieval will flag it as irrelevant because the exact word does not match.</p>

<table>
  <thead>
    <tr>
      <th><strong>Dimension</strong></th>
      <th><strong>Dense Retrieval (Vector Search)</strong></th>
      <th><strong>Sparse Retrieval (BM25)</strong></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong>Core Logic</strong></td>
      <td>Semantic similarity matching</td>
      <td>Keyword frequency and weight matching</td>
    </tr>
    <tr>
      <td><strong>Key Strengths</strong></td>
      <td>Grasps context and handles synonyms</td>
      <td>Locks onto specific terms and offers high speed</td>
    </tr>
    <tr>
      <td><strong>Key Weaknesses</strong></td>
      <td>Misses rare technical terms; relies on text quality</td>
      <td>Lacks semantic understanding; fails with altered phrasing</td>
    </tr>
    <tr>
      <td><strong>Best Use Case</strong></td>
      <td>Conversational queries and conceptual matching</td>
      <td>Exact product codes and specialized jargon</td>
    </tr>
    <tr>
      <td><strong>Standard Tools</strong></td>
      <td>FAISS, Milvus, BGE Embedding Models</td>
      <td>BM25, Elasticsearch</td>
    </tr>
  </tbody>
</table>

<p>Combining these two methodologies creates a hybrid search pipeline that blends semantic comprehension with keyword precision.</p>

<h2 id="mechanics-of-contemporary-hybrid-search-and-reranking">Mechanics of Contemporary Hybrid Search and Reranking</h2>

<p>Modern hybrid retrieval goes beyond simply stitching two lists of results together. It runs a parallel execution pipeline followed by score normalization and a secondary cross encoder validation step.</p>

<p>The process begins with text preprocessing for the sparse engine: the user query and the document chunks are tokenized and stripped of stop words, so BM25 scores only the terms that carry meaning. The dense engine embeds the raw text, since the embedding model was trained on natural sentences.</p>

<pre><code class="language-mermaid">flowchart TB
  subgraph retrieve["Retrieve: two searches, one pool"]
    direction LR
    q([Query]) --&gt; emb[Embed query]
    q --&gt; tok[Tokenize +&lt;br/&gt;drop stop words]
    emb --&gt; dense[FAISS top-k&lt;br/&gt;cosine]
    tok --&gt; sparse[BM25 top-k]
    dense --&gt; pool[Candidate pool&lt;br/&gt;union of both]
    sparse --&gt; pool
  end
  subgraph rank["Rank and answer"]
    direction LR
    fuse["Fuse scores&lt;br/&gt;min-max, 0.6 dense + 0.4 sparse"] --&gt; rr[Cross-encoder rerank&lt;br/&gt;query + chunk together]
    rr --&gt; top[Top 4 chunks]
    top --&gt; llm[LLM answer]
  end
  retrieve -- "each candidate scored on both scales" --&gt; rank
</code></pre>

<p>Next, the system executes parallel dual engine retrieval. The query is sent simultaneously to the dense vector engine to fetch the top semantic matches and to the BM25 engine to pull the top keyword matches. Running these searches concurrently preserves low latency.</p>

<p>The critical phase is result fusion and normalization. Because vector similarity scores and BM25 scores use completely different scales, we must normalize them before combining them. A common production strategy uses min max scaling to bring both sets of scores into a zero to one range. We then apply relative weights, such as sixty percent emphasis on dense scores and forty percent on sparse scores, to calculate a unified hybrid score. A chunk found by only one engine still gets scored by the other, so a strong keyword match isn’t penalized just because it missed the vector top-k. (Reciprocal Rank Fusion, which combines ranks instead of scores, is a popular alternative that needs no normalization or weight tuning.)</p>

<p>The final layer introduces a cross encoder reranking model. While the initial hybrid search is fast and acts as an effective filter, it evaluates queries and documents independently. A reranker inspects the query and the retrieved text chunks together, analyzing deep contextual relationships to output an ultra precise relevance score. The system then sorts the chunks based on this final score and passes the most relevant pieces to the language model.</p>

<h2 id="production-implementation-code-walkthrough">Production Implementation: Code Walkthrough</h2>

<p>We will now rebuild the RAG retrieval module. We will integrate BM25 sparse search, implement normalized hybrid fusion, and add a cross encoder reranker. The code uses the official OpenAI client package, pointed at DeepSeek’s OpenAI-compatible API; any compatible endpoint, including a local Ollama server, works by changing <code class="language-plaintext highlighter-rouge">base_url</code> and <code class="language-plaintext highlighter-rouge">model</code>.</p>

<p>First, update your environment with the required packages.</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>pip <span class="nb">install </span>rank_bm25 faiss-cpu sentence-transformers openai pypdf langchain-text-splitters
</code></pre></div></div>

<p>Below is the complete implementation of the upgraded pipeline.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="n">os</span>
<span class="kn">import</span> <span class="n">re</span>

<span class="kn">import</span> <span class="n">faiss</span>
<span class="kn">import</span> <span class="n">numpy</span> <span class="k">as</span> <span class="n">np</span>
<span class="kn">from</span> <span class="n">langchain_text_splitters</span> <span class="kn">import</span> <span class="n">RecursiveCharacterTextSplitter</span>
<span class="kn">from</span> <span class="n">openai</span> <span class="kn">import</span> <span class="n">OpenAI</span>
<span class="kn">from</span> <span class="n">pypdf</span> <span class="kn">import</span> <span class="n">PdfReader</span>
<span class="kn">from</span> <span class="n">rank_bm25</span> <span class="kn">import</span> <span class="n">BM25Okapi</span>
<span class="kn">from</span> <span class="n">sentence_transformers</span> <span class="kn">import</span> <span class="n">CrossEncoder</span><span class="p">,</span> <span class="n">SentenceTransformer</span>

<span class="c1"># Global pipeline configurations
</span><span class="n">PDF_PATH</span> <span class="o">=</span> <span class="sh">"</span><span class="s">your_document.pdf</span><span class="sh">"</span>
<span class="n">DENSE_WEIGHT</span> <span class="o">=</span> <span class="mf">0.6</span>
<span class="n">SPARSE_WEIGHT</span> <span class="o">=</span> <span class="mf">0.4</span>
<span class="n">TOP_K_RETRIEVAL</span> <span class="o">=</span> <span class="mi">10</span>
<span class="n">TOP_K_FINAL</span> <span class="o">=</span> <span class="mi">4</span>

<span class="c1"># English setup. For Chinese documents, switch EMBED_MODEL to
# "BAAI/bge-large-zh-v1.5" and tokenize with jieba (pip install jieba):
# tokens = jieba.lcut(text), since \w+ can't split Chinese into words.
</span><span class="n">EMBED_MODEL</span> <span class="o">=</span> <span class="sh">"</span><span class="s">BAAI/bge-large-en-v1.5</span><span class="sh">"</span>
<span class="n">RERANK_MODEL</span> <span class="o">=</span> <span class="sh">"</span><span class="s">BAAI/bge-reranker-large</span><span class="sh">"</span>  <span class="c1"># trained on English and Chinese
</span><span class="n">STOP_WORDS</span> <span class="o">=</span> <span class="p">{</span><span class="sh">"</span><span class="s">a</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">an</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">and</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">are</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">for</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">in</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">is</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">of</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">on</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">or</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">the</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">to</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">what</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">with</span><span class="sh">"</span><span class="p">}</span>

<span class="k">def</span> <span class="nf">tokenize</span><span class="p">(</span><span class="n">text</span><span class="p">):</span>
    <span class="sh">"""</span><span class="s">Lowercases, splits into words and drops stop words (sparse index only).</span><span class="sh">"""</span>
    <span class="k">return</span> <span class="p">[</span><span class="n">t</span> <span class="k">for</span> <span class="n">t</span> <span class="ow">in</span> <span class="n">re</span><span class="p">.</span><span class="nf">findall</span><span class="p">(</span><span class="sa">r</span><span class="sh">"</span><span class="s">\w+</span><span class="sh">"</span><span class="p">,</span> <span class="n">text</span><span class="p">.</span><span class="nf">lower</span><span class="p">())</span> <span class="k">if</span> <span class="n">t</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">STOP_WORDS</span><span class="p">]</span>

<span class="k">def</span> <span class="nf">minmax</span><span class="p">(</span><span class="n">scores</span><span class="p">):</span>
    <span class="sh">"""</span><span class="s">Scales scores into [0, 1] so dense and sparse scores are comparable.</span><span class="sh">"""</span>
    <span class="n">lo</span><span class="p">,</span> <span class="n">hi</span> <span class="o">=</span> <span class="n">scores</span><span class="p">.</span><span class="nf">min</span><span class="p">(),</span> <span class="n">scores</span><span class="p">.</span><span class="nf">max</span><span class="p">()</span>
    <span class="nf">return </span><span class="p">(</span><span class="n">scores</span> <span class="o">-</span> <span class="n">lo</span><span class="p">)</span> <span class="o">/</span> <span class="p">(</span><span class="n">hi</span> <span class="o">-</span> <span class="n">lo</span><span class="p">)</span> <span class="k">if</span> <span class="n">hi</span> <span class="o">&gt;</span> <span class="n">lo</span> <span class="k">else</span> <span class="n">np</span><span class="p">.</span><span class="nf">ones_like</span><span class="p">(</span><span class="n">scores</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">extract_and_chunk_pdf</span><span class="p">(</span><span class="n">pdf_path</span><span class="p">):</span>
    <span class="sh">"""</span><span class="s">Extracts raw text from PDF and splits it into manageable chunks.</span><span class="sh">"""</span>
    <span class="n">reader</span> <span class="o">=</span> <span class="nc">PdfReader</span><span class="p">(</span><span class="n">pdf_path</span><span class="p">)</span>
    <span class="c1"># Join pages with a newline so words at page boundaries don't fuse
</span>    <span class="n">raw_text</span> <span class="o">=</span> <span class="sh">"</span><span class="se">\n</span><span class="sh">"</span><span class="p">.</span><span class="nf">join</span><span class="p">(</span><span class="n">page</span><span class="p">.</span><span class="nf">extract_text</span><span class="p">()</span> <span class="ow">or</span> <span class="sh">""</span> <span class="k">for</span> <span class="n">page</span> <span class="ow">in</span> <span class="n">reader</span><span class="p">.</span><span class="n">pages</span><span class="p">)</span>

    <span class="n">splitter</span> <span class="o">=</span> <span class="nc">RecursiveCharacterTextSplitter</span><span class="p">(</span><span class="n">chunk_size</span><span class="o">=</span><span class="mi">500</span><span class="p">,</span> <span class="n">chunk_overlap</span><span class="o">=</span><span class="mi">50</span><span class="p">)</span>
    <span class="k">return</span> <span class="p">[</span><span class="n">chunk</span> <span class="k">for</span> <span class="n">chunk</span> <span class="ow">in</span> <span class="n">splitter</span><span class="p">.</span><span class="nf">split_text</span><span class="p">(</span><span class="n">raw_text</span><span class="p">)</span> <span class="k">if</span> <span class="n">chunk</span><span class="p">.</span><span class="nf">strip</span><span class="p">()]</span>

<span class="k">class</span> <span class="nc">AdvancedHybridRetriever</span><span class="p">:</span>
    <span class="sh">"""</span><span class="s">Manages dual engine search and cross encoder reranking.</span><span class="sh">"""</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="n">self</span><span class="p">,</span> <span class="n">corpus</span><span class="p">):</span>
        <span class="n">self</span><span class="p">.</span><span class="n">corpus</span> <span class="o">=</span> <span class="n">corpus</span>
        <span class="n">self</span><span class="p">.</span><span class="n">dense_model</span> <span class="o">=</span> <span class="nc">SentenceTransformer</span><span class="p">(</span><span class="n">EMBED_MODEL</span><span class="p">)</span>
        <span class="n">self</span><span class="p">.</span><span class="n">reranker</span> <span class="o">=</span> <span class="nc">CrossEncoder</span><span class="p">(</span><span class="n">RERANK_MODEL</span><span class="p">)</span>

        <span class="c1"># Dense index: normalized vectors, so inner product = cosine similarity.
</span>        <span class="c1"># Keep the vectors to score sparse-only candidates on the dense scale too.
</span>        <span class="n">self</span><span class="p">.</span><span class="n">embeddings</span> <span class="o">=</span> <span class="n">self</span><span class="p">.</span><span class="n">dense_model</span><span class="p">.</span><span class="nf">encode</span><span class="p">(</span>
            <span class="n">corpus</span><span class="p">,</span> <span class="n">normalize_embeddings</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">show_progress_bar</span><span class="o">=</span><span class="bp">False</span>
        <span class="p">)</span>
        <span class="n">self</span><span class="p">.</span><span class="n">faiss_index</span> <span class="o">=</span> <span class="n">faiss</span><span class="p">.</span><span class="nc">IndexFlatIP</span><span class="p">(</span><span class="n">self</span><span class="p">.</span><span class="n">embeddings</span><span class="p">.</span><span class="n">shape</span><span class="p">[</span><span class="mi">1</span><span class="p">])</span>
        <span class="n">self</span><span class="p">.</span><span class="n">faiss_index</span><span class="p">.</span><span class="nf">add</span><span class="p">(</span><span class="n">self</span><span class="p">.</span><span class="n">embeddings</span><span class="p">)</span>

        <span class="c1"># Sparse index: BM25 over the same chunks
</span>        <span class="n">self</span><span class="p">.</span><span class="n">bm25</span> <span class="o">=</span> <span class="nc">BM25Okapi</span><span class="p">([</span><span class="nf">tokenize</span><span class="p">(</span><span class="n">doc</span><span class="p">)</span> <span class="k">for</span> <span class="n">doc</span> <span class="ow">in</span> <span class="n">corpus</span><span class="p">])</span>

    <span class="k">def</span> <span class="nf">retrieve</span><span class="p">(</span><span class="n">self</span><span class="p">,</span> <span class="n">query</span><span class="p">):</span>
        <span class="c1"># 1. Dense semantic search
</span>        <span class="n">q</span> <span class="o">=</span> <span class="n">self</span><span class="p">.</span><span class="n">dense_model</span><span class="p">.</span><span class="nf">encode</span><span class="p">([</span><span class="n">query</span><span class="p">],</span> <span class="n">normalize_embeddings</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
        <span class="n">_</span><span class="p">,</span> <span class="n">dense_idx</span> <span class="o">=</span> <span class="n">self</span><span class="p">.</span><span class="n">faiss_index</span><span class="p">.</span><span class="nf">search</span><span class="p">(</span><span class="n">q</span><span class="p">,</span> <span class="n">TOP_K_RETRIEVAL</span><span class="p">)</span>

        <span class="c1"># 2. Sparse keyword search, skipped if the query is only stop words
</span>        <span class="n">q_tokens</span> <span class="o">=</span> <span class="nf">tokenize</span><span class="p">(</span><span class="n">query</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">q_tokens</span><span class="p">:</span>
            <span class="n">sparse_scores</span> <span class="o">=</span> <span class="n">self</span><span class="p">.</span><span class="n">bm25</span><span class="p">.</span><span class="nf">get_scores</span><span class="p">(</span><span class="n">q_tokens</span><span class="p">)</span>
            <span class="n">dense_weight</span><span class="p">,</span> <span class="n">sparse_weight</span> <span class="o">=</span> <span class="n">DENSE_WEIGHT</span><span class="p">,</span> <span class="n">SPARSE_WEIGHT</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">sparse_scores</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="nf">zeros</span><span class="p">(</span><span class="nf">len</span><span class="p">(</span><span class="n">self</span><span class="p">.</span><span class="n">corpus</span><span class="p">))</span>
            <span class="n">dense_weight</span><span class="p">,</span> <span class="n">sparse_weight</span> <span class="o">=</span> <span class="mf">1.0</span><span class="p">,</span> <span class="mf">0.0</span>
        <span class="n">sparse_idx</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="nf">argsort</span><span class="p">(</span><span class="n">sparse_scores</span><span class="p">)[::</span><span class="o">-</span><span class="mi">1</span><span class="p">][:</span><span class="n">TOP_K_RETRIEVAL</span><span class="p">]</span>

        <span class="c1"># 3. Fusion: score every candidate from either list on BOTH scales,
</span>        <span class="c1">#    min-max normalize each over the pool, then weight and sort
</span>        <span class="n">candidates</span> <span class="o">=</span> <span class="nf">sorted</span><span class="p">(</span>
            <span class="p">{</span><span class="nf">int</span><span class="p">(</span><span class="n">i</span><span class="p">)</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">dense_idx</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="k">if</span> <span class="n">i</span> <span class="o">!=</span> <span class="o">-</span><span class="mi">1</span><span class="p">}</span>
            <span class="o">|</span> <span class="p">{</span><span class="nf">int</span><span class="p">(</span><span class="n">i</span><span class="p">)</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">sparse_idx</span> <span class="k">if</span> <span class="n">sparse_scores</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">}</span>
        <span class="p">)</span>
        <span class="n">dense</span> <span class="o">=</span> <span class="n">self</span><span class="p">.</span><span class="n">embeddings</span><span class="p">[</span><span class="n">candidates</span><span class="p">]</span> <span class="o">@</span> <span class="n">q</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
        <span class="n">sparse</span> <span class="o">=</span> <span class="n">sparse_scores</span><span class="p">[</span><span class="n">candidates</span><span class="p">]</span>
        <span class="n">hybrid</span> <span class="o">=</span> <span class="n">dense_weight</span> <span class="o">*</span> <span class="nf">minmax</span><span class="p">(</span><span class="n">dense</span><span class="p">)</span> <span class="o">+</span> <span class="n">sparse_weight</span> <span class="o">*</span> <span class="nf">minmax</span><span class="p">(</span><span class="n">sparse</span><span class="p">)</span>
        <span class="n">order</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="nf">argsort</span><span class="p">(</span><span class="n">hybrid</span><span class="p">)[::</span><span class="o">-</span><span class="mi">1</span><span class="p">][:</span><span class="n">TOP_K_RETRIEVAL</span><span class="p">]</span>
        <span class="n">retrieved_chunks</span> <span class="o">=</span> <span class="p">[</span><span class="n">self</span><span class="p">.</span><span class="n">corpus</span><span class="p">[</span><span class="n">candidates</span><span class="p">[</span><span class="n">i</span><span class="p">]]</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">order</span><span class="p">]</span>

        <span class="c1"># 4. Cross encoder reranking: read query and chunk together
</span>        <span class="n">rerank_scores</span> <span class="o">=</span> <span class="n">self</span><span class="p">.</span><span class="n">reranker</span><span class="p">.</span><span class="nf">predict</span><span class="p">([(</span><span class="n">query</span><span class="p">,</span> <span class="n">chunk</span><span class="p">)</span> <span class="k">for</span> <span class="n">chunk</span> <span class="ow">in</span> <span class="n">retrieved_chunks</span><span class="p">])</span>
        <span class="n">best</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="nf">argsort</span><span class="p">(</span><span class="n">rerank_scores</span><span class="p">)[::</span><span class="o">-</span><span class="mi">1</span><span class="p">][:</span><span class="n">TOP_K_FINAL</span><span class="p">]</span>
        <span class="k">return</span> <span class="p">[</span><span class="n">retrieved_chunks</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">best</span><span class="p">]</span>

<span class="k">def</span> <span class="nf">ask_llm</span><span class="p">(</span><span class="n">query</span><span class="p">,</span> <span class="n">context_chunks</span><span class="p">):</span>
    <span class="sh">"""</span><span class="s">Sends the context and query to DeepSeek via standard OpenAI client integration.</span><span class="sh">"""</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">context_chunks</span><span class="p">:</span>
        <span class="k">return</span> <span class="sh">"</span><span class="s">No relevant documentation found.</span><span class="sh">"</span>

    <span class="n">client</span> <span class="o">=</span> <span class="nc">OpenAI</span><span class="p">(</span>
        <span class="n">api_key</span><span class="o">=</span><span class="n">os</span><span class="p">.</span><span class="n">environ</span><span class="p">[</span><span class="sh">"</span><span class="s">DEEPSEEK_API_KEY</span><span class="sh">"</span><span class="p">],</span>
        <span class="n">base_url</span><span class="o">=</span><span class="sh">"</span><span class="s">https://api.deepseek.com/v1</span><span class="sh">"</span><span class="p">,</span>
    <span class="p">)</span>

    <span class="n">context_text</span> <span class="o">=</span> <span class="sh">"</span><span class="se">\n\n</span><span class="sh">"</span><span class="p">.</span><span class="nf">join</span><span class="p">(</span><span class="n">context_chunks</span><span class="p">)</span>
    <span class="n">prompt</span> <span class="o">=</span> <span class="p">(</span>
        <span class="sh">"</span><span class="s">Answer the question using only the documentation below. </span><span class="sh">"</span>
        <span class="sh">"</span><span class="s">If the answer is not there, say so.</span><span class="se">\n\n</span><span class="sh">"</span>
        <span class="sa">f</span><span class="sh">"</span><span class="s">Context:</span><span class="se">\n</span><span class="si">{</span><span class="n">context_text</span><span class="si">}</span><span class="se">\n\n</span><span class="s">Question: </span><span class="si">{</span><span class="n">query</span><span class="si">}</span><span class="sh">"</span>
    <span class="p">)</span>

    <span class="n">response</span> <span class="o">=</span> <span class="n">client</span><span class="p">.</span><span class="n">chat</span><span class="p">.</span><span class="n">completions</span><span class="p">.</span><span class="nf">create</span><span class="p">(</span>
        <span class="n">model</span><span class="o">=</span><span class="sh">"</span><span class="s">deepseek-chat</span><span class="sh">"</span><span class="p">,</span>
        <span class="n">messages</span><span class="o">=</span><span class="p">[{</span><span class="sh">"</span><span class="s">role</span><span class="sh">"</span><span class="p">:</span> <span class="sh">"</span><span class="s">user</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">content</span><span class="sh">"</span><span class="p">:</span> <span class="n">prompt</span><span class="p">}],</span>
        <span class="n">temperature</span><span class="o">=</span><span class="mf">0.1</span><span class="p">,</span>
    <span class="p">)</span>
    <span class="k">return</span> <span class="n">response</span><span class="p">.</span><span class="n">choices</span><span class="p">[</span><span class="mi">0</span><span class="p">].</span><span class="n">message</span><span class="p">.</span><span class="n">content</span>

<span class="k">if</span> <span class="n">__name__</span> <span class="o">==</span> <span class="sh">"</span><span class="s">__main__</span><span class="sh">"</span><span class="p">:</span>
    <span class="nf">print</span><span class="p">(</span><span class="sh">"</span><span class="s">Extracting text and chunking document...</span><span class="sh">"</span><span class="p">)</span>
    <span class="n">document_chunks</span> <span class="o">=</span> <span class="nf">extract_and_chunk_pdf</span><span class="p">(</span><span class="n">PDF_PATH</span><span class="p">)</span>
    <span class="nf">print</span><span class="p">(</span><span class="sa">f</span><span class="sh">"</span><span class="s">Created </span><span class="si">{</span><span class="nf">len</span><span class="p">(</span><span class="n">document_chunks</span><span class="p">)</span><span class="si">}</span><span class="s"> discrete text units.</span><span class="sh">"</span><span class="p">)</span>

    <span class="nf">print</span><span class="p">(</span><span class="sh">"</span><span class="s">Initializing hybrid retrieval engines and reranker...</span><span class="sh">"</span><span class="p">)</span>
    <span class="n">search_engine</span> <span class="o">=</span> <span class="nc">AdvancedHybridRetriever</span><span class="p">(</span><span class="n">document_chunks</span><span class="p">)</span>
    <span class="nf">print</span><span class="p">(</span><span class="sh">"</span><span class="s">Pipeline ready for queries.</span><span class="sh">"</span><span class="p">)</span>

    <span class="n">user_query</span> <span class="o">=</span> <span class="sh">"</span><span class="s">What are the specific penalty terms for contract violations?</span><span class="sh">"</span>
    <span class="n">matched_contexts</span> <span class="o">=</span> <span class="n">search_engine</span><span class="p">.</span><span class="nf">retrieve</span><span class="p">(</span><span class="n">user_query</span><span class="p">)</span>
    <span class="n">final_answer</span> <span class="o">=</span> <span class="nf">ask_llm</span><span class="p">(</span><span class="n">user_query</span><span class="p">,</span> <span class="n">matched_contexts</span><span class="p">)</span>

    <span class="nf">print</span><span class="p">(</span><span class="sa">f</span><span class="sh">"</span><span class="se">\n</span><span class="s">Query: </span><span class="si">{</span><span class="n">user_query</span><span class="si">}</span><span class="sh">"</span><span class="p">)</span>
    <span class="nf">print</span><span class="p">(</span><span class="sa">f</span><span class="sh">"</span><span class="s">Answer:</span><span class="se">\n</span><span class="si">{</span><span class="n">final_answer</span><span class="si">}</span><span class="sh">"</span><span class="p">)</span>
</code></pre></div></div>

<h3 id="walking-through-the-code">Walking through the code</h3>

<p><strong>Configuration.</strong></p>
<ul>
  <li><code class="language-plaintext highlighter-rouge">DENSE_WEIGHT</code> / <code class="language-plaintext highlighter-rouge">SPARSE_WEIGHT</code> set how much each engine counts in the final score.</li>
  <li><code class="language-plaintext highlighter-rouge">TOP_K_RETRIEVAL = 10</code> is how many candidates each engine contributes.</li>
  <li><code class="language-plaintext highlighter-rouge">TOP_K_FINAL = 4</code> is how many chunks reach the LLM.</li>
  <li><code class="language-plaintext highlighter-rouge">EMBED_MODEL</code>, <code class="language-plaintext highlighter-rouge">RERANK_MODEL</code> and <code class="language-plaintext highlighter-rouge">STOP_WORDS</code> are the language-specific parts; everything else is language-neutral.</li>
</ul>

<p><strong><code class="language-plaintext highlighter-rouge">tokenize</code></strong> prepares text for BM25 only: lowercase it, split it into words, drop stop words. BM25 scores on exact term overlap, so “Penalty” and “penalty” must become the same token, and words like “the” would otherwise match everything.</p>

<p><strong><code class="language-plaintext highlighter-rouge">minmax</code></strong> rescales a set of scores to 0–1. It’s needed because cosine similarity lives roughly in 0.3–0.9 while BM25 scores are unbounded (8.2, 14.7, …); adding them raw would let BM25 drown out the dense score. The <code class="language-plaintext highlighter-rouge">hi &gt; lo</code> guard avoids dividing by zero when every candidate scored the same.</p>

<p><strong><code class="language-plaintext highlighter-rouge">extract_and_chunk_pdf</code></strong> extracts all pages (joined with newlines) and splits them with LangChain’s <code class="language-plaintext highlighter-rouge">RecursiveCharacterTextSplitter</code>. The recursive splitter tries paragraph breaks first, then lines, then sentences, then words, so chunks end at natural boundaries whenever possible.</p>

<p><strong><code class="language-plaintext highlighter-rouge">AdvancedHybridRetriever.__init__</code></strong> builds both indexes once, over the same chunk list:</p>
<ul>
  <li><strong>Dense</strong>: normalized embeddings in a FAISS inner-product index, where inner product equals cosine similarity. The embeddings are also kept in <code class="language-plaintext highlighter-rouge">self.embeddings</code>, which the fusion step needs.</li>
  <li><strong>Sparse</strong>: <code class="language-plaintext highlighter-rouge">BM25Okapi</code> over the tokenized chunks.</li>
</ul>

<p><strong><code class="language-plaintext highlighter-rouge">retrieve</code></strong> works in four steps, matching the diagram above:</p>

<ol>
  <li><strong>Dense search</strong> returns the indices of the 10 nearest chunks.</li>
  <li><strong>Sparse search</strong> scores <em>every</em> chunk with BM25 and takes the 10 best. If the query was nothing but stop words, there’s nothing for BM25 to match, so the weights fall back to 100% dense.</li>
  <li><strong>Fusion</strong> is where most hybrid implementations cut corners:
    <ul>
      <li>The candidate pool is the <strong>union</strong> of both top-10 lists (up to 20 chunks). Chunks with a BM25 score of 0 are excluded from the sparse side.</li>
      <li>Each candidate gets <strong>both</strong> scores. The dense one is computed directly as <code class="language-plaintext highlighter-rouge">self.embeddings[candidates] @ q[0]</code>, a single matrix-vector product, so a chunk BM25 found but FAISS didn’t still gets its real similarity instead of a 0.</li>
      <li>Both score sets are min-max normalized <em>over this pool</em>, then weighted and added.</li>
      <li>The top 10 by hybrid score go on to reranking.</li>
    </ul>
  </li>
  <li><strong>Reranking</strong>: the cross-encoder reads each <code class="language-plaintext highlighter-rouge">(query, chunk)</code> pair together, so it can judge whether the chunk actually <em>answers</em> the question, not just whether it shares words or topic. The best 4 are returned.</li>
</ol>

<p><strong><code class="language-plaintext highlighter-rouge">ask_llm</code></strong> sends the chunks to any OpenAI-compatible endpoint.</p>
<ul>
  <li>The key comes from <code class="language-plaintext highlighter-rouge">os.environ</code>, so a missing key fails loudly at startup instead of sending an invalid key to the API.</li>
  <li>The prompt restricts the model to the provided documentation and tells it to say so when the answer isn’t there.</li>
  <li><code class="language-plaintext highlighter-rouge">temperature=0.1</code> keeps answers close to deterministic, which is what you want for factual Q&amp;A.</li>
</ul>

<h2 id="optimization-strategies-for-advanced-deployments">Optimization Strategies for Advanced Deployments</h2>

<p><strong>Dynamic Parameter Tuning</strong></p>

<p>Instead of keeping your dense and sparse weights static, you can adjust them based on the incoming query structure. If the query contains highly specific technical identifiers, alphanumeric product codes, or exact serial numbers, programmatic detection can shift the sparse weight higher. If the user query is long and conversational, the system can favor the dense retrieval engine.</p>

<p><strong>Advanced Semantic Chunking</strong></p>

<p>Fixed size token chunking often breaks paragraphs mid sentence, destroying the semantic unity of the text. Upgrading to semantic chunking allows your system to monitor embedding drift between sentences. The document breaks only when a meaningful shift in topic occurs, ensuring that the dense vector representations remain pure and contextually complete.</p>

<p><strong>Cross Encoder Reranking Scaling</strong></p>

<p>While cross encoders provide exceptional accuracy, they introduce higher computational latency compared to bi encoders. To maintain high performance in production environments, implement a two tier architecture. Use the hybrid retrieval layer to filter thousands of documents down to a small candidate pool of perhaps fifteen or twenty blocks, then pass only that small pool to the reranker.</p>

<h2 id="resolving-common-deployment-challenges">Resolving Common Deployment Challenges</h2>

<p><strong>Empty Keyword Tokens</strong></p>

<p>When a query consists purely of common stop words, the tokenization process can return an empty list, forcing the sparse engine to output flat zeros. To resolve this, implement a fallback mechanism that bypasses the sparse scoring stage completely if no valid keywords remain after filtering.</p>

<p><strong>Latency Bottlenecks</strong></p>

<p>If your database scales to millions of chunks, running unindexed keyword searches alongside dense calculations will slow down response times. Ensure that your sparse index leverages an optimized inverted index framework like Elasticsearch or Milvus sparse vectors, and limit the initial retrieval count to a tight window.</p>

<p><strong>Mismatched Reranker Scales</strong></p>

<p>Using a reranker model trained on general web text might downgrade the relevance of highly specialized internal corporate documentation. Always verify that your cross encoder matches the primary language and domain of your dataset, or consider fine tuning a lightweight open source model on your specific documentation history.</p>

<p>Modern RAG success relies heavily on high quality data retrieval. Moving to a hybrid architecture backed by dual engines and cross encoder validation removes the structural blind spots of single strategy systems. By implementing these patterns, you bridge the gap between abstract understanding and exact keyword tracking, giving your enterprise application production level precision.</p>]]></content><author><name>Echo Yin</name></author><category term="ai" /><category term="ai" /><category term="rag" /><category term="hybrid-search" /><category term="llm" /><summary type="html"><![CDATA[Learn how to upgrade your RAG system with hybrid search combining sparse (BM25) and dense (vector) retrieval, enhanced with cross encoder reranking for maximum precision in document question answering.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://e-choness.github.io/portfolio-site/assets/images/blogs/advanced-rag.webp" /><media:content medium="image" url="https://e-choness.github.io/portfolio-site/assets/images/blogs/advanced-rag.webp" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Building Aegis: An Enterprise AI Gateway</title><link href="https://e-choness.github.io/portfolio-site/blog/2025/11/25/aegis-ai-gateway/" rel="alternate" type="text/html" title="Building Aegis: An Enterprise AI Gateway" /><published>2025-11-25T12:00:00+00:00</published><updated>2025-11-25T12:00:00+00:00</updated><id>https://e-choness.github.io/portfolio-site/blog/2025/11/25/aegis-ai-gateway</id><content type="html" xml:base="https://e-choness.github.io/portfolio-site/blog/2025/11/25/aegis-ai-gateway/"><![CDATA[<p>When I started working on <a href="https://github.com/e-choness/aegis">Aegis</a>, I wasn’t trying to build yet another AI platform. I was trying to solve a real problem: how do you bring AI into an enterprise without turning your organization into a compliance nightmare? Companies were already using LLMs for everything from code reviews to customer support, but they were doing it haphazardly—different teams using different providers, no visibility into costs, and worst of all, no guarantee that sensitive data wasn’t leaking to third-party APIs.</p>

<p>I wanted to create something that felt like a natural extension of existing infrastructure, not a disruptive new layer. The result is Aegis, a provider-agnostic AI gateway that sits between your applications and LLM providers, handling governance, compliance, and optimization automatically.</p>

<h2 id="the-core-problem-fragmented-ai-adoption">The Core Problem: Fragmented AI Adoption</h2>

<p>Before Aegis, AI integration looked like this: every team would pick their favorite LLM provider, hardcode API keys into their applications, and hope for the best. This created several problems that I knew I had to address.</p>

<p>First, there was no centralized control. If Anthropic changed their API, you’d have to update code across dozens of services. Second, costs were spiraling out of control—teams would use expensive Opus models for simple tasks like summarizing commit messages. Third, and most critically, there was no way to prevent sensitive data from leaving your network. A developer might accidentally include a customer’s credit card number in a prompt, and it would go straight to a cloud API.</p>

<p>I decided early on that Aegis needed to be the single point of control for all AI traffic in an organization. But I also wanted it to be invisible to developers—something that just worked without requiring major changes to existing workflows.</p>

<p>Here is the path every request takes; the rest of this post walks through each stage:</p>

<pre><code class="language-mermaid">flowchart LR
  subgraph intake["1 · Intake"]
    direction TB
    app([App / SDK]) -- "submit, get job ID" --&gt; cls[Classify data&lt;br/&gt;regex, ~0.2 ms]
    cls --&gt; r@{ shape: hex, label: "RESTRICTED?" }
    r -- yes --&gt; local[Local Ollama only&lt;br/&gt;never leaves the&lt;br/&gt;network, still audited]
  end
  subgraph guard["2 · Before any LLM call"]
    direction TB
    pii[Mask PII&lt;br/&gt;Presidio + CA SIN] --&gt; bud@{ shape: hex, label: "Budget&lt;br/&gt;estimate OK?" }
    bud -- no --&gt; rej([Rejected before&lt;br/&gt;any LLM call])
  end
  subgraph record["3 · Call and record"]
    direction TB
    route[Route by task&lt;br/&gt;Haiku / Sonnet / Opus] --&gt; cb[Circuit breakers&lt;br/&gt;Anthropic → Azure&lt;br/&gt;OpenAI → Ollama]
    cb --&gt; scan[Scan response for&lt;br/&gt;new PII, restore&lt;br/&gt;placeholders]
    scan --&gt; audit[(Audit: TimescaleDB&lt;br/&gt;metrics: Prometheus)]
    audit --&gt; done([Job complete:&lt;br/&gt;client polls result])
  end
  intake -- "not restricted" --&gt; guard
  guard -- "within budget" --&gt; record
</code></pre>

<h2 id="provider-agnosticism-the-foundation">Provider Agnosticism: The Foundation</h2>

<p>The first design decision I made was to make Aegis completely provider-agnostic. Instead of building around a single LLM provider, I created an abstraction layer that could work with any provider—Anthropic, Azure OpenAI, Ollama, or even future ones.</p>

<p>I implemented this through a <code class="language-plaintext highlighter-rouge">LLMProvider</code> abstract base class and a <code class="language-plaintext highlighter-rouge">ProviderFactory</code> that instantiates the right provider based on a string name. This meant that switching providers or adding new ones required only configuration changes, not code changes.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">LLMProvider</span><span class="p">(</span><span class="n">ABC</span><span class="p">):</span>
    <span class="nd">@abstractmethod</span>
    <span class="k">async</span> <span class="k">def</span> <span class="nf">complete</span><span class="p">(</span><span class="n">self</span><span class="p">,</span> <span class="n">prompt</span><span class="p">:</span> <span class="nb">str</span><span class="p">,</span> <span class="n">model_id</span><span class="p">:</span> <span class="nb">str</span><span class="p">,</span> <span class="n">max_tokens</span><span class="p">:</span> <span class="nb">int</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="nb">str</span><span class="p">:</span>
        <span class="k">pass</span>
    
    <span class="nd">@abstractmethod</span>
    <span class="k">async</span> <span class="k">def</span> <span class="nf">health_check</span><span class="p">(</span><span class="n">self</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="nb">bool</span><span class="p">:</span>
        <span class="k">pass</span>
</code></pre></div></div>

<p>The tradeoff here was complexity—I had to implement and maintain multiple provider integrations. But the benefit was enormous: organizations could start with whatever provider they had access to, and migrate seamlessly later. It also made testing easier, since I could mock providers or use local Ollama for development.</p>

<h2 id="data-classification-the-1ms-decision">Data Classification: The &lt;1ms Decision</h2>

<p>One of the most critical components is the data classifier. Every request goes through this before anything else happens. I chose regex-based classification because it had to be fast—sub-millisecond fast—and deterministic. No machine learning models in the hot path.</p>

<p>The classifier looks for patterns that indicate data sensitivity:</p>

<ul>
  <li><strong>RESTRICTED</strong>: Canadian SIN numbers, credit cards, account numbers</li>
  <li><strong>CONFIDENTIAL</strong>: API keys, bearer tokens, internal email addresses</li>
  <li><strong>INTERNAL</strong>: Default for unclassified data</li>
  <li><strong>PUBLIC</strong>: Explicitly marked public content</li>
</ul>

<p>I implemented this as a compiled regex engine that runs in about 0.2ms on average. The tradeoff was that it might miss some edge cases that a more sophisticated classifier would catch, but the speed and predictability were worth it. False negatives are the real risk: anything the patterns miss falls through to INTERNAL, which is allowed to reach a cloud provider. That’s why the classifier isn’t the only line of defense; PII masking (below) runs independently on everything bound for the cloud.</p>

<h2 id="pipeda-compliance-the-hard-invariant">PIPEDA Compliance: The Hard Invariant</h2>

<p>The most important design constraint was Canadian privacy law compliance under PIPEDA. The rule I chose to meet it is strict: RESTRICTED data must never leave the local network. I didn’t want this to be a configuration option—I wanted it to be a code invariant that couldn’t be accidentally disabled.</p>

<p>I enforced this at four independent layers:</p>

<ol>
  <li><strong>Routing logic</strong>: The <code class="language-plaintext highlighter-rouge">ModelRouter.route()</code> method immediately returns local Ollama for any RESTRICTED classification</li>
  <li><strong>Runtime monitoring</strong>: A Prometheus counter tracks violations and alerts if it ever goes above zero</li>
  <li><strong>Database auditing</strong>: A view queries for violations and must always return zero rows</li>
  <li><strong>Automated testing</strong>: CI fails if the invariant is broken</li>
</ol>

<p>The tradeoff was that RESTRICTED data is always processed locally, which might be slower than cloud providers. But compliance wasn’t negotiable—better to be slower and compliant than fast and in violation of privacy laws.</p>

<h2 id="pii-protection-mask-before-send">PII Protection: Mask Before Send</h2>

<p>Even for data that can go to cloud providers, I wanted to protect personally identifiable information. I integrated Microsoft Presidio for entity recognition, but added custom patterns for Canadian SIN numbers.</p>

<p>The flow is: detect PII → replace with typed placeholders → send to LLM → scan response for hallucinations → restore original entities.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Example: "John Doe's SIN is 123-456-789" 
# becomes: "PERSON_0's SIN is CA_SIN_0"
</span></code></pre></div></div>

<p>The challenge was handling hallucinations—LLMs sometimes invent PII in their responses. I added a post-processing step that scans all responses and alerts if new PII appears.</p>

<p>The tradeoff was latency—PII masking adds about 1ms to each request. But the security benefit was worth it, especially since the system can be configured to block requests with detected PII.</p>

<h2 id="smart-routing-cost-optimization-through-intelligence">Smart Routing: Cost Optimization Through Intelligence</h2>

<p>One of the biggest wins was intelligent model routing. Instead of letting developers choose models, I created a router that selects the right model based on task type, data classification, and budget constraints.</p>

<p>The router uses a simple mapping:</p>

<ul>
  <li>Simple tasks (commit summaries, routing): Haiku (fast and cheap)</li>
  <li>Medium complexity (code reviews, RAG): Sonnet (balanced)</li>
  <li>Complex reasoning (security audits): Opus (maximum capability)</li>
</ul>

<p>It also does budget-aware degradation—if a team’s budget drops below $1, Opus requests automatically downgrade to Sonnet.</p>

<p>I considered using ML for routing, but decided against it because I wanted deterministic behavior and easy debugging. The current rules-based approach is transparent and testable.</p>

<p>The tradeoff was that the routing might not be as nuanced as an ML model could be, but it was predictable and required no training data.</p>

<h2 id="async-job-model-scalability-through-decoupling">Async Job Model: Scalability Through Decoupling</h2>

<p>I chose an asynchronous job model for inference requests. Clients submit a request, get a job ID immediately, then poll for completion. This was crucial for handling variable LLM latencies and preventing timeouts.</p>

<p>The async model also enabled better resource utilization—I could queue requests and process them as providers became available.</p>

<p>The downside was added complexity for clients, who now had to implement polling logic. I mitigated this by providing SDKs with built-in polling helpers.</p>

<h2 id="rag-pipeline-classification-aware-retrieval">RAG Pipeline: Classification-Aware Retrieval</h2>

<p>For retrieval-augmented generation, I built a pipeline that respects data classifications. Documents are chunked, embedded, and stored in pgvector with classification metadata.</p>

<p>The key insight was routing embeddings based on data sensitivity:</p>

<ul>
  <li>RESTRICTED/CONFIDENTIAL: Always use local Ollama embeddings (768 dimensions)</li>
  <li>INTERNAL/PUBLIC: Can use cloud embeddings if available</li>
</ul>

<p>Retrieval queries can only access chunks at their classification level or lower. A PUBLIC query can’t see INTERNAL chunks.</p>

<p>I chose pgvector over more specialized vector databases because it integrated well with the existing PostgreSQL/TimescaleDB setup. The tradeoff was that it might not scale as well as dedicated vector databases, but for enterprise use cases, it was sufficient.</p>

<h2 id="observability-metrics-first">Observability: Metrics First</h2>

<p>From the beginning, I designed observability into the system rather than adding it later. Every component emits Prometheus metrics, and I pre-built Grafana dashboards.</p>

<p>Key metrics include request counts by team/provider/model, costs, latencies, and the critical compliance counter.</p>

<p>I also implemented comprehensive audit logging to TimescaleDB, partitioned by time for efficient querying.</p>

<p>The tradeoff was development overhead—adding metrics to every code path. But the debugging benefits were immense, especially in production.</p>

<h2 id="circuit-breakers-and-health-checks">Circuit Breakers and Health Checks</h2>

<p>Provider failures are inevitable, so I implemented circuit breakers that automatically fail over to healthy providers. After three consecutive failures, a provider is marked unhealthy for 60 seconds.</p>

<p>The fallback chain is: Anthropic → Azure OpenAI → Ollama (always available as final fallback).</p>

<p>This made the system resilient but added complexity in testing all failure scenarios.</p>

<h2 id="budget-enforcement-pre-flight-checks">Budget Enforcement: Pre-Flight Checks</h2>

<p>To prevent cost overruns, I added per-team monthly budget caps with pre-flight cost estimation. Requests that would exceed the budget are rejected before any LLM processing occurs.</p>

<p>The system tracks spend in real-time and provides visibility through Prometheus gauges.</p>

<p>The challenge was accurate cost estimation, since actual costs depend on token counts. I solved this with conservative estimates and post-processing reconciliation.</p>

<h2 id="docker-native-development">Docker-Native Development</h2>

<p>I made the entire development environment Docker-based—no host Python or Node installations required. This was crucial for consistency across development machines and CI/CD.</p>

<p>The tradeoff was slower builds and more complex debugging, but the reproducibility benefits outweighed these costs.</p>

<h2 id="the-scaling-path">The Scaling Path</h2>

<p>One of the design principles was to make scaling infrastructure-only, not requiring code changes. The system can scale from a single Docker Compose setup to Kubernetes replicas by just adding more containers.</p>

<p>For GPU acceleration, I designed the router to support vLLM as a tier 2 provider, which can be enabled by uncommenting configuration.</p>

<h2 id="tradeoffs-and-lessons-learned">Tradeoffs and Lessons Learned</h2>

<p>Building Aegis taught me that enterprise software requires balancing technical excellence with operational constraints. The biggest tradeoff was speed vs. security, every protection layer added latency, but compliance requirements made them non-negotiable.</p>

<p>I also learned that deterministic systems are easier to operate than probabilistic ones. While ML could have made some components smarter, the debugging and compliance benefits of rules-based logic were worth the tradeoffs.</p>

<p>The async job model was the decision I went back and forth on most—a synchronous API is simpler for every client—but polling is what lets slow models and queued requests coexist without timeouts.</p>

<h2 id="looking-forward">Looking Forward</h2>

<p>Aegis shows that you can build enterprise-grade AI infrastructure without sacrificing developer experience. The provider-agnostic design means it can evolve with the AI landscape, and the strong compliance foundations give organizations confidence to adopt AI more broadly.</p>

<p>The next challenges will be around multi-modal inputs, more sophisticated routing algorithms, and integration with existing enterprise identity systems. But the core architecture—governance through abstraction, compliance through invariants, and optimization through intelligence will remain the same.</p>]]></content><author><name>Echo Yin</name></author><category term="ai" /><category term="ai" /><category term="python" /><category term="llm" /><category term="enterprise" /><category term="infrastructure" /><category term="security" /><category term="compliance" /><category term="pipeda" /><summary type="html"><![CDATA[How to build an enterprise-grade AI gateway: a provider-agnostic LLM routing layer with deterministic compliance, PII protection, and intelligent cost optimization.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://e-choness.github.io/portfolio-site/assets/images/blogs/aegis-gateway.webp" /><media:content medium="image" url="https://e-choness.github.io/portfolio-site/assets/images/blogs/aegis-gateway.webp" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Chapter 1.11 - Docker Swarm: From One Host to a Cluster</title><link href="https://e-choness.github.io/portfolio-site/blog/2025/07/17/chapter-1-11-docker-swarm/" rel="alternate" type="text/html" title="Chapter 1.11 - Docker Swarm: From One Host to a Cluster" /><published>2025-07-17T00:00:00+00:00</published><updated>2025-07-17T00:00:00+00:00</updated><id>https://e-choness.github.io/portfolio-site/blog/2025/07/17/chapter-1-11-docker-swarm</id><content type="html" xml:base="https://e-choness.github.io/portfolio-site/blog/2025/07/17/chapter-1-11-docker-swarm/"><![CDATA[<p>Compose runs an application on <strong>one</strong> host. When that host needs maintenance, or one machine isn’t enough, you want a cluster: several hosts acting as one, placing containers wherever there’s room and replacing them when a machine dies.</p>

<p><strong>Swarm mode</strong> is the orchestrator built into Docker Engine. There’s nothing extra to install, it reads the same Compose file format, and a working cluster takes about three commands. It’s far simpler than Kubernetes; you give up Kubernetes’ enormous ecosystem in exchange. For small and medium setups that’s often the right trade.</p>

<h2 id="the-concepts">The concepts</h2>

<h3 id="nodes-managers-and-workers">Nodes: managers and workers</h3>

<p>Every Docker host in a swarm is a <strong>node</strong>.</p>

<ul>
  <li><strong>Managers</strong> hold the cluster state and schedule work. They replicate that state among themselves with the <strong>Raft</strong> consensus protocol, and one of them is the elected <strong>leader</strong>.</li>
  <li><strong>Workers</strong> just run containers. By default, managers run containers too.</li>
</ul>

<pre><code class="language-mermaid">flowchart TB
  subgraph M["Managers: Raft replicated state"]
    direction LR
    M1["manager-1&lt;br/&gt;(leader)"] &lt;--&gt; M2[manager-2]
    M2 &lt;--&gt; M3[manager-3]
    M1 &lt;--&gt; M3
  end
  M1 -- "schedules tasks" --&gt; W1[worker-1]
  M1 --&gt; W2[worker-2]
  M1 --&gt; W3[worker-3]
</code></pre>

<p>Raft needs a <strong>majority</strong> of managers to agree on any change, which gives the rule for how many to run:</p>

<table>
  <thead>
    <tr>
      <th>Managers</th>
      <th>Can lose</th>
      <th>Notes</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>0</td>
      <td>fine for a lab; the cluster can’t change while it’s down</td>
    </tr>
    <tr>
      <td>3</td>
      <td>1</td>
      <td>the usual production choice</td>
    </tr>
    <tr>
      <td>5</td>
      <td>2</td>
      <td>larger clusters</td>
    </tr>
  </tbody>
</table>

<p>Always use an <strong>odd</strong> number: 4 managers tolerate no more failures than 3, and give you one more machine that can break. If a majority is lost, running containers keep running, but nothing can be scheduled or changed until quorum returns.</p>

<h3 id="services-and-tasks">Services and tasks</h3>

<p>You don’t start containers in a swarm; you declare a <strong>service</strong> (“run 3 replicas of <code class="language-plaintext highlighter-rouge">nginx:1.27</code>, published on port 80”), and the managers make it true. Each replica is a <strong>task</strong>, and each task runs one container on some node. If a node dies, its tasks are rescheduled elsewhere to get back to 3.</p>

<ul>
  <li><strong>Replicated</strong> services run a set number of tasks wherever there’s capacity.</li>
  <li><strong>Global</strong> services run exactly one task on <strong>every</strong> node (managers included, unless constrained), which suits monitoring agents and log shippers.</li>
</ul>

<h2 id="1-build-a-lab-cluster">1. Build a lab cluster</h2>

<p>Three VMs with Docker, using the cloud-init file from <a href="/portfolio-site/blog/2025/07/16/chapter-1-10-docker-machine/">Chapter 1.10</a>:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">for </span>n <span class="k">in </span>manager worker-1 worker-2<span class="p">;</span> <span class="k">do
  </span>multipass launch <span class="nt">--name</span> <span class="s2">"</span><span class="nv">$n</span><span class="s2">"</span> <span class="nt">--cpus</span> 2 <span class="nt">--memory</span> 2G <span class="nt">--disk</span> 10G <span class="nt">--cloud-init</span> docker.yaml
<span class="k">done
</span>multipass list          <span class="c"># note each VM's IPv4 address</span>
</code></pre></div></div>

<p>Nodes talk to each other on three ports, which must be open between them (not to the internet):</p>

<table>
  <thead>
    <tr>
      <th>Port</th>
      <th>Protocol</th>
      <th>Used for</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>2377</td>
      <td>TCP</td>
      <td>cluster management (joining, Raft)</td>
    </tr>
    <tr>
      <td>7946</td>
      <td>TCP + UDP</td>
      <td>node-to-node gossip, discovering who’s alive</td>
    </tr>
    <tr>
      <td>4789</td>
      <td>UDP</td>
      <td>overlay network traffic (VXLAN)</td>
    </tr>
  </tbody>
</table>

<h3 id="initialize-and-join">Initialize and join</h3>

<p>On the manager:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>multipass <span class="nb">exec </span>manager <span class="nt">--</span> docker swarm init <span class="nt">--advertise-addr</span> 192.168.64.10
</code></pre></div></div>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">swarm init</code></strong>: turn this Engine into a single-node swarm, with itself as the leader.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">--advertise-addr</code></strong>: the address other nodes should use to reach this manager. Always set it on machines with more than one network interface, or Swarm may advertise the wrong one.</li>
</ul>

<p>The output contains a ready-made join command with a secret <strong>token</strong>. Run it on each worker:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>multipass <span class="nb">exec </span>worker-1 <span class="nt">--</span> docker swarm <span class="nb">join</span> <span class="nt">--token</span> SWMTKN-1-3xqa… 192.168.64.10:2377
multipass <span class="nb">exec </span>worker-2 <span class="nt">--</span> docker swarm <span class="nb">join</span> <span class="nt">--token</span> SWMTKN-1-3xqa… 192.168.64.10:2377
</code></pre></div></div>

<p>Lost the command? <code class="language-plaintext highlighter-rouge">docker swarm join-token worker</code> prints it again (<code class="language-plaintext highlighter-rouge">join-token manager</code> for adding managers). Treat these tokens like passwords: anyone holding one can join a machine to your cluster.</p>

<p>From here on, run commands against the manager. A Docker context saves typing <code class="language-plaintext highlighter-rouge">multipass exec</code> every time:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker context create swarm <span class="nt">--docker</span> <span class="s2">"host=ssh://deploy@192.168.64.10"</span>
docker context use swarm
docker node <span class="nb">ls</span>
</code></pre></div></div>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>ID                            HOSTNAME   STATUS   AVAILABILITY   MANAGER STATUS   ENGINE VERSION
p1l3k9…      *                manager    Ready    Active         Leader           27.3.1
a8d2x7…                       worker-1   Ready    Active                          27.3.1
q0m5c1…                       worker-2   Ready    Active                          27.3.1
</code></pre></div></div>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">STATUS Ready</code></strong>: the node is reachable and healthy.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">AVAILABILITY Active</code></strong>: it accepts new tasks. <code class="language-plaintext highlighter-rouge">Drain</code> means it’s being emptied for maintenance.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">MANAGER STATUS</code></strong>: <code class="language-plaintext highlighter-rouge">Leader</code>, <code class="language-plaintext highlighter-rouge">Reachable</code> (another manager), or blank for workers.</li>
</ul>

<h2 id="2-run-a-service">2. Run a service</h2>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker service create <span class="nt">--name</span> web <span class="nt">--replicas</span> 3 <span class="nt">-p</span> 80:80 nginx:1.27
docker service <span class="nb">ls
</span>docker service ps web
</code></pre></div></div>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>ID       NAME    IMAGE        NODE       DESIRED STATE   CURRENT STATE
x1…      web.1   nginx:1.27   worker-1   Running         Running 20 seconds ago
x2…      web.2   nginx:1.27   worker-2   Running         Running 20 seconds ago
x3…      web.3   nginx:1.27   manager    Running         Running 20 seconds ago
</code></pre></div></div>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">--replicas 3</code></strong>: the desired state. Swarm spreads the tasks across nodes.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">-p 80:80</code></strong>: publish through the <strong>routing mesh</strong>. <em>Every</em> node now listens on port 80, including nodes running no <code class="language-plaintext highlighter-rouge">web</code> task, and forwards each connection to a healthy task anywhere in the cluster. Point a load balancer or DNS at all nodes, and any of them can take traffic.</li>
</ul>

<pre><code class="language-mermaid">flowchart LR
  c([Client]) --&gt; n1[worker-1 :80]
  c --&gt; n2[worker-2 :80]
  c --&gt; n3[manager :80]
  subgraph mesh["Routing mesh (ingress network)"]
    n1 &amp; n2 &amp; n3 --&gt; vip(["service VIP&lt;br/&gt;load-balances"])
  end
  vip --&gt; t1[web.1]
  vip --&gt; t2[web.2]
  vip --&gt; t3[web.3]
</code></pre>

<h3 id="scaling-updating-rolling-back">Scaling, updating, rolling back</h3>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker service scale <span class="nv">web</span><span class="o">=</span>5

docker service update <span class="se">\</span>
  <span class="nt">--image</span> nginx:1.27.2 <span class="se">\</span>
  <span class="nt">--update-parallelism</span> 1 <span class="se">\</span>
  <span class="nt">--update-delay</span> 10s <span class="se">\</span>
  <span class="nt">--update-failure-action</span> rollback <span class="se">\</span>
  web

docker service rollback web
docker service logs <span class="nt">-f</span> web
</code></pre></div></div>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">scale web=5</code></strong>: change the desired count; Swarm adds or removes tasks to match.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">service update --image</code></strong>: a <strong>rolling update</strong>. With <code class="language-plaintext highlighter-rouge">--update-parallelism 1</code> and <code class="language-plaintext highlighter-rouge">--update-delay 10s</code>, it replaces one task, waits 10 seconds, then moves to the next, so most replicas keep serving throughout.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">--update-failure-action rollback</code></strong>: if new tasks fail to start, Swarm automatically goes back to the previous version.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">service rollback</code></strong>: the manual version, which returns to the service’s previous definition.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">service logs</code></strong>: the logs of every task, from whichever node each runs on, in one stream.</li>
</ul>

<p>Take a node out for maintenance by draining it: Swarm moves its tasks elsewhere, and <code class="language-plaintext highlighter-rouge">active</code> brings it back:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker node update <span class="nt">--availability</span> drain worker-1
docker node update <span class="nt">--availability</span> active worker-1
</code></pre></div></div>

<h2 id="3-deploy-a-whole-application-as-a-stack">3. Deploy a whole application as a stack</h2>

<p>A <strong>stack</strong> is a Compose file deployed to a swarm. Here’s the proxy/API/Redis project from <a href="/portfolio-site/blog/2025/07/16/chapter-1-9-docker-compose/">Chapter 1.9</a>, adapted for a cluster, as <code class="language-plaintext highlighter-rouge">stack.yml</code>:</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">services</span><span class="pi">:</span>
  <span class="na">proxy</span><span class="pi">:</span>
    <span class="na">image</span><span class="pi">:</span> <span class="s">nginx:1.27</span>
    <span class="na">ports</span><span class="pi">:</span>
      <span class="pi">-</span> <span class="s2">"</span><span class="s">80:80"</span>
    <span class="na">configs</span><span class="pi">:</span>
      <span class="pi">-</span> <span class="na">source</span><span class="pi">:</span> <span class="s">nginx_conf</span>
        <span class="na">target</span><span class="pi">:</span> <span class="s">/etc/nginx/conf.d/default.conf</span>
    <span class="na">deploy</span><span class="pi">:</span>
      <span class="na">replicas</span><span class="pi">:</span> <span class="m">2</span>

  <span class="na">api</span><span class="pi">:</span>
    <span class="na">image</span><span class="pi">:</span> <span class="s">yourname/shop-api:1.0</span>
    <span class="na">environment</span><span class="pi">:</span>
      <span class="na">REDIS_URL</span><span class="pi">:</span> <span class="s">redis://redis:6379</span>
    <span class="na">deploy</span><span class="pi">:</span>
      <span class="na">replicas</span><span class="pi">:</span> <span class="m">3</span>
      <span class="na">update_config</span><span class="pi">:</span>
        <span class="na">parallelism</span><span class="pi">:</span> <span class="m">1</span>
        <span class="na">delay</span><span class="pi">:</span> <span class="s">10s</span>
        <span class="na">order</span><span class="pi">:</span> <span class="s">start-first</span>
        <span class="na">failure_action</span><span class="pi">:</span> <span class="s">rollback</span>
      <span class="na">restart_policy</span><span class="pi">:</span>
        <span class="na">condition</span><span class="pi">:</span> <span class="s">on-failure</span>

  <span class="na">redis</span><span class="pi">:</span>
    <span class="na">image</span><span class="pi">:</span> <span class="s">redis:8.0</span>
    <span class="na">command</span><span class="pi">:</span> <span class="pi">[</span><span class="s2">"</span><span class="s">redis-server"</span><span class="pi">,</span> <span class="s2">"</span><span class="s">--appendonly"</span><span class="pi">,</span> <span class="s2">"</span><span class="s">yes"</span><span class="pi">]</span>
    <span class="na">volumes</span><span class="pi">:</span>
      <span class="pi">-</span> <span class="s">redis-data:/data</span>
    <span class="na">deploy</span><span class="pi">:</span>
      <span class="na">placement</span><span class="pi">:</span>
        <span class="na">constraints</span><span class="pi">:</span>
          <span class="pi">-</span> <span class="s">node.labels.redis == </span><span class="kc">true</span>

<span class="na">configs</span><span class="pi">:</span>
  <span class="na">nginx_conf</span><span class="pi">:</span>
    <span class="na">file</span><span class="pi">:</span> <span class="s">./nginx/default.conf</span>

<span class="na">volumes</span><span class="pi">:</span>
  <span class="na">redis-data</span><span class="pi">:</span>
</code></pre></div></div>

<p>What’s different from the Compose version, and why:</p>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">image: yourname/shop-api:1.0</code> instead of <code class="language-plaintext highlighter-rouge">build: .</code></strong>: Swarm doesn’t build. Every node pulls images from a registry, so build and push first: <code class="language-plaintext highlighter-rouge">docker build -t yourname/shop-api:1.0 . &amp;&amp; docker push yourname/shop-api:1.0</code>.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">configs:</code> instead of a bind mount for <code class="language-plaintext highlighter-rouge">default.conf</code></strong>: a bind mount points at a file on <em>whichever node</em> the task lands on, and the file won’t be there. A <strong>config</strong> is stored in the cluster (in the managers’ Raft store) and delivered into the container on any node. It’s read-only and meant for non-secret files.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">deploy:</code></strong>: Swarm-only settings (plain <code class="language-plaintext highlighter-rouge">docker compose up</code> ignores most of them):
    <ul>
      <li><code class="language-plaintext highlighter-rouge">replicas</code>: how many tasks.</li>
      <li><code class="language-plaintext highlighter-rouge">update_config</code>: the rolling-update behaviour from section 2, per service. <code class="language-plaintext highlighter-rouge">order: start-first</code> starts the new task <em>before</em> stopping the old one, so capacity never dips during an update.</li>
      <li><code class="language-plaintext highlighter-rouge">restart_policy: condition: on-failure</code>: restart a task that exits with an error. (The valid values are <code class="language-plaintext highlighter-rouge">none</code>, <code class="language-plaintext highlighter-rouge">on-failure</code> and <code class="language-plaintext highlighter-rouge">any</code>, with a hyphen.)</li>
      <li><code class="language-plaintext highlighter-rouge">placement.constraints</code>: only schedule <code class="language-plaintext highlighter-rouge">redis</code> on nodes with the label <code class="language-plaintext highlighter-rouge">redis=true</code>.</li>
    </ul>
  </li>
  <li><strong>No <code class="language-plaintext highlighter-rouge">depends_on</code> with conditions</strong>: Swarm starts services independently and restarts failing tasks until their dependencies are up. That’s why the app from Chapter 1.9 waits for its Redis connection before listening.</li>
  <li><strong>Service discovery by VIP</strong>: in a stack, <code class="language-plaintext highlighter-rouge">api</code> resolves to a single <strong>virtual IP</strong> that load-balances across all <code class="language-plaintext highlighter-rouge">api</code> tasks. Unlike the Compose setup, Nginx doesn’t need a reload after scaling.</li>
</ul>

<h3 id="stateful-services-need-a-home">Stateful services need a home</h3>

<p>The <code class="language-plaintext highlighter-rouge">redis-data</code> volume is created on <strong>the node where the task runs</strong>; volumes don’t move between nodes. If <code class="language-plaintext highlighter-rouge">redis</code> were rescheduled to another node, it would start with an empty volume there. That’s why it’s pinned: label the one node that should hold the data.</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker node update <span class="nt">--label-add</span> <span class="nv">redis</span><span class="o">=</span><span class="nb">true </span>worker-2
</code></pre></div></div>

<p>For real persistence across node failures, either run the database outside the swarm (a managed service, or a dedicated host) or use a volume driver backed by shared or replicated storage.</p>

<h3 id="deploy-it">Deploy it</h3>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker stack deploy <span class="nt">-c</span> stack.yml shop
docker stack services shop
docker stack ps shop
</code></pre></div></div>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">stack deploy -c stack.yml shop</code></strong>: create or update everything in the file, named with the <code class="language-plaintext highlighter-rouge">shop_</code> prefix (<code class="language-plaintext highlighter-rouge">shop_api</code>, <code class="language-plaintext highlighter-rouge">shop_redis</code>). It also creates an <strong>overlay network</strong>, <code class="language-plaintext highlighter-rouge">shop_default</code>, spanning every node, so tasks reach each other by service name across machines.</li>
  <li><strong>Re-running the same command</strong> after editing the file applies the changes, using each service’s <code class="language-plaintext highlighter-rouge">update_config</code>.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">stack services</code></strong> shows replica counts per service; <strong><code class="language-plaintext highlighter-rouge">stack ps</code></strong> shows every task and its node.</li>
</ul>

<h2 id="4-secrets">4. Secrets</h2>

<p>Passwords shouldn’t live in stack files or environment variables, which show up in <code class="language-plaintext highlighter-rouge">docker inspect</code>. Swarm secrets are encrypted in the managers’ store and mounted as files, in memory, only into the services that ask for them:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>openssl rand <span class="nt">-base64</span> 32 | docker secret create redis_password -
</code></pre></div></div>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">services</span><span class="pi">:</span>
  <span class="na">redis</span><span class="pi">:</span>
    <span class="na">image</span><span class="pi">:</span> <span class="s">redis:8.0</span>
    <span class="na">command</span><span class="pi">:</span> <span class="pi">[</span><span class="s2">"</span><span class="s">sh"</span><span class="pi">,</span> <span class="s2">"</span><span class="s">-c"</span><span class="pi">,</span> <span class="s2">"</span><span class="s">exec</span><span class="nv"> </span><span class="s">redis-server</span><span class="nv"> </span><span class="s">--appendonly</span><span class="nv"> </span><span class="s">yes</span><span class="nv"> </span><span class="s">--requirepass</span><span class="nv"> </span><span class="se">\"</span><span class="s">$$(cat</span><span class="nv"> </span><span class="s">/run/secrets/redis_password)</span><span class="se">\"</span><span class="s">"</span><span class="pi">]</span>
    <span class="na">secrets</span><span class="pi">:</span>
      <span class="pi">-</span> <span class="s">redis_password</span>

<span class="na">secrets</span><span class="pi">:</span>
  <span class="na">redis_password</span><span class="pi">:</span>
    <span class="na">external</span><span class="pi">:</span> <span class="kc">true</span>
</code></pre></div></div>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">docker secret create redis_password -</code></strong>: create a secret from standard input (the <code class="language-plaintext highlighter-rouge">-</code>), so it never touches disk or your shell history.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">secrets:</code> on the service</strong>: the secret appears in the container as the file <code class="language-plaintext highlighter-rouge">/run/secrets/redis_password</code>.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">$$(cat …)</code></strong>: <code class="language-plaintext highlighter-rouge">$$</code> escapes the <code class="language-plaintext highlighter-rouge">$</code> from Compose’s own variable substitution, so the container’s shell sees <code class="language-plaintext highlighter-rouge">$(cat …)</code> and reads the file at startup.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">external: true</code></strong>: the secret already exists in the cluster; the stack file only references it.</li>
</ul>

<p>The <code class="language-plaintext highlighter-rouge">api</code> service then needs the same secret: add <code class="language-plaintext highlighter-rouge">secrets: [redis_password]</code> to it and have the app read <code class="language-plaintext highlighter-rouge">/run/secrets/redis_password</code> when it builds its Redis URL. Many official images read secrets from files directly through <code class="language-plaintext highlighter-rouge">*_FILE</code> variables, for example <code class="language-plaintext highlighter-rouge">MYSQL_ROOT_PASSWORD_FILE=/run/secrets/mysql_root</code>.</p>

<h2 id="5-tearing-down">5. Tearing down</h2>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker stack <span class="nb">rm </span>shop              <span class="c"># services, networks and configs</span>
docker volume <span class="nb">ls</span>                  <span class="c"># volumes remain, on each node where they were created</span>
docker swarm leave                <span class="c"># on a worker; add --force on the last manager</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">stack rm</code> deliberately leaves volumes alone. Remove them per node with <code class="language-plaintext highlighter-rouge">docker volume rm shop_redis-data</code> once you’re sure.</p>

<h2 id="troubleshooting">Troubleshooting</h2>

<table>
  <thead>
    <tr>
      <th>Symptom</th>
      <th>Check</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Tasks stuck in <code class="language-plaintext highlighter-rouge">Pending</code></td>
      <td>No node satisfies the constraints or has enough resources: <code class="language-plaintext highlighter-rouge">docker service ps --no-trunc &lt;service&gt;</code> shows the reason.</td>
    </tr>
    <tr>
      <td>Tasks stuck in <code class="language-plaintext highlighter-rouge">Preparing</code> / pull errors</td>
      <td>Workers can’t pull the image: registry login (<code class="language-plaintext highlighter-rouge">--with-registry-auth</code> on deploy) or the image doesn’t exist.</td>
    </tr>
    <tr>
      <td>Published port unreachable on some nodes</td>
      <td>Ports 7946 and 4789 blocked between nodes, so the routing mesh can’t forward.</td>
    </tr>
    <tr>
      <td>Data “disappeared” after a restart</td>
      <td>The task moved to another node with its own empty volume; add a placement constraint.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">The swarm does not have a leader</code></td>
      <td>Majority of managers lost; restore them, or rebuild from one with <code class="language-plaintext highlighter-rouge">docker swarm init --force-new-cluster</code>.</td>
    </tr>
  </tbody>
</table>

<p><a href="/portfolio-site/blog/2025/07/17/chapter-1-12-docker-multistage/">Chapter 1.12</a> closes the chapter by shrinking the images all these nodes pull: multi-stage builds.</p>]]></content><author><name>Echo Yin</name></author><category term="devops" /><category term="Platform Engineering" /><category term="DevOps" /><category term="Chapter One" /><category term="Docker" /><summary type="html"><![CDATA[Join three machines into a Docker Swarm cluster, run replicated services behind the routing mesh, and deploy the Compose project from the previous chapters as a stack, with rolling updates, automatic rollback, configs, secrets and the rules for stateful services. Every command and stack key is explained.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://e-choness.github.io/portfolio-site/assets/images/blogs/docker-swarm.webp" /><media:content medium="image" url="https://e-choness.github.io/portfolio-site/assets/images/blogs/docker-swarm.webp" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Chapter 1.12 - Multi-Stage Builds: From a 1.3 GB Image to 7 MB</title><link href="https://e-choness.github.io/portfolio-site/blog/2025/07/17/chapter-1-12-docker-multistage/" rel="alternate" type="text/html" title="Chapter 1.12 - Multi-Stage Builds: From a 1.3 GB Image to 7 MB" /><published>2025-07-17T00:00:00+00:00</published><updated>2025-07-17T00:00:00+00:00</updated><id>https://e-choness.github.io/portfolio-site/blog/2025/07/17/chapter-1-12-docker-multistage</id><content type="html" xml:base="https://e-choness.github.io/portfolio-site/blog/2025/07/17/chapter-1-12-docker-multistage/"><![CDATA[<p>The obvious Dockerfile for a compiled program starts from the language’s official image, copies the source, builds, and runs. It works, and it ships everything: the compiler, the package cache, the source code, a full Debian userland. None of it is needed at run time, all of it has to be pulled onto every server, and every package in it is something a vulnerability scanner will flag.</p>

<p><strong>Multi-stage builds</strong> fix this inside a single Dockerfile: one stage has the full toolchain and builds the program; the final stage starts from something tiny and copies in only the finished binary.</p>

<h2 id="the-starting-point">The starting point</h2>

<p>A small Go service, <code class="language-plaintext highlighter-rouge">main.go</code>, using only the standard library:</p>

<div class="language-go highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">package</span> <span class="n">main</span>

<span class="k">import</span> <span class="p">(</span>
	<span class="s">"fmt"</span>
	<span class="s">"log"</span>
	<span class="s">"net/http"</span>
	<span class="s">"os"</span>
<span class="p">)</span>

<span class="k">func</span> <span class="n">main</span><span class="p">()</span> <span class="p">{</span>
	<span class="n">http</span><span class="o">.</span><span class="n">HandleFunc</span><span class="p">(</span><span class="s">"/ping"</span><span class="p">,</span> <span class="k">func</span><span class="p">(</span><span class="n">w</span> <span class="n">http</span><span class="o">.</span><span class="n">ResponseWriter</span><span class="p">,</span> <span class="n">r</span> <span class="o">*</span><span class="n">http</span><span class="o">.</span><span class="n">Request</span><span class="p">)</span> <span class="p">{</span>
		<span class="n">fmt</span><span class="o">.</span><span class="n">Fprintln</span><span class="p">(</span><span class="n">w</span><span class="p">,</span> <span class="s">"pong"</span><span class="p">)</span>
	<span class="p">})</span>

	<span class="n">port</span> <span class="o">:=</span> <span class="n">os</span><span class="o">.</span><span class="n">Getenv</span><span class="p">(</span><span class="s">"PORT"</span><span class="p">)</span>
	<span class="k">if</span> <span class="n">port</span> <span class="o">==</span> <span class="s">""</span> <span class="p">{</span>
		<span class="n">port</span> <span class="o">=</span> <span class="s">"8080"</span>
	<span class="p">}</span>
	<span class="n">log</span><span class="o">.</span><span class="n">Printf</span><span class="p">(</span><span class="s">"listening on :%s"</span><span class="p">,</span> <span class="n">port</span><span class="p">)</span>
	<span class="n">log</span><span class="o">.</span><span class="n">Fatal</span><span class="p">(</span><span class="n">http</span><span class="o">.</span><span class="n">ListenAndServe</span><span class="p">(</span><span class="s">":"</span><span class="o">+</span><span class="n">port</span><span class="p">,</span> <span class="no">nil</span><span class="p">))</span>
<span class="p">}</span>
</code></pre></div></div>

<p>and a <code class="language-plaintext highlighter-rouge">go.mod</code>:</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>module example.com/pingsvc

go 1.22
</code></pre></div></div>

<p>The naive Dockerfile:</p>

<div class="language-dockerfile highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">FROM</span><span class="s"> golang:1.22</span>
<span class="k">WORKDIR</span><span class="s"> /src</span>
<span class="k">COPY</span><span class="s"> . .</span>
<span class="k">RUN </span>go build <span class="nt">-o</span> /usr/local/bin/pingsvc .
<span class="k">CMD</span><span class="s"> ["pingsvc"]</span>
</code></pre></div></div>

<p>Built on my machine, that image is <strong>1.31 GB</strong>, for a program whose binary is a few megabytes.</p>

<h2 id="the-multi-stage-version">The multi-stage version</h2>

<div class="language-dockerfile highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># syntax=docker/dockerfile:1</span>

<span class="c"># ---- Stage 1: build ----</span>
<span class="k">FROM</span><span class="w"> </span><span class="s">golang:1.22-alpine</span><span class="w"> </span><span class="k">AS</span><span class="w"> </span><span class="s">build</span>
<span class="k">WORKDIR</span><span class="s"> /src</span>

<span class="k">COPY</span><span class="s"> go.mod ./</span>
<span class="k">RUN </span><span class="nt">--mount</span><span class="o">=</span><span class="nb">type</span><span class="o">=</span>cache,target<span class="o">=</span>/go/pkg/mod go mod download

<span class="k">COPY</span><span class="s"> . .</span>
<span class="k">RUN </span><span class="nt">--mount</span><span class="o">=</span><span class="nb">type</span><span class="o">=</span>cache,target<span class="o">=</span>/go/pkg/mod <span class="se">\
</span>    <span class="nt">--mount</span><span class="o">=</span><span class="nb">type</span><span class="o">=</span>cache,target<span class="o">=</span>/root/.cache/go-build <span class="se">\
</span>    <span class="nv">CGO_ENABLED</span><span class="o">=</span>0 go build <span class="nt">-ldflags</span><span class="o">=</span><span class="s2">"-s -w"</span> <span class="nt">-o</span> /out/pingsvc .

<span class="c"># ---- Stage 2: runtime ----</span>
<span class="k">FROM</span><span class="s"> scratch</span>
<span class="k">COPY</span><span class="s"> --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/</span>
<span class="k">COPY</span><span class="s"> --from=build /out/pingsvc /pingsvc</span>
<span class="k">USER</span><span class="s"> 65534:65534</span>
<span class="k">EXPOSE</span><span class="s"> 8080</span>
<span class="k">ENTRYPOINT</span><span class="s"> ["/pingsvc"]</span>
</code></pre></div></div>

<p>The result: <strong>7.24 MB</strong>, about 180 times smaller.</p>

<pre><code class="language-mermaid">flowchart TD
  subgraph S1["Stage 1: build (golang:1.22-alpine)"]
    src[source + go.mod] --&gt; dl[go mod download]
    dl --&gt; b[go build]
    b --&gt; bin["/out/pingsvc"]
  end
  subgraph S2["Stage 2: runtime (scratch)&lt;br/&gt;the image you ship"]
    certs[CA certificates]
    app["/pingsvc"]
  end
  bin -- "COPY --from=build" --&gt; app
  S1 -. "discarded: compiler, source,&lt;br/&gt;module cache, Alpine userland" .-&gt; x([not shipped])
</code></pre>

<h3 id="line-by-line">Line by line</h3>

<p><strong>Stage 1, the build:</strong></p>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge"># syntax=docker/dockerfile:1</code></strong>: use the current Dockerfile syntax through BuildKit, the default builder in modern Docker. It’s needed for the <code class="language-plaintext highlighter-rouge">--mount</code> flags below.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">FROM golang:1.22-alpine AS build</code></strong>: start a stage from the Go toolchain on Alpine and <strong>name it</strong> <code class="language-plaintext highlighter-rouge">build</code>, so later stages can refer to it.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">COPY go.mod ./</code> then <code class="language-plaintext highlighter-rouge">RUN … go mod download</code></strong>: fetch dependencies in their own layer before copying the source. As in <a href="/portfolio-site/blog/2025/07/10/chapter-1-1-docker-basics/">Chapter 1.1</a>, editing code then reuses this layer. With third-party modules you’d copy <code class="language-plaintext highlighter-rouge">go.sum</code> as well.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">--mount=type=cache,target=/go/pkg/mod</code></strong>: a <strong>BuildKit cache mount</strong>. The module cache persists between builds on this machine but is never written into the image, so even when this layer has to rerun, downloads come from the local cache.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">--mount=type=cache,target=/root/.cache/go-build</code></strong>: the same for Go’s compiler cache, so rebuilds only recompile what changed.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">CGO_ENABLED=0</code></strong>: build a pure-Go, statically linked binary that doesn’t depend on the C library. This is what makes an empty runtime image possible: <code class="language-plaintext highlighter-rouge">scratch</code> has no libc to link against.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">-ldflags="-s -w"</code></strong>: strip the symbol table (<code class="language-plaintext highlighter-rouge">-s</code>) and DWARF debug information (<code class="language-plaintext highlighter-rouge">-w</code>) for a smaller binary. You lose debugger symbols, not stack traces.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">-o /out/pingsvc</code></strong>: write the binary to a predictable path for the next stage to copy.</li>
</ul>

<p>(You’ll still find <code class="language-plaintext highlighter-rouge">-a -installsuffix cgo</code> in many guides. Those flags date from before Go 1.10’s build cache; today <code class="language-plaintext highlighter-rouge">-a</code> only forces a full rebuild of the standard library every time.)</p>

<p><strong>Stage 2, the runtime:</strong></p>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">FROM scratch</code></strong>: an empty image: no shell, no package manager, no userland. Only what you copy in exists.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">COPY --from=build /etc/ssl/certs/ca-certificates.crt …</code></strong>: the CA bundle, so the service can verify certificates on outbound HTTPS calls. Without it, any <code class="language-plaintext highlighter-rouge">https://</code> request fails with <code class="language-plaintext highlighter-rouge">x509: certificate signed by unknown authority</code>. (The Alpine Go image already has the bundle installed.)</li>
  <li><strong><code class="language-plaintext highlighter-rouge">COPY --from=build /out/pingsvc /pingsvc</code></strong>: the binary, and nothing else, from stage 1.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">USER 65534:65534</code></strong>: run as UID/GID 65534, the conventional “nobody”. <code class="language-plaintext highlighter-rouge">scratch</code> has no <code class="language-plaintext highlighter-rouge">/etc/passwd</code>, but numeric IDs work without one. Otherwise the process runs as root.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">ENTRYPOINT ["/pingsvc"]</code></strong>: the binary is the container’s process. Arguments passed to <code class="language-plaintext highlighter-rouge">docker run pingsvc …</code> are appended to it.</li>
</ul>

<p>Build and check:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker build <span class="nt">-t</span> pingsvc:1.0 <span class="nb">.</span>
docker image <span class="nb">ls </span>pingsvc
docker run <span class="nt">--rm</span> <span class="nt">-p</span> 8080:8080 pingsvc:1.0
curl http://localhost:8080/ping        <span class="c"># pong</span>
</code></pre></div></div>

<p>Only the last stage becomes the image; the build stage stays behind as cache.</p>

<h2 id="what-you-give-up-with-scratch-and-the-alternatives">What you give up with <code class="language-plaintext highlighter-rouge">scratch</code>, and the alternatives</h2>

<p>An empty image has no shell. <code class="language-plaintext highlighter-rouge">docker exec -it … sh</code> fails with <code class="language-plaintext highlighter-rouge">executable file not found</code>, and there’s no <code class="language-plaintext highlighter-rouge">curl</code> or <code class="language-plaintext highlighter-rouge">ps</code> for debugging. That’s a security win, since there’s nothing for an attacker to use either, but it changes how you debug: use logs and metrics, or attach a tools container to the target’s namespaces (<a href="/portfolio-site/blog/2025/07/14/chapter-1-8-docker-network/">Chapter 1.8</a>’s container mode).</p>

<p>If <code class="language-plaintext highlighter-rouge">scratch</code> is too bare, there are two common middle grounds:</p>

<table>
  <thead>
    <tr>
      <th>Runtime base</th>
      <th>Size</th>
      <th>Includes</th>
      <th>Choose it when</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">scratch</code></td>
      <td>~0</td>
      <td>nothing</td>
      <td>static binaries (Go, Rust); you add certs yourself</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">gcr.io/distroless/static-debian12:nonroot</code></td>
      <td>~2 MB</td>
      <td>CA certs, time zone data, a non-root user, no shell</td>
      <td>static binaries, without the manual extras</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">alpine:3.20</code></td>
      <td>~8 MB</td>
      <td>shell, <code class="language-plaintext highlighter-rouge">apk</code> package manager</td>
      <td>you need a few tools, or the binary needs libc (musl)</td>
    </tr>
  </tbody>
</table>

<p>With distroless, stage 2 shrinks to:</p>

<div class="language-dockerfile highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">FROM</span><span class="s"> gcr.io/distroless/static-debian12:nonroot</span>
<span class="k">COPY</span><span class="s"> --from=build /out/pingsvc /pingsvc</span>
<span class="k">ENTRYPOINT</span><span class="s"> ["/pingsvc"]</span>
</code></pre></div></div>

<p>The certificates and the non-root user are already in the base image.</p>

<h2 id="the-same-idea-for-a-javascript-frontend">The same idea for a JavaScript frontend</h2>

<p>Multi-stage isn’t only for compiled languages. A React or Vue app needs Node.js and hundreds of megabytes of <code class="language-plaintext highlighter-rouge">node_modules</code> to <em>build</em>, but the result is a folder of static files:</p>

<div class="language-dockerfile highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># ---- build: Node, dependencies, bundler ----</span>
<span class="k">FROM</span><span class="w"> </span><span class="s">node:22-alpine</span><span class="w"> </span><span class="k">AS</span><span class="w"> </span><span class="s">build</span>
<span class="k">WORKDIR</span><span class="s"> /app</span>
<span class="k">COPY</span><span class="s"> package*.json ./</span>
<span class="k">RUN </span>npm ci
<span class="k">COPY</span><span class="s"> . .</span>
<span class="k">RUN </span>npm run build

<span class="c"># ---- runtime: just a web server and the built files ----</span>
<span class="k">FROM</span><span class="s"> nginx:1.27-alpine</span>
<span class="k">COPY</span><span class="s"> --from=build /app/dist /usr/share/nginx/html</span>
</code></pre></div></div>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">npm ci</code></strong>: installs exactly what <code class="language-plaintext highlighter-rouge">package-lock.json</code> specifies, <em>including</em> dev dependencies, because the bundler needs them.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">npm run build</code></strong>: produces the static site in <code class="language-plaintext highlighter-rouge">dist/</code> (Vite’s default; Create React App uses <code class="language-plaintext highlighter-rouge">build/</code>).</li>
  <li><strong>Stage 2</strong> is stock Nginx plus the built files. No Node.js, no <code class="language-plaintext highlighter-rouge">node_modules</code> and no source code reach production.</li>
</ul>

<h2 id="tests-as-a-build-stage">Tests as a build stage</h2>

<p>Stages don’t have to end up in an image. A stage that runs the test suite turns “the build passes” into “the tests pass”:</p>

<div class="language-dockerfile highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">FROM</span><span class="w"> </span><span class="s">build</span><span class="w"> </span><span class="k">AS</span><span class="w"> </span><span class="s">test</span>
<span class="k">RUN </span>go <span class="nb">test</span> ./...
</code></pre></div></div>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker build <span class="nt">--target</span> <span class="nb">test</span> <span class="nb">.</span>          <span class="c"># build up to the test stage; fails if tests fail</span>
docker build <span class="nt">-t</span> pingsvc:1.0 <span class="nb">.</span>         <span class="c"># the default: the last stage, the runtime image</span>
</code></pre></div></div>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">FROM build AS test</code></strong>: a stage that starts from the <code class="language-plaintext highlighter-rouge">build</code> stage’s result, so the source and toolchain are already there.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">--target test</code></strong>: stop at that stage. CI can run this first and only build and push the runtime image if it succeeds.</li>
</ul>

<p>A normal <code class="language-plaintext highlighter-rouge">docker build</code> skips the test stage entirely: BuildKit only builds stages the final image actually depends on.</p>

<h2 id="checklist">Checklist</h2>

<ul>
  <li>Build tools in an early stage; the final stage starts from the smallest base that works.</li>
  <li>Copy <strong>only</strong> artifacts across stages: binaries, built assets, never source or caches.</li>
  <li>Dependency manifests before source, and cache mounts for package managers.</li>
  <li>Non-root <code class="language-plaintext highlighter-rouge">USER</code> in the final stage, and CA certificates if the service makes HTTPS calls.</li>
  <li>Pin base image versions in both stages.</li>
</ul>

<p>That’s the end of the Docker chapter. We started with <code class="language-plaintext highlighter-rouge">docker run hello-world</code>; by now you’ve built images, wired services together on networks, run databases and CI in containers, managed remote hosts and a cluster, and shipped images a fraction of their naive size.</p>]]></content><author><name>Echo Yin</name></author><category term="devops" /><category term="Platform Engineering" /><category term="DevOps" /><category term="Chapter One" /><category term="Docker" /><summary type="html"><![CDATA[Build with the full toolchain, ship only the result. A Go service goes from 1.31 GB to 7.24 MB with a two-stage Dockerfile, explained line by line, plus distroless and Alpine runtime choices, a Node.js frontend served by Nginx, BuildKit cache mounts, and running tests as a build stage.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://e-choness.github.io/portfolio-site/assets/images/blogs/docker-multistage.webp" /><media:content medium="image" url="https://e-choness.github.io/portfolio-site/assets/images/blogs/docker-multistage.webp" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Chapter 1.10 - Remote Docker Hosts: Docker Contexts over SSH</title><link href="https://e-choness.github.io/portfolio-site/blog/2025/07/16/chapter-1-10-docker-machine/" rel="alternate" type="text/html" title="Chapter 1.10 - Remote Docker Hosts: Docker Contexts over SSH" /><published>2025-07-16T00:00:00+00:00</published><updated>2025-07-16T00:00:00+00:00</updated><id>https://e-choness.github.io/portfolio-site/blog/2025/07/16/chapter-1-10-docker-machine</id><content type="html" xml:base="https://e-choness.github.io/portfolio-site/blog/2025/07/16/chapter-1-10-docker-machine/"><![CDATA[<p>Sooner or later your containers need to run somewhere other than your laptop: a staging server, a build box, a small production host. You could SSH in and run <code class="language-plaintext highlighter-rouge">docker</code> there, but then your Compose files, scripts and muscle memory all live in two places.</p>

<p>A better model: <strong>keep one Docker CLI on your laptop and point it at whichever machine you’re working on.</strong> That’s what <strong>Docker contexts</strong> do. A context is a named connection to a Docker daemon: your local one, or one on a server over SSH. Switch the context, and every <code class="language-plaintext highlighter-rouge">docker</code> and <code class="language-plaintext highlighter-rouge">docker compose</code> command runs against that machine.</p>

<p>(If you remember <strong>Docker Machine</strong>, the <code class="language-plaintext highlighter-rouge">docker-machine create / env / ssh</code> tool: it was deprecated and archived in 2021. Its two jobs, creating machines and connecting to them, are now done by your cloud provider’s tooling and by contexts respectively. There’s a mapping table at the end.)</p>

<pre><code class="language-mermaid">flowchart LR
  cli[docker CLI on your laptop] -- "context: default" --&gt; local[(Local daemon&lt;br/&gt;Docker Desktop / Engine)]
  cli -- "context: staging&lt;br/&gt;ssh://deploy@staging" --&gt; s[(Docker Engine&lt;br/&gt;staging server)]
  cli -- "context: prod&lt;br/&gt;ssh://deploy@prod" --&gt; p[(Docker Engine&lt;br/&gt;production server)]
</code></pre>

<h2 id="1-a-server-with-docker-engine">1. A server with Docker Engine</h2>

<p>Any Linux VM or physical machine works. On Ubuntu, install Docker Engine from Docker’s own repository (distribution packages tend to lag behind):</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># Docker's signing key</span>
<span class="nb">sudo </span>apt-get update
<span class="nb">sudo </span>apt-get <span class="nb">install</span> <span class="nt">-y</span> ca-certificates curl
<span class="nb">sudo install</span> <span class="nt">-m</span> 0755 <span class="nt">-d</span> /etc/apt/keyrings
<span class="nb">sudo </span>curl <span class="nt">-fsSL</span> https://download.docker.com/linux/ubuntu/gpg <span class="nt">-o</span> /etc/apt/keyrings/docker.asc
<span class="nb">sudo chmod </span>a+r /etc/apt/keyrings/docker.asc

<span class="c"># The repository, for this Ubuntu release and CPU architecture</span>
<span class="nb">echo</span> <span class="s2">"deb [arch=</span><span class="si">$(</span>dpkg <span class="nt">--print-architecture</span><span class="si">)</span><span class="s2"> signed-by=/etc/apt/keyrings/docker.asc] </span><span class="se">\</span><span class="s2">
https://download.docker.com/linux/ubuntu </span><span class="si">$(</span><span class="nb">.</span> /etc/os-release <span class="o">&amp;&amp;</span> <span class="nb">echo</span> <span class="s2">"</span><span class="k">${</span><span class="nv">UBUNTU_CODENAME</span><span class="k">:-</span><span class="nv">$VERSION_CODENAME</span><span class="k">}</span><span class="s2">"</span><span class="si">)</span><span class="s2"> stable"</span> <span class="se">\</span>
  | <span class="nb">sudo tee</span> /etc/apt/sources.list.d/docker.list <span class="o">&gt;</span> /dev/null

<span class="c"># Engine, CLI, containerd, and the buildx and compose plugins</span>
<span class="nb">sudo </span>apt-get update
<span class="nb">sudo </span>apt-get <span class="nb">install</span> <span class="nt">-y</span> docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
</code></pre></div></div>

<p>What the less obvious lines do:</p>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">install -m 0755 -d /etc/apt/keyrings</code></strong>: create the keyring directory with the right permissions.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">curl … -o /etc/apt/keyrings/docker.asc</code></strong>: download Docker’s GPG key; apt uses it to verify that packages really come from Docker.</li>
  <li><strong>The <code class="language-plaintext highlighter-rouge">echo "deb …"</code> line</strong>: add the repository. <code class="language-plaintext highlighter-rouge">dpkg --print-architecture</code> fills in <code class="language-plaintext highlighter-rouge">amd64</code> or <code class="language-plaintext highlighter-rouge">arm64</code>; <code class="language-plaintext highlighter-rouge">/etc/os-release</code> supplies the release codename (<code class="language-plaintext highlighter-rouge">noble</code>, <code class="language-plaintext highlighter-rouge">jammy</code>), so the same command works across versions. <code class="language-plaintext highlighter-rouge">signed-by=</code> restricts that key to this one repository.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">docker-ce</code></strong>: the daemon; <strong><code class="language-plaintext highlighter-rouge">containerd.io</code></strong>: the runtime underneath it; the two plugins give you <code class="language-plaintext highlighter-rouge">docker buildx</code> and <code class="language-plaintext highlighter-rouge">docker compose</code> on the server too.</li>
</ul>

<p>Other distributions have equivalent instructions in <a href="https://docs.docker.com/engine/install/">Docker’s install docs</a>.</p>

<p>Then create a user for deployments, allow it to use Docker, and install your SSH key:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">sudo </span>adduser <span class="nt">--disabled-password</span> <span class="nt">--gecos</span> <span class="s2">""</span> deploy
<span class="nb">sudo </span>usermod <span class="nt">-aG</span> docker deploy
<span class="nb">sudo mkdir</span> <span class="nt">-p</span> /home/deploy/.ssh
<span class="nb">sudo cp</span> ~/.ssh/authorized_keys /home/deploy/.ssh/      <span class="c"># or paste your public key into it</span>
<span class="nb">sudo chown</span> <span class="nt">-R</span> deploy:deploy /home/deploy/.ssh
<span class="nb">sudo chmod </span>700 /home/deploy/.ssh <span class="o">&amp;&amp;</span> <span class="nb">sudo chmod </span>600 /home/deploy/.ssh/authorized_keys
</code></pre></div></div>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">--disabled-password</code></strong>: the user can only log in with an SSH key.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">usermod -aG docker deploy</code></strong>: membership in the <code class="language-plaintext highlighter-rouge">docker</code> group lets <code class="language-plaintext highlighter-rouge">deploy</code> use the daemon without <code class="language-plaintext highlighter-rouge">sudo</code>. As covered in earlier chapters, that’s root-equivalent on this host, so protect that key accordingly.</li>
  <li><strong>The <code class="language-plaintext highlighter-rouge">chmod</code> lines</strong>: SSH refuses keys in directories other users can write to.</li>
</ul>

<h3 id="the-same-thing-automatically-with-cloud-init">The same thing, automatically, with cloud-init</h3>

<p>Most cloud providers (and Multipass for local VMs) accept a <strong>cloud-init</strong> file that runs on first boot. That turns “create a Docker host” into a single command, which is what <code class="language-plaintext highlighter-rouge">docker-machine create</code> used to do:</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">#cloud-config</span>
<span class="na">users</span><span class="pi">:</span>
  <span class="pi">-</span> <span class="s">default</span>
  <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">deploy</span>
    <span class="na">shell</span><span class="pi">:</span> <span class="s">/bin/bash</span>
    <span class="na">ssh_authorized_keys</span><span class="pi">:</span>
      <span class="pi">-</span> <span class="s">ssh-ed25519 AAAAC3Nza... you@laptop</span>

<span class="na">package_update</span><span class="pi">:</span> <span class="kc">true</span>

<span class="na">runcmd</span><span class="pi">:</span>
  <span class="pi">-</span> <span class="s">curl -fsSL https://get.docker.com | sh</span>
  <span class="pi">-</span> <span class="s">usermod -aG docker deploy</span>
</code></pre></div></div>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">users:</code></strong>: keep the provider’s default user and add <code class="language-plaintext highlighter-rouge">deploy</code>, with your public key and no password.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">package_update: true</code></strong>: refresh the package lists before anything else.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">runcmd:</code></strong>: commands that run once, as root, at the end of the first boot. <code class="language-plaintext highlighter-rouge">get.docker.com</code> is Docker’s convenience install script: it adds the same repository and packages as the manual steps above. It’s fine for throwaway and test hosts; for production, pin versions using the repository steps.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">usermod -aG docker deploy</code></strong>: must run <em>after</em> Docker is installed, because the <code class="language-plaintext highlighter-rouge">docker</code> group doesn’t exist before that.</li>
</ul>

<p>For example, a local VM with Multipass, or a cloud VM with the provider’s CLI:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>multipass launch <span class="nt">--name</span> staging <span class="nt">--cpus</span> 2 <span class="nt">--memory</span> 4G <span class="nt">--disk</span> 20G <span class="nt">--cloud-init</span> docker.yaml
<span class="c"># or, e.g.: hcloud server create --name staging --type cx22 --image ubuntu-24.04 --user-data-from-file docker.yaml</span>
</code></pre></div></div>

<p>For fleets, Terraform or your provider’s templates do the same declaratively.</p>

<h2 id="2-connecting-with-a-context">2. Connecting with a context</h2>

<p>On your laptop:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker context create staging <span class="nt">--docker</span> <span class="s2">"host=ssh://deploy@203.0.113.10"</span>
docker context <span class="nb">ls</span>
</code></pre></div></div>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>NAME        DESCRIPTION                               DOCKER ENDPOINT
default *   Current DOCKER_HOST based configuration   unix:///var/run/docker.sock
staging                                               ssh://deploy@203.0.113.10
</code></pre></div></div>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">host=ssh://deploy@203.0.113.10</code></strong>: the Docker CLI opens an SSH connection as <code class="language-plaintext highlighter-rouge">deploy</code> and talks to the remote daemon’s socket through it. The daemon needs <strong>no</strong> configuration changes and no open ports beyond SSH.</li>
  <li>The <code class="language-plaintext highlighter-rouge">*</code> marks the active context.</li>
</ul>

<p>Three ways to use it:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker context use staging      <span class="c"># switch: everything from now on runs on staging</span>
docker ps                       <span class="c"># containers on staging</span>
docker context use default      <span class="c"># back to your local daemon</span>

docker <span class="nt">--context</span> staging ps     <span class="c"># one command, without switching</span>

<span class="nv">DOCKER_CONTEXT</span><span class="o">=</span>staging docker ps          <span class="c"># per shell or per script</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">docker context use</code> is sticky, surviving across terminals and reboots, and that’s the classic way to run something on production by accident. A few habits help: prefer <code class="language-plaintext highlighter-rouge">--context</code> for one-off commands, and put the current context in your shell prompt, or at least run <code class="language-plaintext highlighter-rouge">docker context ls</code> before anything destructive.</p>

<h3 id="making-ssh-fast-and-tidy">Making SSH fast and tidy</h3>

<p>Every <code class="language-plaintext highlighter-rouge">docker</code> command opens a new SSH connection, which adds noticeable latency. Let SSH reuse one connection, and give the host a short name, in <code class="language-plaintext highlighter-rouge">~/.ssh/config</code>:</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Host staging
    HostName 203.0.113.10
    User deploy
    IdentityFile ~/.ssh/id_ed25519
    ControlMaster auto
    ControlPath ~/.ssh/cm-%r@%h:%p
    ControlPersist 10m
</code></pre></div></div>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">Host staging</code></strong>: an alias; now <code class="language-plaintext highlighter-rouge">ssh staging</code> works, and so does <code class="language-plaintext highlighter-rouge">host=ssh://staging</code> in the context.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">ControlMaster auto</code> + <code class="language-plaintext highlighter-rouge">ControlPath</code></strong>: the first connection opens a shared channel at that socket path; later ones ride on it.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">ControlPersist 10m</code></strong>: keep the shared channel open for 10 minutes after the last use, so a burst of Docker commands pays the SSH handshake once.</li>
</ul>

<p>Then recreate the context with the alias: <code class="language-plaintext highlighter-rouge">docker context create staging --docker "host=ssh://staging"</code>.</p>

<h2 id="3-compose-on-a-remote-host">3. Compose on a remote host</h2>

<p>With a remote context, Compose works as usual; the containers simply start on the server:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker <span class="nt">--context</span> staging compose up <span class="nt">-d</span> <span class="nt">--build</span>
docker <span class="nt">--context</span> staging compose logs <span class="nt">-f</span>
</code></pre></div></div>

<p>Two things behave differently, and both catch people out:</p>

<ul>
  <li><strong>Builds happen on the remote daemon.</strong> <code class="language-plaintext highlighter-rouge">--build</code> sends the build context (your project directory, minus <code class="language-plaintext highlighter-rouge">.dockerignore</code>) over SSH and builds there. That’s convenient for small projects; for bigger ones, build in CI and push to a registry, and have the server only pull.</li>
  <li><strong>Bind mounts refer to the remote host’s filesystem.</strong> <code class="language-plaintext highlighter-rouge">./nginx/default.conf:/etc/nginx/conf.d/default.conf</code> in your Compose file means <code class="language-plaintext highlighter-rouge">./nginx/default.conf</code> <em>on the server</em>, relative to the same path. If the file only exists on your laptop, Docker creates an empty directory in its place on the server, and Nginx fails with a confusing error. Either copy the files over first (<code class="language-plaintext highlighter-rouge">rsync -av nginx/ staging:app/nginx/</code>), bake configuration into images, or use named volumes and Compose <code class="language-plaintext highlighter-rouge">configs</code>.</li>
</ul>

<h2 id="4-dont-open-the-daemon-to-the-network">4. Don’t open the daemon to the network</h2>

<p>Guides from the Docker Machine era expose the daemon on TCP port 2375 so remote clients can reach it. <strong>An unauthenticated Docker API is root on that machine for anyone who can reach the port</strong>, and automated scanners find exposed ones within hours. SSH contexts make it unnecessary.</p>

<p>If SSH isn’t an option, the daemon can listen on <strong>2376 with mutual TLS</strong>, where both sides present certificates. Contexts support that too (<code class="language-plaintext highlighter-rouge">--docker "host=tcp://host:2376,ca=…,cert=…,key=…"</code>), but managing the certificates is real work. Choose SSH whenever you can.</p>

<h2 id="5-local-machines-are-contexts-too">5. Local machines are contexts too</h2>

<p>Local VM tools register their own contexts:</p>

<ul>
  <li><strong>Docker Desktop</strong> creates <code class="language-plaintext highlighter-rouge">desktop-linux</code>.</li>
  <li><strong>Colima</strong> (macOS/Linux): <code class="language-plaintext highlighter-rouge">colima start --cpus 4 --memory 8</code> starts a VM with Docker and switches to the <code class="language-plaintext highlighter-rouge">colima</code> context.</li>
  <li><strong>Multipass</strong> VMs set up with the cloud-init above are just SSH hosts: <code class="language-plaintext highlighter-rouge">docker context create lab --docker "host=ssh://deploy@$(multipass info lab | awk '/IPv4/{print $2}')"</code>.</li>
</ul>

<p>So the same workflow covers a VM on your laptop, a lab server and production, and switching between them is one flag.</p>

<h2 id="coming-from-docker-machine">Coming from Docker Machine</h2>

<table>
  <thead>
    <tr>
      <th><code class="language-plaintext highlighter-rouge">docker-machine</code></th>
      <th>Today</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">create -d &lt;driver&gt; host</code></td>
      <td>cloud-init + provider CLI / Terraform (section 1), or <code class="language-plaintext highlighter-rouge">multipass launch</code>, <code class="language-plaintext highlighter-rouge">colima start</code></td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">env host</code> + <code class="language-plaintext highlighter-rouge">eval $(…)</code></td>
      <td><code class="language-plaintext highlighter-rouge">docker context use host</code>, or <code class="language-plaintext highlighter-rouge">--context host</code></td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">ls</code></td>
      <td><code class="language-plaintext highlighter-rouge">docker context ls</code></td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">ssh host</code></td>
      <td><code class="language-plaintext highlighter-rouge">ssh host</code></td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">scp</code></td>
      <td><code class="language-plaintext highlighter-rouge">scp</code> / <code class="language-plaintext highlighter-rouge">rsync</code></td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">ip host</code></td>
      <td>your provider’s CLI, or the context’s endpoint</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">rm host</code></td>
      <td>delete the VM with the provider’s CLI; <code class="language-plaintext highlighter-rouge">docker context rm host</code></td>
    </tr>
    <tr>
      <td>TLS certs on :2376 generated for you</td>
      <td>SSH (no certificates), or TLS contexts if you must</td>
    </tr>
  </tbody>
</table>

<p><a href="/portfolio-site/blog/2025/07/17/chapter-1-11-docker-swarm/">Chapter 1.11</a> takes several of these hosts and joins them into one cluster with Docker Swarm.</p>]]></content><author><name>Echo Yin</name></author><category term="devops" /><category term="Platform Engineering" /><category term="DevOps" /><category term="Chapter One" /><category term="Docker" /><summary type="html"><![CDATA[Drive Docker on any number of servers from your laptop: provision a host with Docker Engine by hand or with cloud-init, connect to it with a Docker context over SSH, run Compose projects remotely, and avoid the traps (remote bind mounts, slow SSH, exposed daemons). This is the modern replacement for the retired Docker Machine.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://e-choness.github.io/portfolio-site/assets/images/blogs/docker-machine.webp" /><media:content medium="image" url="https://e-choness.github.io/portfolio-site/assets/images/blogs/docker-machine.webp" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Chapter 1.9 - Docker Compose: Whole Applications in One File</title><link href="https://e-choness.github.io/portfolio-site/blog/2025/07/16/chapter-1-9-docker-compose/" rel="alternate" type="text/html" title="Chapter 1.9 - Docker Compose: Whole Applications in One File" /><published>2025-07-16T00:00:00+00:00</published><updated>2025-07-16T00:00:00+00:00</updated><id>https://e-choness.github.io/portfolio-site/blog/2025/07/16/chapter-1-9-docker-compose</id><content type="html" xml:base="https://e-choness.github.io/portfolio-site/blog/2025/07/16/chapter-1-9-docker-compose/"><![CDATA[<p>By now, running the pieces of an application means a stack of long <code class="language-plaintext highlighter-rouge">docker run</code> commands, a <code class="language-plaintext highlighter-rouge">docker network create</code>, and remembering the order to start them in. <strong>Docker Compose</strong> replaces all of that with one declarative file: you describe the services, networks and volumes, and <code class="language-plaintext highlighter-rouge">docker compose up</code> makes reality match.</p>

<p>It’s the standard tool for local development, CI test environments and single-host deployments. (For several hosts you’d move to Swarm, <a href="/portfolio-site/blog/2025/07/17/chapter-1-11-docker-swarm/">Chapter 1.11</a>, or Kubernetes.)</p>

<h2 id="installing">Installing</h2>

<p>Compose v2 is a plugin for the Docker CLI, invoked as <code class="language-plaintext highlighter-rouge">docker compose</code> (with a space).</p>

<ul>
  <li><strong>Docker Desktop</strong> includes it.</li>
  <li><strong>Linux with Docker Engine</strong>: install <code class="language-plaintext highlighter-rouge">docker-compose-plugin</code> from Docker’s package repository (<code class="language-plaintext highlighter-rouge">sudo apt install docker-compose-plugin</code> or <code class="language-plaintext highlighter-rouge">sudo dnf install docker-compose-plugin</code>).</li>
</ul>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker compose version
</code></pre></div></div>

<p>If you find <code class="language-plaintext highlighter-rouge">docker-compose</code> (with a hyphen) in old scripts: that’s Compose v1, a separate Python tool that reached end of life in 2023. The file format is compatible; switch the command.</p>

<h2 id="the-example-proxy-app-and-cache">The example: proxy, app and cache</h2>

<p>We’ll extend the app from <a href="/portfolio-site/blog/2025/07/10/chapter-1-1-docker-basics/">Chapter 1.1</a> to count visits in Redis, and put Nginx in front of it:</p>

<pre><code class="language-mermaid">flowchart TD
  b([Browser]) -- "localhost:8080" --&gt; proxy
  subgraph P["Compose project: shop&lt;br/&gt;(network shop_default)"]
    proxy["proxy&lt;br/&gt;nginx:1.27"] -- "api:3000" --&gt; api["api&lt;br/&gt;built from ./Dockerfile"]
    api -- "redis:6379" --&gt; redis["redis&lt;br/&gt;redis:8.0"]
  end
  vol[("redis-data volume")] -. "/data" .-&gt; redis
</code></pre>

<h3 id="the-app">The app</h3>

<p><code class="language-plaintext highlighter-rouge">server.js</code>:</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">const</span> <span class="nx">express</span> <span class="o">=</span> <span class="nf">require</span><span class="p">(</span><span class="dl">"</span><span class="s2">express</span><span class="dl">"</span><span class="p">);</span>
<span class="kd">const</span> <span class="nx">os</span> <span class="o">=</span> <span class="nf">require</span><span class="p">(</span><span class="dl">"</span><span class="s2">os</span><span class="dl">"</span><span class="p">);</span>
<span class="kd">const</span> <span class="p">{</span> <span class="nx">createClient</span> <span class="p">}</span> <span class="o">=</span> <span class="nf">require</span><span class="p">(</span><span class="dl">"</span><span class="s2">redis</span><span class="dl">"</span><span class="p">);</span>

<span class="kd">const</span> <span class="nx">redis</span> <span class="o">=</span> <span class="nf">createClient</span><span class="p">({</span> <span class="na">url</span><span class="p">:</span> <span class="nx">process</span><span class="p">.</span><span class="nx">env</span><span class="p">.</span><span class="nx">REDIS_URL</span> <span class="p">});</span>
<span class="nx">redis</span><span class="p">.</span><span class="nf">on</span><span class="p">(</span><span class="dl">"</span><span class="s2">error</span><span class="dl">"</span><span class="p">,</span> <span class="p">(</span><span class="nx">err</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="nx">console</span><span class="p">.</span><span class="nf">error</span><span class="p">(</span><span class="dl">"</span><span class="s2">redis:</span><span class="dl">"</span><span class="p">,</span> <span class="nx">err</span><span class="p">.</span><span class="nx">message</span><span class="p">));</span>

<span class="kd">const</span> <span class="nx">app</span> <span class="o">=</span> <span class="nf">express</span><span class="p">();</span>
<span class="nx">app</span><span class="p">.</span><span class="nf">get</span><span class="p">(</span><span class="dl">"</span><span class="s2">/</span><span class="dl">"</span><span class="p">,</span> <span class="k">async </span><span class="p">(</span><span class="nx">req</span><span class="p">,</span> <span class="nx">res</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
  <span class="kd">const</span> <span class="nx">visits</span> <span class="o">=</span> <span class="k">await</span> <span class="nx">redis</span><span class="p">.</span><span class="nf">incr</span><span class="p">(</span><span class="dl">"</span><span class="s2">visits</span><span class="dl">"</span><span class="p">);</span>
  <span class="nx">res</span><span class="p">.</span><span class="nf">send</span><span class="p">(</span><span class="s2">`Hello from </span><span class="p">${</span><span class="nx">os</span><span class="p">.</span><span class="nf">hostname</span><span class="p">()}</span><span class="s2">, visit #</span><span class="p">${</span><span class="nx">visits</span><span class="p">}</span><span class="s2">\n`</span><span class="p">);</span>
<span class="p">});</span>

<span class="nx">redis</span><span class="p">.</span><span class="nf">connect</span><span class="p">().</span><span class="nf">then</span><span class="p">(()</span> <span class="o">=&gt;</span> <span class="p">{</span>
  <span class="nx">app</span><span class="p">.</span><span class="nf">listen</span><span class="p">(</span><span class="mi">3000</span><span class="p">,</span> <span class="p">()</span> <span class="o">=&gt;</span> <span class="nx">console</span><span class="p">.</span><span class="nf">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">listening on 3000</span><span class="dl">"</span><span class="p">));</span>
<span class="p">});</span>
</code></pre></div></div>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">createClient({ url: process.env.REDIS_URL })</code></strong>: the Redis address comes from the environment, so the same image works anywhere; Compose will set it to <code class="language-plaintext highlighter-rouge">redis://redis:6379</code>.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">redis.incr("visits")</code></strong>: an atomic increment, so concurrent requests, even from several app containers, never lose a count.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">redis.connect().then(…)</code></strong>: start accepting HTTP requests only once Redis is connected.</li>
</ul>

<p><code class="language-plaintext highlighter-rouge">package.json</code> adds the Redis client:</p>

<div class="language-json highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span><span class="w">
  </span><span class="nl">"name"</span><span class="p">:</span><span class="w"> </span><span class="s2">"shop-api"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"version"</span><span class="p">:</span><span class="w"> </span><span class="s2">"1.0.0"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"main"</span><span class="p">:</span><span class="w"> </span><span class="s2">"server.js"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"dependencies"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
    </span><span class="nl">"express"</span><span class="p">:</span><span class="w"> </span><span class="s2">"^5.1.0"</span><span class="p">,</span><span class="w">
    </span><span class="nl">"redis"</span><span class="p">:</span><span class="w"> </span><span class="s2">"^4.7.0"</span><span class="w">
  </span><span class="p">}</span><span class="w">
</span><span class="p">}</span><span class="w">
</span></code></pre></div></div>

<p>The <code class="language-plaintext highlighter-rouge">Dockerfile</code> and <code class="language-plaintext highlighter-rouge">.dockerignore</code> are unchanged from Chapter 1.1. For the proxy, <code class="language-plaintext highlighter-rouge">nginx/default.conf</code>:</p>

<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">server</span> <span class="p">{</span>
    <span class="kn">listen</span> <span class="mi">80</span><span class="p">;</span>
    <span class="kn">location</span> <span class="n">/</span> <span class="p">{</span>
        <span class="kn">proxy_pass</span> <span class="s">http://api:3000</span><span class="p">;</span>
        <span class="kn">proxy_set_header</span> <span class="s">Host</span> <span class="nv">$host</span><span class="p">;</span>
        <span class="kn">proxy_set_header</span> <span class="s">X-Forwarded-For</span> <span class="nv">$proxy_add_x_forwarded_for</span><span class="p">;</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<h3 id="the-compose-file">The Compose file</h3>

<p><code class="language-plaintext highlighter-rouge">compose.yml</code>, next to the Dockerfile:</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">name</span><span class="pi">:</span> <span class="s">shop</span>

<span class="na">services</span><span class="pi">:</span>
  <span class="na">proxy</span><span class="pi">:</span>
    <span class="na">image</span><span class="pi">:</span> <span class="s">nginx:1.27</span>
    <span class="na">ports</span><span class="pi">:</span>
      <span class="pi">-</span> <span class="s2">"</span><span class="s">8080:80"</span>
    <span class="na">volumes</span><span class="pi">:</span>
      <span class="pi">-</span> <span class="s">./nginx/default.conf:/etc/nginx/conf.d/default.conf:ro</span>
    <span class="na">depends_on</span><span class="pi">:</span>
      <span class="pi">-</span> <span class="s">api</span>
    <span class="na">restart</span><span class="pi">:</span> <span class="s">unless-stopped</span>

  <span class="na">api</span><span class="pi">:</span>
    <span class="na">build</span><span class="pi">:</span> <span class="s">.</span>
    <span class="na">environment</span><span class="pi">:</span>
      <span class="na">REDIS_URL</span><span class="pi">:</span> <span class="s">redis://redis:6379</span>
    <span class="na">depends_on</span><span class="pi">:</span>
      <span class="na">redis</span><span class="pi">:</span>
        <span class="na">condition</span><span class="pi">:</span> <span class="s">service_healthy</span>
    <span class="na">restart</span><span class="pi">:</span> <span class="s">unless-stopped</span>

  <span class="na">redis</span><span class="pi">:</span>
    <span class="na">image</span><span class="pi">:</span> <span class="s">redis:8.0</span>
    <span class="na">command</span><span class="pi">:</span> <span class="pi">[</span><span class="s2">"</span><span class="s">redis-server"</span><span class="pi">,</span> <span class="s2">"</span><span class="s">--appendonly"</span><span class="pi">,</span> <span class="s2">"</span><span class="s">yes"</span><span class="pi">]</span>
    <span class="na">volumes</span><span class="pi">:</span>
      <span class="pi">-</span> <span class="s">redis-data:/data</span>
    <span class="na">healthcheck</span><span class="pi">:</span>
      <span class="na">test</span><span class="pi">:</span> <span class="pi">[</span><span class="s2">"</span><span class="s">CMD"</span><span class="pi">,</span> <span class="s2">"</span><span class="s">redis-cli"</span><span class="pi">,</span> <span class="s2">"</span><span class="s">ping"</span><span class="pi">]</span>
      <span class="na">interval</span><span class="pi">:</span> <span class="s">5s</span>
      <span class="na">timeout</span><span class="pi">:</span> <span class="s">3s</span>
      <span class="na">retries</span><span class="pi">:</span> <span class="m">5</span>
    <span class="na">restart</span><span class="pi">:</span> <span class="s">unless-stopped</span>

<span class="na">volumes</span><span class="pi">:</span>
  <span class="na">redis-data</span><span class="pi">:</span>
</code></pre></div></div>

<p>Key by key:</p>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">name: shop</code></strong>: the project name. It prefixes everything Compose creates (<code class="language-plaintext highlighter-rouge">shop-api-1</code>, network <code class="language-plaintext highlighter-rouge">shop_default</code>, volume <code class="language-plaintext highlighter-rouge">shop_redis-data</code>). Without it, the directory name is used.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">services:</code></strong>: each entry becomes one or more containers. The service name is also its <strong>DNS name</strong> on the project network, which is why <code class="language-plaintext highlighter-rouge">proxy_pass http://api:3000</code> and <code class="language-plaintext highlighter-rouge">redis://redis:6379</code> work.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">proxy</code></strong>:
    <ul>
      <li><code class="language-plaintext highlighter-rouge">image: nginx:1.27</code>: use a published image.</li>
      <li><code class="language-plaintext highlighter-rouge">ports: "8080:80"</code>: the only published port in the whole project; <code class="language-plaintext highlighter-rouge">api</code> and <code class="language-plaintext highlighter-rouge">redis</code> are reachable only from inside.</li>
      <li><code class="language-plaintext highlighter-rouge">volumes: ./nginx/default.conf:…:ro</code>: relative paths are relative to the Compose file, which keeps the project portable.</li>
      <li><code class="language-plaintext highlighter-rouge">depends_on: [api]</code>: start <code class="language-plaintext highlighter-rouge">api</code> first. This is start order only.</li>
    </ul>
  </li>
  <li><strong><code class="language-plaintext highlighter-rouge">api</code></strong>:
    <ul>
      <li><code class="language-plaintext highlighter-rouge">build: .</code>: build the image from the Dockerfile in this directory instead of pulling one.</li>
      <li><code class="language-plaintext highlighter-rouge">environment</code>: variables for the container.</li>
      <li><code class="language-plaintext highlighter-rouge">depends_on: redis: condition: service_healthy</code>: don’t start <code class="language-plaintext highlighter-rouge">api</code> until Redis’s health check passes, not merely until its container starts.</li>
    </ul>
  </li>
  <li><strong><code class="language-plaintext highlighter-rouge">redis</code></strong>:
    <ul>
      <li><code class="language-plaintext highlighter-rouge">command</code>: replace the image’s default command, here to turn on the append-only file.</li>
      <li><code class="language-plaintext highlighter-rouge">volumes: redis-data:/data</code>: a named volume, declared at the bottom.</li>
      <li><code class="language-plaintext highlighter-rouge">healthcheck</code>: Compose runs <code class="language-plaintext highlighter-rouge">redis-cli ping</code> every 5 seconds; after it succeeds, the container counts as healthy.</li>
    </ul>
  </li>
  <li><strong><code class="language-plaintext highlighter-rouge">restart: unless-stopped</code></strong>: the same restart policy as <code class="language-plaintext highlighter-rouge">docker run --restart</code>.</li>
  <li><strong>Top-level <code class="language-plaintext highlighter-rouge">volumes:</code></strong>: named volumes the project owns. They survive <code class="language-plaintext highlighter-rouge">docker compose down</code>.</li>
  <li><strong>No <code class="language-plaintext highlighter-rouge">networks:</code> section</strong>: Compose creates a default network per project and attaches every service to it. Declare networks only when you want to split tiers.</li>
  <li><strong>No <code class="language-plaintext highlighter-rouge">version:</code> key</strong>: it’s obsolete, and current Compose ignores it with a warning.</li>
</ul>

<h2 id="running-it">Running it</h2>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker compose up <span class="nt">-d</span> <span class="nt">--build</span>
curl http://localhost:8080
<span class="c"># Hello from 5c1f0e9ab2d3, visit #1</span>
docker compose ps
docker compose logs <span class="nt">-f</span> api
</code></pre></div></div>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">up</code></strong>: create whatever doesn’t exist, start whatever isn’t running, and recreate containers whose configuration or image changed. Run it again after editing the file and only the affected services are recreated.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">-d</code></strong>: detached; without it, logs stream to your terminal and Ctrl+C stops everything.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">--build</code></strong>: rebuild images for services with a <code class="language-plaintext highlighter-rouge">build:</code> key, even if one already exists.</li>
</ul>

<h3 id="scaling">Scaling</h3>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker compose up <span class="nt">-d</span> <span class="nt">--scale</span> <span class="nv">api</span><span class="o">=</span>3
docker compose <span class="nb">exec </span>proxy nginx <span class="nt">-s</span> reload
<span class="k">for </span>i <span class="k">in </span>1 2 3 4<span class="p">;</span> <span class="k">do </span>curl <span class="nt">-s</span> http://localhost:8080<span class="p">;</span> <span class="k">done</span>
<span class="c"># Hello from 5c1f0e9ab2d3, visit #2</span>
<span class="c"># Hello from a93b77c01e5f, visit #3</span>
<span class="c"># Hello from 0d4e61b8f7a2, visit #4</span>
<span class="c"># Hello from 5c1f0e9ab2d3, visit #5</span>
</code></pre></div></div>

<p>Three <code class="language-plaintext highlighter-rouge">api</code> containers now share the name <code class="language-plaintext highlighter-rouge">api</code>, and Docker’s DNS returns all three addresses. Nginx resolves <code class="language-plaintext highlighter-rouge">api</code> when it loads its config, so after scaling it needs a reload to pick up the new addresses; then it round-robins between them. The counter keeps climbing across containers, because the state lives in Redis, not in the app. That’s the whole point of stateless services. (Scaling only works because <code class="language-plaintext highlighter-rouge">api</code> publishes no port: three containers can’t all bind host port 8080.)</p>

<h2 id="the-commands-youll-use">The commands you’ll use</h2>

<table>
  <thead>
    <tr>
      <th>Command</th>
      <th>What it does</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">docker compose up -d</code></td>
      <td>Create/update and start everything</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">docker compose ps</code></td>
      <td>Containers in this project, with health status</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">docker compose logs -f [service]</code></td>
      <td>Follow logs, optionally for one service</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">docker compose exec api sh</code></td>
      <td>A shell in a running service container</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">docker compose run --rm api npm test</code></td>
      <td>A <strong>new</strong> one-off container for a task (tests, migrations)</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">docker compose restart api</code></td>
      <td>Restart without recreating</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">docker compose pull</code></td>
      <td>Pull newer versions of the images</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">docker compose build</code></td>
      <td>Rebuild images (<code class="language-plaintext highlighter-rouge">--no-cache</code> for a clean build)</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">docker compose config</code></td>
      <td>Print the final file after variables and merges are applied</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">docker compose stop</code></td>
      <td>Stop, keeping the containers</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">docker compose down</code></td>
      <td>Remove the containers and network; <strong>keep volumes</strong></td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">docker compose down -v</code></td>
      <td>Also delete named volumes, and with them the data</td>
    </tr>
  </tbody>
</table>

<p><code class="language-plaintext highlighter-rouge">exec</code> versus <code class="language-plaintext highlighter-rouge">run</code> trips people up: <code class="language-plaintext highlighter-rouge">exec</code> runs a command in a container that’s already running, while <code class="language-plaintext highlighter-rouge">run</code> starts a fresh container from the service’s definition, which is what you want for one-off tasks that shouldn’t touch the running service.</p>

<h2 id="configuration-without-editing-the-file">Configuration without editing the file</h2>

<h3 id="variables-and-env">Variables and <code class="language-plaintext highlighter-rouge">.env</code></h3>

<p>Compose substitutes <code class="language-plaintext highlighter-rouge">${VARIABLES}</code> in the file from your shell and from a <code class="language-plaintext highlighter-rouge">.env</code> file next to it:</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">services</span><span class="pi">:</span>
  <span class="na">api</span><span class="pi">:</span>
    <span class="na">image</span><span class="pi">:</span> <span class="s">yourname/shop-api:${API_TAG:-latest}</span>
    <span class="na">env_file</span><span class="pi">:</span> <span class="s">api.env</span>
</code></pre></div></div>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">${API_TAG:-latest}</code></strong>: the value of <code class="language-plaintext highlighter-rouge">API_TAG</code>, or <code class="language-plaintext highlighter-rouge">latest</code> if it’s unset. <code class="language-plaintext highlighter-rouge">API_TAG=1.4.2 docker compose up -d</code> deploys a specific version without touching the file.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">.env</code></strong> (automatically read) is for these <em>file</em> variables. <strong><code class="language-plaintext highlighter-rouge">env_file: api.env</code></strong> is different: it passes a file’s variables <em>into the container</em>. Keep both out of Git if they contain secrets.</li>
</ul>

<p><code class="language-plaintext highlighter-rouge">docker compose config</code> shows the result of all substitutions, which is the fastest way to debug “why is it using the wrong value”.</p>

<h3 id="override-files-for-development">Override files for development</h3>

<p>Compose automatically merges <code class="language-plaintext highlighter-rouge">compose.override.yml</code> on top of <code class="language-plaintext highlighter-rouge">compose.yml</code> if it exists. Put development-only changes there:</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># compose.override.yml (development only)</span>
<span class="na">services</span><span class="pi">:</span>
  <span class="na">api</span><span class="pi">:</span>
    <span class="na">command</span><span class="pi">:</span> <span class="pi">[</span><span class="s2">"</span><span class="s">node"</span><span class="pi">,</span> <span class="s2">"</span><span class="s">--watch"</span><span class="pi">,</span> <span class="s2">"</span><span class="s">server.js"</span><span class="pi">]</span>
    <span class="na">volumes</span><span class="pi">:</span>
      <span class="pi">-</span> <span class="s">./server.js:/app/server.js</span>
    <span class="na">ports</span><span class="pi">:</span>
      <span class="pi">-</span> <span class="s2">"</span><span class="s">3000:3000"</span>
</code></pre></div></div>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">--watch</code></strong>: Node restarts the server whenever the file changes.</li>
  <li><strong>The bind mount</strong>: your edited <code class="language-plaintext highlighter-rouge">server.js</code> replaces the one baked into the image, so a save shows up without a rebuild.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">ports: "3000:3000"</code></strong>: hit the app directly while debugging, bypassing the proxy.</li>
</ul>

<p>In production, deploy with only the base file: <code class="language-plaintext highlighter-rouge">docker compose -f compose.yml up -d</code>.</p>

<h3 id="profiles-for-optional-tools">Profiles for optional tools</h3>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">services</span><span class="pi">:</span>
  <span class="na">redis-ui</span><span class="pi">:</span>
    <span class="na">image</span><span class="pi">:</span> <span class="s">redis/redisinsight:latest</span>
    <span class="na">ports</span><span class="pi">:</span>
      <span class="pi">-</span> <span class="s2">"</span><span class="s">5540:5540"</span>
    <span class="na">profiles</span><span class="pi">:</span> <span class="pi">[</span><span class="nv">tools</span><span class="pi">]</span>
</code></pre></div></div>

<p>Services with <code class="language-plaintext highlighter-rouge">profiles:</code> don’t start by default. <code class="language-plaintext highlighter-rouge">docker compose --profile tools up -d</code> adds them, which suits admin UIs and debugging tools you want sometimes, but not always.</p>

<h2 id="a-few-habits-that-pay-off">A few habits that pay off</h2>

<ul>
  <li><strong>Pin image versions</strong> (<code class="language-plaintext highlighter-rouge">nginx:1.27</code>, <code class="language-plaintext highlighter-rouge">redis:8.0</code>) so <code class="language-plaintext highlighter-rouge">docker compose pull</code> never surprises you.</li>
  <li><strong>Publish as little as possible.</strong> Services talk over the project network by name; only the entry point needs <code class="language-plaintext highlighter-rouge">ports</code>.</li>
  <li><strong>Use health checks</strong> plus <code class="language-plaintext highlighter-rouge">condition: service_healthy</code> for anything with a slow start, like databases.</li>
  <li><strong>Treat <code class="language-plaintext highlighter-rouge">down -v</code> as a delete command</strong>, because it is one.</li>
  <li><strong>Commit <code class="language-plaintext highlighter-rouge">compose.yml</code></strong>, and keep secrets in <code class="language-plaintext highlighter-rouge">.env</code> / <code class="language-plaintext highlighter-rouge">env_file</code> files that aren’t committed.</li>
</ul>

<p><a href="/portfolio-site/blog/2025/07/16/chapter-1-10-docker-machine/">Chapter 1.10</a> takes these same commands to other machines: managing remote Docker hosts from your laptop with Docker contexts.</p>]]></content><author><name>Echo Yin</name></author><category term="devops" /><category term="Platform Engineering" /><category term="DevOps" /><category term="Chapter One" /><category term="Docker" /><summary type="html"><![CDATA[Replace pages of docker run commands with one compose.yml: a proxy, an app and Redis wired together by name, health-checked startup order, scaling, a live-reload development loop, environment files and profiles. Every key in the file is explained.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://e-choness.github.io/portfolio-site/assets/images/blogs/docker-compose.webp" /><media:content medium="image" url="https://e-choness.github.io/portfolio-site/assets/images/blogs/docker-compose.webp" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Chapter 1.7 - Redis in Docker: Persistence, Memory Limits and Safe Upgrades</title><link href="https://e-choness.github.io/portfolio-site/blog/2025/07/14/chapter-1-7-docker-redis/" rel="alternate" type="text/html" title="Chapter 1.7 - Redis in Docker: Persistence, Memory Limits and Safe Upgrades" /><published>2025-07-14T00:00:00+00:00</published><updated>2025-07-14T00:00:00+00:00</updated><id>https://e-choness.github.io/portfolio-site/blog/2025/07/14/chapter-1-7-docker-redis</id><content type="html" xml:base="https://e-choness.github.io/portfolio-site/blog/2025/07/14/chapter-1-7-docker-redis/"><![CDATA[<p>Redis is the Swiss-army knife next to most applications: a cache, a session store, a rate limiter, a job queue. It’s also deceptively easy to run badly. The defaults are tuned for a developer laptop, and a Redis instance exposed to the internet without a password is still one of the most commonly exploited services.</p>

<p>This chapter sets it up properly: a config file you understand, data on a volume, memory that can’t run away, and an upgrade path.</p>

<h2 id="first-decide-what-this-redis-is-for">First, decide what this Redis is for</h2>

<p>Two settings follow from that one decision: <strong>persistence</strong> and <strong>what happens when memory fills up</strong>.</p>

<table>
  <thead>
    <tr>
      <th>Use</th>
      <th>Persistence</th>
      <th>When memory is full</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong>Cache</strong> (data can be rebuilt from the database)</td>
      <td>none, or snapshots only</td>
      <td>evict old keys: <code class="language-plaintext highlighter-rouge">allkeys-lru</code></td>
    </tr>
    <tr>
      <td><strong>Sessions, rate limits</strong> (losing them is annoying, not fatal)</td>
      <td>snapshots (RDB)</td>
      <td><code class="language-plaintext highlighter-rouge">volatile-lru</code>, evicting keys that have a TTL</td>
    </tr>
    <tr>
      <td><strong>Queues, source-of-truth data</strong></td>
      <td>append-only file (AOF), ideally plus RDB</td>
      <td><code class="language-plaintext highlighter-rouge">noeviction</code>: reject writes rather than silently lose data</td>
    </tr>
  </tbody>
</table>

<p>The two persistence mechanisms:</p>

<ul>
  <li><strong>RDB snapshots</strong>: Redis periodically forks and writes the whole dataset to <code class="language-plaintext highlighter-rouge">dump.rdb</code>. Compact and fast to restart from, but you lose whatever changed since the last snapshot.</li>
  <li><strong>AOF (append-only file)</strong>: every write is appended to a log. With <code class="language-plaintext highlighter-rouge">appendfsync everysec</code> you lose at most about a second of writes on a crash. Files are larger, and Redis compacts them in the background.</li>
</ul>

<h2 id="quick-start-for-development">Quick start for development</h2>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker run <span class="nt">-d</span> <span class="nt">--name</span> redis-dev <span class="nt">-p</span> 127.0.0.1:6379:6379 redis:8.0
docker <span class="nb">exec</span> <span class="nt">-it</span> redis-dev redis-cli ping      <span class="c"># PONG</span>
</code></pre></div></div>

<p>Fine on a laptop, and deliberately bound to <code class="language-plaintext highlighter-rouge">127.0.0.1</code>. Everything below is about running it for real.</p>

<h2 id="a-production-configuration">A production configuration</h2>

<p>The official image ships <strong>without</strong> a config file (Redis runs on built-in defaults), so download the annotated example for your version and keep it next to your deployment:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">mkdir</span> <span class="nt">-p</span> ~/redis/conf
curl <span class="nt">-fsSL</span> <span class="nt">-o</span> ~/redis/conf/redis.conf <span class="se">\</span>
  https://raw.githubusercontent.com/redis/redis/8.0/redis.conf
</code></pre></div></div>

<p>It’s long and heavily commented, which makes it good documentation. These are the lines to change (they already exist in the file; edit them in place rather than appending duplicates):</p>

<div class="language-ini highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># --- Network ---------------------------------------------------------------
</span><span class="na">bind</span><span class="w"> </span><span class="na">0.0.0.0</span><span class="w"> </span><span class="na">-::</span><span class="w">
</span><span class="na">protected-mode</span><span class="w"> </span><span class="na">yes</span><span class="w">
</span><span class="na">port</span><span class="w"> </span><span class="na">6379</span><span class="w">

</span><span class="c"># --- Auth ------------------------------------------------------------------
</span><span class="na">requirepass</span><span class="w"> </span><span class="na">use-a-long-random-password</span><span class="w">

</span><span class="c"># --- Persistence -----------------------------------------------------------
</span><span class="na">dir</span><span class="w"> </span><span class="na">/data</span><span class="w">
</span><span class="na">appendonly</span><span class="w"> </span><span class="na">yes</span><span class="w">
</span><span class="na">appendfsync</span><span class="w"> </span><span class="na">everysec</span><span class="w">
</span><span class="na">save</span><span class="w"> </span><span class="na">3600</span><span class="w"> </span><span class="na">1</span><span class="w"> </span><span class="na">300</span><span class="w"> </span><span class="na">100</span><span class="w"> </span><span class="na">60</span><span class="w"> </span><span class="na">10000</span><span class="w">

</span><span class="c"># --- Memory ----------------------------------------------------------------
</span><span class="na">maxmemory</span><span class="w"> </span><span class="na">512mb</span><span class="w">
</span><span class="na">maxmemory-policy</span><span class="w"> </span><span class="na">noeviction</span><span class="w">
</span></code></pre></div></div>

<p>Section by section:</p>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">bind 0.0.0.0 -::</code></strong>: listen on all interfaces <em>inside the container</em>. The example file binds <code class="language-plaintext highlighter-rouge">127.0.0.1</code>, which inside a container means only the container itself can connect: your published port and your app containers would all get “connection refused”. The <code class="language-plaintext highlighter-rouge">-</code> before <code class="language-plaintext highlighter-rouge">::</code> means “don’t fail if IPv6 isn’t available”.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">protected-mode yes</code></strong>: refuse remote connections unless a password is set. With <code class="language-plaintext highlighter-rouge">requirepass</code> configured it no longer blocks anything, but it’s a safety net if the password line is ever removed.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">requirepass</code></strong>: clients must <code class="language-plaintext highlighter-rouge">AUTH</code> first. Use a long random value (<code class="language-plaintext highlighter-rouge">openssl rand -base64 32</code>). For several apps with different permissions, Redis 6+ ACLs (<code class="language-plaintext highlighter-rouge">user … on &gt;password ~keys:* +@read</code>) are the finer-grained option.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">dir /data</code></strong>: where snapshots and the AOF are written. We’ll mount a volume there.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">appendonly yes</code> + <code class="language-plaintext highlighter-rouge">appendfsync everysec</code></strong>: turn on the AOF and flush it to disk once a second; this is the queue/source-of-truth profile from the table above. For a pure cache, set <code class="language-plaintext highlighter-rouge">appendonly no</code>.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">save 3600 1 300 100 60 10000</code></strong>: RDB snapshot rules, read in pairs: after 3600 s if at least 1 key changed, after 300 s if 100 changed, after 60 s if 10,000 changed. <code class="language-plaintext highlighter-rouge">save ""</code> disables snapshots.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">maxmemory 512mb</code></strong>: the ceiling for data. Without it, Redis grows until the container’s memory limit (or the kernel) kills it.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">maxmemory-policy noeviction</code></strong>: when full, reject writes with an error. A cache would use <code class="language-plaintext highlighter-rouge">allkeys-lru</code> here instead, evicting the least recently used keys.</li>
</ul>

<h2 id="running-it">Running it</h2>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker network create backend

docker run <span class="nt">-d</span> <span class="nt">--name</span> redis <span class="se">\</span>
  <span class="nt">--network</span> backend <span class="se">\</span>
  <span class="nt">--restart</span> unless-stopped <span class="se">\</span>
  <span class="nt">--memory</span> 768m <span class="se">\</span>
  <span class="nt">-p</span> 127.0.0.1:6379:6379 <span class="se">\</span>
  <span class="nt">-v</span> redis_data:/data <span class="se">\</span>
  <span class="nt">-v</span> ~/redis/conf/redis.conf:/usr/local/etc/redis/redis.conf:ro <span class="se">\</span>
  redis:8.0 redis-server /usr/local/etc/redis/redis.conf
</code></pre></div></div>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">--network backend</code></strong>: app containers on the same network connect to <code class="language-plaintext highlighter-rouge">redis:6379</code>.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">--memory 768m</code></strong>: the container’s hard limit, deliberately larger than <code class="language-plaintext highlighter-rouge">maxmemory</code> (512 MB). Redis needs headroom beyond the data itself: connection buffers, and the fork that writes RDB snapshots and rewrites the AOF, which can briefly need extra memory for pages being modified.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">-p 127.0.0.1:6379:6379</code></strong>: reachable from the host for <code class="language-plaintext highlighter-rouge">redis-cli</code>, not from the network. Omit it if only containers use Redis.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">-v redis_data:/data</code></strong>: persistence files live in a named volume.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">-v …redis.conf:/usr/local/etc/redis/redis.conf:ro</code></strong>: your config, read-only. The path inside the container is your choice; it just has to match the next argument.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">redis-server /usr/local/etc/redis/redis.conf</code></strong>: replace the image’s default command so Redis starts with that file.</li>
</ul>

<p>Check it (the examples from here on assume the password is in a shell variable, for example <code class="language-plaintext highlighter-rouge">read -rs REDIS_PASSWORD</code>, which reads it without echoing):</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker <span class="nb">exec</span> <span class="nt">-it</span> <span class="nt">-e</span> <span class="nv">REDISCLI_AUTH</span><span class="o">=</span><span class="s2">"</span><span class="nv">$REDIS_PASSWORD</span><span class="s2">"</span> redis redis-cli
127.0.0.1:6379&gt; INFO persistence
127.0.0.1:6379&gt; CONFIG GET maxmemory<span class="k">*</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">REDISCLI_AUTH</code> passes the password through the environment instead of <code class="language-plaintext highlighter-rouge">-a</code>, which would show it in the process list and prints a warning.</p>

<p>Most settings can be changed live (<code class="language-plaintext highlighter-rouge">CONFIG SET maxmemory 1gb</code>) and written back to the file with <code class="language-plaintext highlighter-rouge">CONFIG REWRITE</code>. With the file mounted read-only, that write fails on purpose: edit the host file and <code class="language-plaintext highlighter-rouge">docker restart redis</code> instead, so the file on the host stays the source of truth.</p>

<h2 id="backups">Backups</h2>

<p>Everything Redis persists is in the volume: <code class="language-plaintext highlighter-rouge">dump.rdb</code> and, with AOF on, the <code class="language-plaintext highlighter-rouge">appendonlydir/</code> directory (Redis 7+ splits the AOF into several files plus a manifest). To take a consistent copy:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker <span class="nb">exec</span> <span class="nt">-e</span> <span class="nv">REDISCLI_AUTH</span><span class="o">=</span><span class="s2">"</span><span class="nv">$REDIS_PASSWORD</span><span class="s2">"</span> redis redis-cli BGSAVE
docker <span class="nb">exec</span> <span class="nt">-e</span> <span class="nv">REDISCLI_AUTH</span><span class="o">=</span><span class="s2">"</span><span class="nv">$REDIS_PASSWORD</span><span class="s2">"</span> redis redis-cli LASTSAVE      <span class="c"># repeat until the timestamp changes</span>
docker run <span class="nt">--rm</span> <span class="nt">-v</span> redis_data:/data <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$PWD</span><span class="s2">"</span>:/backup alpine <span class="se">\</span>
  <span class="nb">tar </span>czf <span class="s2">"/backup/redis-</span><span class="si">$(</span><span class="nb">date</span> +%F<span class="si">)</span><span class="s2">.tgz"</span> <span class="nt">-C</span> /data <span class="nb">.</span>
</code></pre></div></div>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">BGSAVE</code></strong>: write a fresh snapshot in the background, without blocking clients.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">LASTSAVE</code></strong>: the Unix time of the last successful save; when it changes, the snapshot is complete.</li>
  <li><strong>The <code class="language-plaintext highlighter-rouge">alpine</code> container</strong>: a throwaway container that mounts the same volume and your current directory, then archives the volume’s contents. This is the general-purpose way to back up any named volume.</li>
</ul>

<h2 id="upgrading">Upgrading</h2>

<p>Newer Redis versions read older RDB and AOF files, but not the other way round. So the plan is: keep the old container around until the new one has proven itself, and have a backup for the moment you can’t go back.</p>

<pre><code class="language-mermaid">flowchart LR
  subgraph prep["Prepare"]
    direction TB
    A[Back up /data] --&gt; B[docker pull redis:8.0.3]
    B --&gt; C[docker stop redis]
    C --&gt; D[docker rename redis redis-old]
    D --&gt; E[Compare redis.conf with the&lt;br/&gt;new version's example file]
  end
  subgraph swap["Swap and verify"]
    direction TB
    F[docker run new container&lt;br/&gt;same volume and config] --&gt; G{Version, DBSIZE&lt;br/&gt;and app checks OK?}
    G -- yes --&gt; H[docker rm redis-old]
    G -- no --&gt; I[Stop the new container, restore&lt;br/&gt;the backup into the volume]
    I --&gt; J[docker start redis-old]
  end
  prep --&gt; swap
</code></pre>

<p>Checks after the switch:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker <span class="nb">exec</span> <span class="nt">-e</span> <span class="nv">REDISCLI_AUTH</span><span class="o">=</span><span class="s2">"</span><span class="nv">$REDIS_PASSWORD</span><span class="s2">"</span> redis redis-cli INFO server | <span class="nb">grep </span>redis_version
docker <span class="nb">exec</span> <span class="nt">-e</span> <span class="nv">REDISCLI_AUTH</span><span class="o">=</span><span class="s2">"</span><span class="nv">$REDIS_PASSWORD</span><span class="s2">"</span> redis redis-cli DBSIZE
</code></pre></div></div>

<p>Compare <code class="language-plaintext highlighter-rouge">DBSIZE</code> with the number before the upgrade. Resist <code class="language-plaintext highlighter-rouge">KEYS *</code> on a real instance: it walks the entire keyspace in one blocking call and freezes every client until it finishes. <code class="language-plaintext highlighter-rouge">SCAN</code> gives you a sample without blocking.</p>

<p>Before a major version jump, diff your <code class="language-plaintext highlighter-rouge">redis.conf</code> against the new version’s example file: directives do get renamed or removed, and Redis refuses to start on an unknown directive, which is at least an easy failure to spot.</p>

<h2 id="a-note-on-licensing">A note on licensing</h2>

<p>Redis changed its license in 2024 (to RSALv2/SSPL) and added AGPLv3 as an option with Redis 8. For most teams running it internally this changes nothing, but if you offer Redis as a service or redistribute it, check the terms. <strong>Valkey</strong>, a Linux Foundation fork of Redis 7.2, remains BSD-licensed, is a drop-in replacement for the commands above (<code class="language-plaintext highlighter-rouge">valkey/valkey</code> image, <code class="language-plaintext highlighter-rouge">valkey-cli</code>), and is what several cloud providers now offer.</p>

<h2 id="checklist">Checklist</h2>

<ul>
  <li>Password (or ACLs) set, and the port never published to the internet.</li>
  <li><code class="language-plaintext highlighter-rouge">bind 0.0.0.0</code> inside the container, so containers and published ports can actually reach it.</li>
  <li>Persistence chosen deliberately: none for caches, AOF for anything you can’t lose.</li>
  <li><code class="language-plaintext highlighter-rouge">maxmemory</code> set, with the container limit comfortably above it.</li>
  <li>The volume backed up after a <code class="language-plaintext highlighter-rouge">BGSAVE</code>; upgrades keep the old container until verified.</li>
</ul>

<p><a href="/portfolio-site/blog/2025/07/14/chapter-1-8-docker-network/">Chapter 1.8</a> looks at what has been connecting all these containers: Docker’s network modes.</p>]]></content><author><name>Echo Yin</name></author><category term="devops" /><category term="Platform Engineering" /><category term="DevOps" /><category term="Chapter One" /><category term="Docker" /><summary type="html"><![CDATA[Run Redis in a container with a configuration you understand: which persistence mode fits a cache versus a queue, why the stock config file makes a published port unreachable, memory limits and eviction, passwords, backups, and an upgrade you can roll back.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://e-choness.github.io/portfolio-site/assets/images/blogs/docker-redis.webp" /><media:content medium="image" url="https://e-choness.github.io/portfolio-site/assets/images/blogs/docker-redis.webp" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Chapter 1.8 - Docker Networking: Bridge, User-Defined Networks, Host, Container and None</title><link href="https://e-choness.github.io/portfolio-site/blog/2025/07/14/chapter-1-8-docker-network/" rel="alternate" type="text/html" title="Chapter 1.8 - Docker Networking: Bridge, User-Defined Networks, Host, Container and None" /><published>2025-07-14T00:00:00+00:00</published><updated>2025-07-14T00:00:00+00:00</updated><id>https://e-choness.github.io/portfolio-site/blog/2025/07/14/chapter-1-8-docker-network</id><content type="html" xml:base="https://e-choness.github.io/portfolio-site/blog/2025/07/14/chapter-1-8-docker-network/"><![CDATA[<p>Every chapter so far has quietly relied on networking: Nginx reaching <code class="language-plaintext highlighter-rouge">app:3000</code>, an API connecting to <code class="language-plaintext highlighter-rouge">mysql:3306</code>. This chapter opens that up: how a container gets an address, how names resolve, what publishing a port really does, and when to pick each network mode.</p>

<table>
  <thead>
    <tr>
      <th>Mode</th>
      <th>What the container gets</th>
      <th>Typical use</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong>default <code class="language-plaintext highlighter-rouge">bridge</code></strong></td>
      <td>its own IP on a private network; no name resolution</td>
      <td>quick one-off containers</td>
    </tr>
    <tr>
      <td><strong>user-defined bridge</strong></td>
      <td>its own IP, <strong>DNS by container name</strong>, isolation per network</td>
      <td>almost everything on one host</td>
    </tr>
    <tr>
      <td><strong><code class="language-plaintext highlighter-rouge">host</code></strong></td>
      <td>no network isolation; shares the host’s interfaces</td>
      <td>network tools, extreme performance needs (Linux only)</td>
    </tr>
    <tr>
      <td><strong><code class="language-plaintext highlighter-rouge">container:&lt;name&gt;</code></strong></td>
      <td>shares another container’s network stack</td>
      <td>sidecars, debugging</td>
    </tr>
    <tr>
      <td><strong><code class="language-plaintext highlighter-rouge">none</code></strong></td>
      <td>only a loopback interface</td>
      <td>jobs that must have no network</td>
    </tr>
  </tbody>
</table>

<p>(<code class="language-plaintext highlighter-rouge">overlay</code> for multi-host clusters appears in <a href="/portfolio-site/blog/2025/07/17/chapter-1-11-docker-swarm/">Chapter 1.11</a>; <code class="language-plaintext highlighter-rouge">macvlan</code>, which puts containers directly on your LAN, is for special cases.)</p>

<h2 id="the-default-bridge-how-it-works">The default bridge: how it works</h2>

<p>When Docker starts, it creates a virtual switch called <strong><code class="language-plaintext highlighter-rouge">docker0</code></strong> on the host, with a private subnet, <code class="language-plaintext highlighter-rouge">172.17.0.0/16</code> by default. Each container started without <code class="language-plaintext highlighter-rouge">--network</code> is plugged into it:</p>

<pre><code class="language-mermaid">flowchart TB
    subgraph HOST["host"]
        direction TB
        subgraph D1["container 1"]
            D1ETH["eth0&lt;br/&gt;172.17.0.2/16"]
        end
        subgraph D2["container 2"]
            D2ETH["eth0&lt;br/&gt;172.17.0.3/16"]
        end
        subgraph NET["docker0 bridge"]
            V1["veth…"]
            V2["veth…"]
            DOCKER0["docker0&lt;br/&gt;172.17.0.1/16 (gateway)"]
        end
        ETH0["host eth0&lt;br/&gt;10.11.55.5/24"]
        D1ETH &lt;--&gt;|"veth pair"| V1
        D2ETH &lt;--&gt;|"veth pair"| V2
        V1 --&gt; DOCKER0
        V2 --&gt; DOCKER0
        DOCKER0 --&gt;|"NAT (masquerade)"| ETH0
    end
</code></pre>

<ul>
  <li>Each container gets a <strong>veth pair</strong>: a virtual cable with one end inside the container (appearing as <code class="language-plaintext highlighter-rouge">eth0</code>) and the other end on the host, plugged into <code class="language-plaintext highlighter-rouge">docker0</code>.</li>
  <li>The container’s default gateway is <code class="language-plaintext highlighter-rouge">docker0</code> itself, <code class="language-plaintext highlighter-rouge">172.17.0.1</code>.</li>
  <li>Outbound traffic is <strong>NATed</strong> through the host’s real interface, so the internet sees the host’s IP.</li>
</ul>

<p>See it for yourself:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker run <span class="nt">-d</span> <span class="nt">--name</span> b1 alpine <span class="nb">sleep </span>3600
docker run <span class="nt">-d</span> <span class="nt">--name</span> b2 alpine <span class="nb">sleep </span>3600
docker <span class="nb">exec </span>b1 ip addr show eth0       <span class="c"># 172.17.0.2</span>
docker <span class="nb">exec </span>b1 ip route                <span class="c"># default via 172.17.0.1</span>
docker <span class="nb">exec </span>b1 ping <span class="nt">-c</span> 2 172.17.0.3    <span class="c"># works by IP…</span>
docker <span class="nb">exec </span>b1 ping <span class="nt">-c</span> 2 b2            <span class="c"># …but not by name: "bad address 'b2'"</span>
</code></pre></div></div>

<p>That last line is the default bridge’s big limitation: <strong>no DNS between containers</strong>. It exists mainly for backward compatibility. For anything with more than one container, use a user-defined network.</p>

<h3 id="what--p-actually-does">What <code class="language-plaintext highlighter-rouge">-p</code> actually does</h3>

<p>Publishing a port (<code class="language-plaintext highlighter-rouge">-p 8080:80</code>) makes Docker add NAT rules to the host’s firewall (iptables or nftables): traffic arriving at host port 8080 is rewritten to the container’s IP and port 80. You can see them with <code class="language-plaintext highlighter-rouge">sudo iptables -t nat -L DOCKER -n</code>.</p>

<p>This has a consequence that surprises many people: <strong>those rules sit in front of host firewalls like <code class="language-plaintext highlighter-rouge">ufw</code> and firewalld.</strong> <code class="language-plaintext highlighter-rouge">ufw deny 8080</code> does <em>not</em> block a port Docker has published; the traffic is NATed to the container before <code class="language-plaintext highlighter-rouge">ufw</code>’s rules ever see it. So:</p>

<ul>
  <li>Publish only what must be reachable from outside.</li>
  <li>Bind to a specific address when you only need local access: <code class="language-plaintext highlighter-rouge">-p 127.0.0.1:8080:80</code>.</li>
  <li>For containers that only talk to each other, don’t publish at all. They don’t need it on a shared network.</li>
</ul>

<h2 id="user-defined-bridge-networks-the-one-youll-use">User-defined bridge networks: the one you’ll use</h2>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker network create backend
docker run <span class="nt">-d</span> <span class="nt">--name</span> api   <span class="nt">--network</span> backend alpine <span class="nb">sleep </span>3600
docker run <span class="nt">-d</span> <span class="nt">--name</span> cache <span class="nt">--network</span> backend alpine <span class="nb">sleep </span>3600
docker <span class="nb">exec </span>api ping <span class="nt">-c</span> 2 cache
<span class="c"># PING cache (172.19.0.3): 56 data bytes</span>
<span class="c"># 64 bytes from 172.19.0.3: seq=0 ttl=64 time=0.081 ms</span>
</code></pre></div></div>

<p>What you gain over the default bridge:</p>

<ul>
  <li><strong>DNS by container name.</strong> Docker runs an embedded DNS server (at <code class="language-plaintext highlighter-rouge">127.0.0.11</code> inside each container) that resolves container names, and network aliases, to their current IPs. IPs change when containers are recreated; names don’t. That’s why connection strings use <code class="language-plaintext highlighter-rouge">mysql:3306</code>, never an IP.</li>
  <li><strong>Isolation between networks.</strong> Containers on different user-defined networks can’t reach each other at all, which gives you a simple way to separate tiers.</li>
  <li><strong>Live attach and detach.</strong> <code class="language-plaintext highlighter-rouge">docker network connect</code> / <code class="language-plaintext highlighter-rouge">disconnect</code> changes a running container’s networks without restarting it.</li>
</ul>

<h3 id="isolating-tiers">Isolating tiers</h3>

<p>A container can be on several networks at once. That lets you build a front door that only the proxy passes through:</p>

<pre><code class="language-mermaid">flowchart TD
  u([Internet]) -- ":443 published" --&gt; proxy
  subgraph FE["network: frontend"]
    proxy[nginx]
    api1[api]
  end
  subgraph BE["network: backend"]
    api2[api]
    db[(mysql)]
    cache[(redis)]
  end
  proxy --&gt; api1
  api1 -. "same container,&lt;br/&gt;on both networks" .- api2
  api2 --&gt; db
  api2 --&gt; cache
</code></pre>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker network create frontend
docker network create backend

docker run <span class="nt">-d</span> <span class="nt">--name</span> db    <span class="nt">--network</span> backend  <span class="nt">-e</span> <span class="nv">MYSQL_ROOT_PASSWORD</span><span class="o">=</span>… mysql:8.4
docker run <span class="nt">-d</span> <span class="nt">--name</span> api   <span class="nt">--network</span> backend  yourname/api:1.4.2
docker network connect frontend api
docker run <span class="nt">-d</span> <span class="nt">--name</span> proxy <span class="nt">--network</span> frontend <span class="nt">-p</span> 443:443 nginx:1.27
</code></pre></div></div>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">api</code></strong> is on both networks: Nginx can reach it, and it can reach the database.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">proxy</code></strong> is only on <code class="language-plaintext highlighter-rouge">frontend</code>: even if Nginx is compromised, <code class="language-plaintext highlighter-rouge">db</code> isn’t resolvable or routable from it.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">db</code></strong> publishes no port and sits only on <code class="language-plaintext highlighter-rouge">backend</code>: the only way in is through <code class="language-plaintext highlighter-rouge">api</code>.</li>
</ul>

<p>Compose (<a href="/portfolio-site/blog/2025/07/16/chapter-1-9-docker-compose/">Chapter 1.9</a>) creates a network like this for every project automatically, which is why services in a Compose file can reach each other by service name with no setup.</p>

<h3 id="inspecting-networks">Inspecting networks</h3>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker network <span class="nb">ls</span>                                  <span class="c"># all networks</span>
docker network inspect backend                     <span class="c"># subnet, gateway, and every attached container with its IP</span>
docker inspect <span class="nt">-f</span> <span class="s1">'{{range $k, $v := .NetworkSettings.Networks}}{{$k}}={{$v.IPAddress}} {{end}}'</span> api
</code></pre></div></div>

<p>The last command prints every network the <code class="language-plaintext highlighter-rouge">api</code> container is on, with its IP on each: <code class="language-plaintext highlighter-rouge">backend=172.19.0.3 frontend=172.20.0.2</code>.</p>

<h2 id="host-mode-no-network-isolation">Host mode: no network isolation</h2>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker run <span class="nt">-d</span> <span class="nt">--name</span> h1 <span class="nt">--network</span> host nginx:1.27
curl <span class="nt">-I</span> http://localhost:80        <span class="c"># served directly on the host's port 80, no -p needed</span>
</code></pre></div></div>

<p>The container skips network namespacing entirely: it sees the host’s interfaces and binds straight to the host’s ports. Filesystem, processes and users are still isolated.</p>

<pre><code class="language-mermaid">flowchart TB
    subgraph HOST["host network namespace"]
        direction TB
        n1["nginx (container)&lt;br/&gt;listening on :80"]
        n2["node_exporter (container)&lt;br/&gt;listening on :9100"]
        ETH0["eth0&lt;br/&gt;10.11.55.5/24"]
        n1 --- ETH0
        n2 --- ETH0
    end
</code></pre>

<p>Use it for tools that need to see the host’s real network (monitoring agents, packet capture) or when NAT overhead genuinely matters at very high packet rates. The costs:</p>

<ul>
  <li><strong>Port conflicts are back.</strong> Two host-mode containers can’t both listen on 80, and neither can a host process.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">-p</code> is ignored</strong>, since there’s nothing to publish.</li>
  <li><strong>It’s a Linux feature.</strong> On Docker Desktop, the “host” is the Desktop’s Linux VM, so a host-mode container shares the VM’s network, not your laptop’s, unless you turn on the newer host networking option in Desktop’s settings.</li>
</ul>

<h2 id="container-mode-sharing-another-containers-network">Container mode: sharing another container’s network</h2>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker run <span class="nt">-d</span> <span class="nt">--name</span> web nginx:1.27
docker run <span class="nt">-it</span> <span class="nt">--rm</span> <span class="nt">--network</span> container:web alpine sh
/ <span class="c"># wget -qO- http://localhost        # that's nginx, in the other container</span>
</code></pre></div></div>

<p>The second container joins the first one’s network namespace: same interfaces, same IP, same <code class="language-plaintext highlighter-rouge">localhost</code>, same port space. Filesystems and processes stay separate.</p>

<pre><code class="language-mermaid">flowchart LR
  subgraph NS["one network namespace (web's)"]
    web[nginx container]
    side[helper container]
    lo(["localhost / eth0 172.19.0.4"])
    web --- lo
    side --- lo
  end
</code></pre>

<p>This is the <strong>sidecar</strong> pattern (Kubernetes pods work exactly this way): a log shipper, a proxy or a metrics exporter that talks to the main app over <code class="language-plaintext highlighter-rouge">localhost</code>. It’s also the best debugging trick for minimal images that ship no tools: attach a <code class="language-plaintext highlighter-rouge">busybox</code> or <code class="language-plaintext highlighter-rouge">nicolaka/netshoot</code> container to the target’s network and use its <code class="language-plaintext highlighter-rouge">curl</code>, <code class="language-plaintext highlighter-rouge">dig</code> and <code class="language-plaintext highlighter-rouge">tcpdump</code> as if you were inside.</p>

<h2 id="none-no-network-at-all">None: no network at all</h2>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker run <span class="nt">--rm</span> <span class="nt">--network</span> none alpine ip addr
<span class="c"># 1: lo: &lt;LOOPBACK,UP,LOWER_UP&gt; …    (nothing else)</span>
</code></pre></div></div>

<pre><code class="language-mermaid">flowchart TB
    subgraph HOST["host"]
        direction TB
        subgraph C["container (own network namespace)"]
            LO["lo&lt;br/&gt;127.0.0.1"]
        end
        DOCKER0["docker0"]
        ETH0["eth0"]
        DOCKER0 --- ETH0
    end
</code></pre>

<p>Only a loopback interface, and nothing connects it to <code class="language-plaintext highlighter-rouge">docker0</code> or the host. It’s useful for jobs that process untrusted input and must not exfiltrate anything, such as file converters, or batch jobs that read and write mounted volumes only.</p>

<h2 id="troubleshooting">Troubleshooting</h2>

<table>
  <thead>
    <tr>
      <th>Symptom</th>
      <th>Check</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Name doesn’t resolve (<code class="language-plaintext highlighter-rouge">bad address</code>)</td>
      <td>Both containers on the same <strong>user-defined</strong> network? <code class="language-plaintext highlighter-rouge">docker network inspect &lt;net&gt;</code>.</td>
    </tr>
    <tr>
      <td>Connection refused between containers</td>
      <td>The service listens on <code class="language-plaintext highlighter-rouge">127.0.0.1</code> inside its container; it must listen on <code class="language-plaintext highlighter-rouge">0.0.0.0</code> to be reachable from others.</td>
    </tr>
    <tr>
      <td>Port reachable from the internet despite <code class="language-plaintext highlighter-rouge">ufw</code></td>
      <td>Docker’s NAT rules bypass it; bind to <code class="language-plaintext highlighter-rouge">127.0.0.1</code> or don’t publish.</td>
    </tr>
    <tr>
      <td>Container can’t reach the internet</td>
      <td><code class="language-plaintext highlighter-rouge">docker exec c ping -c1 1.1.1.1</code> (routing) vs <code class="language-plaintext highlighter-rouge">ping google.com</code> (DNS); check the host’s IP forwarding and the daemon’s <code class="language-plaintext highlighter-rouge">dns</code> setting.</td>
    </tr>
    <tr>
      <td>Subnet clashes with your VPN or office LAN</td>
      <td>Pick other ranges with <code class="language-plaintext highlighter-rouge">"default-address-pools"</code> in <code class="language-plaintext highlighter-rouge">/etc/docker/daemon.json</code>.</td>
    </tr>
  </tbody>
</table>

<p>The “listens on <code class="language-plaintext highlighter-rouge">127.0.0.1</code>” row catches almost everyone once: a dev server bound to localhost works inside its own container and nowhere else.</p>

<p><a href="/portfolio-site/blog/2025/07/16/chapter-1-9-docker-compose/">Chapter 1.9</a> stops typing long <code class="language-plaintext highlighter-rouge">docker run</code> and <code class="language-plaintext highlighter-rouge">docker network</code> commands and describes whole multi-container applications in one file.</p>]]></content><author><name>Echo Yin</name></author><category term="devops" /><category term="Platform Engineering" /><category term="DevOps" /><category term="Chapter One" /><category term="Docker" /><summary type="html"><![CDATA[How containers actually get an IP address, find each other by name and reach the outside world, and when to use each of Docker's network modes. Includes a frontend/backend isolation setup, what -p really does to your firewall, and hands-on checks for each mode.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://e-choness.github.io/portfolio-site/assets/images/blogs/docker-network.webp" /><media:content medium="image" url="https://e-choness.github.io/portfolio-site/assets/images/blogs/docker-network.webp" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Chapter 1.5 - Self-Hosted GitLab in Docker: Setup, Runners, Backups and Upgrades</title><link href="https://e-choness.github.io/portfolio-site/blog/2025/07/13/chapter-1-5-docker-gitlab/" rel="alternate" type="text/html" title="Chapter 1.5 - Self-Hosted GitLab in Docker: Setup, Runners, Backups and Upgrades" /><published>2025-07-13T00:00:00+00:00</published><updated>2025-07-13T00:00:00+00:00</updated><id>https://e-choness.github.io/portfolio-site/blog/2025/07/13/chapter-1-5-docker-gitlab</id><content type="html" xml:base="https://e-choness.github.io/portfolio-site/blog/2025/07/13/chapter-1-5-docker-gitlab/"><![CDATA[<p>GitLab bundles Git hosting, merge requests, CI/CD and a container registry into one application. The official <code class="language-plaintext highlighter-rouge">gitlab/gitlab-ce</code> image packages all of it (Rails, PostgreSQL, Redis, Gitaly, Nginx) into a single container, which makes it the easiest way to self-host.</p>

<p>Plan for resources: GitLab needs <strong>at least 4 GB of RAM, and 8 GB to be comfortable</strong>, plus a few CPU cores. On less than that it starts, then swaps itself to a standstill.</p>

<h2 id="1-run-gitlab-with-compose">1. Run GitLab with Compose</h2>

<p>Create a directory for it and a <code class="language-plaintext highlighter-rouge">compose.yml</code>:</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">services</span><span class="pi">:</span>
  <span class="na">gitlab</span><span class="pi">:</span>
    <span class="na">image</span><span class="pi">:</span> <span class="s">gitlab/gitlab-ce:18.2.1-ce.0</span>
    <span class="na">container_name</span><span class="pi">:</span> <span class="s">gitlab</span>
    <span class="na">hostname</span><span class="pi">:</span> <span class="s">gitlab.example.com</span>
    <span class="na">restart</span><span class="pi">:</span> <span class="s">unless-stopped</span>
    <span class="na">shm_size</span><span class="pi">:</span> <span class="s2">"</span><span class="s">256m"</span>
    <span class="na">ports</span><span class="pi">:</span>
      <span class="pi">-</span> <span class="s2">"</span><span class="s">80:80"</span>
      <span class="pi">-</span> <span class="s2">"</span><span class="s">443:443"</span>
      <span class="pi">-</span> <span class="s2">"</span><span class="s">2222:22"</span>
    <span class="na">environment</span><span class="pi">:</span>
      <span class="na">GITLAB_OMNIBUS_CONFIG</span><span class="pi">:</span> <span class="pi">|</span>
        <span class="s">external_url 'https://gitlab.example.com'</span>
        <span class="s">gitlab_rails['gitlab_shell_ssh_port'] = 2222</span>
        <span class="s">gitlab_rails['time_zone'] = 'America/Edmonton'</span>
        <span class="s">gitlab_rails['backup_keep_time'] = 604800</span>
        <span class="s">registry_external_url 'https://registry.example.com'</span>
    <span class="na">volumes</span><span class="pi">:</span>
      <span class="pi">-</span> <span class="s">./config:/etc/gitlab</span>
      <span class="pi">-</span> <span class="s">./logs:/var/log/gitlab</span>
      <span class="pi">-</span> <span class="s">./data:/var/opt/gitlab</span>
</code></pre></div></div>

<p>Line by line:</p>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">image: gitlab/gitlab-ce:18.2.1-ce.0</code></strong>: pin an exact version. GitLab upgrades must follow a specific path (section 7), and <code class="language-plaintext highlighter-rouge">latest</code> would jump you across versions on the next pull.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">hostname</code></strong>: the container’s own hostname; GitLab uses it in a few generated places.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">shm_size: "256m"</code></strong>: GitLab’s metrics exporter uses shared memory, and Docker’s 64 MB default is too small for it.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">ports</code></strong>: web on 80/443, and GitLab’s SSH on host port <strong>2222</strong>, because the host’s own SSH server already owns 22.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">GITLAB_OMNIBUS_CONFIG</code></strong>: lines of Ruby that GitLab applies as if they were in <code class="language-plaintext highlighter-rouge">gitlab.rb</code>:
    <ul>
      <li><code class="language-plaintext highlighter-rouge">external_url</code>: the address users see. With an <code class="language-plaintext highlighter-rouge">https://</code> URL and a public DNS name, GitLab requests a Let’s Encrypt certificate automatically (it needs port 80 reachable for that).</li>
      <li><code class="language-plaintext highlighter-rouge">gitlab_shell_ssh_port = 2222</code>: tells GitLab that SSH is on 2222, so the clone URLs it shows read <code class="language-plaintext highlighter-rouge">ssh://git@gitlab.example.com:2222/group/project.git</code>. Without this line it displays port 22, and every copied clone command fails.</li>
      <li><code class="language-plaintext highlighter-rouge">time_zone</code>: for timestamps in the UI and in emails.</li>
      <li><code class="language-plaintext highlighter-rouge">backup_keep_time</code>: delete local backups older than 7 days (in seconds).</li>
      <li><code class="language-plaintext highlighter-rouge">registry_external_url</code>: turns on the built-in container registry at its own hostname (section 5).</li>
    </ul>
  </li>
  <li><strong><code class="language-plaintext highlighter-rouge">volumes</code></strong>: the three places GitLab keeps state. <code class="language-plaintext highlighter-rouge">config</code> holds <code class="language-plaintext highlighter-rouge">gitlab.rb</code> and the <strong>secrets</strong>, <code class="language-plaintext highlighter-rouge">logs</code> the logs, and <code class="language-plaintext highlighter-rouge">data</code> repositories, uploads, the database and backups. These bind mounts sit next to <code class="language-plaintext highlighter-rouge">compose.yml</code>, which makes them easy to find and to back up.</li>
</ul>

<p>Start it and watch the first boot, which takes a few minutes:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker compose up <span class="nt">-d</span>
docker compose logs <span class="nt">-f</span> gitlab       <span class="c"># wait until the log settles and the UI answers</span>
</code></pre></div></div>

<p>A <code class="language-plaintext highlighter-rouge">502</code> page during those first minutes is normal: Nginx is up before Rails is.</p>

<p>The first login is <code class="language-plaintext highlighter-rouge">root</code>, with a generated password:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker compose <span class="nb">exec </span>gitlab <span class="nb">cat</span> /etc/gitlab/initial_root_password
</code></pre></div></div>

<p>That file is deleted automatically after 24 hours. Log in and change the password straight away.</p>

<h2 id="2-the-ssh-port-and-the-alternative">2. The SSH port, and the alternative</h2>

<p>With the setup above, users clone with the port in the URL, and GitLab shows exactly that string:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git clone ssh://git@gitlab.example.com:2222/team/api.git
</code></pre></div></div>

<p>If you’d rather have plain <code class="language-plaintext highlighter-rouge">git@gitlab.example.com:team/api.git</code> URLs, GitLab must own port 22 on that address. Either give GitLab its own IP address, or move the host’s SSH server to another port (edit <code class="language-plaintext highlighter-rouge">Port</code> in <code class="language-plaintext highlighter-rouge">/etc/ssh/sshd_config</code>, open the new port in your firewall, <strong>test logging in on it from a second terminal before you close the first</strong>, then restart <code class="language-plaintext highlighter-rouge">sshd</code>). After that, map <code class="language-plaintext highlighter-rouge">"22:22"</code> and drop the <code class="language-plaintext highlighter-rouge">gitlab_shell_ssh_port</code> line.</p>

<h2 id="3-changing-configuration">3. Changing configuration</h2>

<p>Anything in <code class="language-plaintext highlighter-rouge">GITLAB_OMNIBUS_CONFIG</code> is applied on every container start. For settings you’d rather keep in a file, edit <code class="language-plaintext highlighter-rouge">./config/gitlab.rb</code> on the host, then:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker compose <span class="nb">exec </span>gitlab gitlab-ctl reconfigure
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">reconfigure</code> regenerates every component’s configuration from <code class="language-plaintext highlighter-rouge">gitlab.rb</code> and restarts whatever changed. If a setting seems to be ignored, check that it isn’t also set in <code class="language-plaintext highlighter-rouge">GITLAB_OMNIBUS_CONFIG</code>: the environment variable wins.</p>

<h2 id="4-backups-and-the-part-everyone-forgets">4. Backups (and the part everyone forgets)</h2>

<p>GitLab’s backup task dumps the database, repositories and uploads into one tar file under <code class="language-plaintext highlighter-rouge">./data/backups</code>:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker compose <span class="nb">exec </span>gitlab gitlab-backup create
</code></pre></div></div>

<p>That file is <strong>not enough to restore</strong>. The configuration and the encryption secrets live in <code class="language-plaintext highlighter-rouge">./config</code>, which <code class="language-plaintext highlighter-rouge">gitlab-backup</code> doesn’t touch:</p>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">gitlab-secrets.json</code></strong> holds the keys that encrypt CI/CD variables, two-factor secrets and runner tokens in the database. Restore a backup without it and all of those become unreadable.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">gitlab.rb</code></strong> is your configuration.</li>
</ul>

<p>Back up both together, and copy them <strong>off the machine</strong>; a backup that lives on the same disk as GitLab doesn’t survive the disk. A nightly script:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c">#!/bin/bash</span>
<span class="c"># /opt/gitlab/backup.sh: nightly GitLab backup, run from cron</span>
<span class="nb">set</span> <span class="nt">-euo</span> pipefail
<span class="nb">cd</span> /opt/gitlab

docker compose <span class="nb">exec</span> <span class="nt">-T</span> gitlab gitlab-backup create <span class="nv">CRON</span><span class="o">=</span>1
<span class="nb">tar </span>czf <span class="s2">"data/backups/gitlab-config-</span><span class="si">$(</span><span class="nb">date</span> +%F<span class="si">)</span><span class="s2">.tgz"</span> config

rsync <span class="nt">-a</span> <span class="nt">--delete</span> data/backups/ backup@203.0.113.50:/backups/gitlab/
</code></pre></div></div>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">set -euo pipefail</code></strong>: stop at the first failing command, treat unset variables as errors, and fail a pipeline if any part of it fails. Without it, a failed backup would still be rsynced away as if it had worked.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">exec -T</code></strong>: don’t allocate a terminal; cron has none, and <code class="language-plaintext highlighter-rouge">exec</code> errors out without this flag.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">CRON=1</code></strong>: silence progress output unless something goes wrong, so cron only emails you on failure.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">tar czf … config</code></strong>: the configuration and secrets, next to the data backup.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">rsync -a --delete</code></strong>: mirror the backup directory to another machine. <code class="language-plaintext highlighter-rouge">--delete</code> keeps the copy in step with GitLab’s own 7-day retention.</li>
</ul>

<p>Schedule it with <code class="language-plaintext highlighter-rouge">crontab -e</code>:</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>0 2 * * * /opt/gitlab/backup.sh
</code></pre></div></div>

<p>(minute 0, hour 2, every day of the month, every month, every day of the week).</p>

<h3 id="restoring">Restoring</h3>

<p>A restore must go onto the <strong>same GitLab version</strong> that created the backup:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># 1. Put the config backup back: gitlab.rb and gitlab-secrets.json into ./config</span>
<span class="c"># 2. Start GitLab (same version), then stop the processes that write to the database</span>
docker compose <span class="nb">exec </span>gitlab gitlab-ctl stop puma
docker compose <span class="nb">exec </span>gitlab gitlab-ctl stop sidekiq

<span class="c"># 3. Restore; BACKUP is the file name without _gitlab_backup.tar</span>
docker compose <span class="nb">exec </span>gitlab gitlab-backup restore <span class="nv">BACKUP</span><span class="o">=</span>1752900000_2025_07_19_18.2.1

<span class="c"># 4. Restart and verify</span>
docker compose restart gitlab
docker compose <span class="nb">exec </span>gitlab gitlab-rake gitlab:check <span class="nv">SANITIZE</span><span class="o">=</span><span class="nb">true</span>
</code></pre></div></div>

<p>Rehearse this on a spare machine before you need it. A restore you’ve never run is a hope, not a backup.</p>

<h2 id="5-the-container-registry">5. The container registry</h2>

<p>The <code class="language-plaintext highlighter-rouge">registry_external_url</code> line from section 1 serves a Docker registry at <code class="language-plaintext highlighter-rouge">registry.example.com</code>, with GitLab handling authentication. Every project gets an image namespace: <code class="language-plaintext highlighter-rouge">registry.example.com/team/api</code>.</p>

<p>It needs its own DNS name pointing at the server. GitLab obtains its certificate automatically if Let’s Encrypt is enabled; otherwise put a certificate for that name in <code class="language-plaintext highlighter-rouge">./config/ssl/</code>. Users log in with a personal access token that has the <code class="language-plaintext highlighter-rouge">read_registry</code> / <code class="language-plaintext highlighter-rouge">write_registry</code> scopes, never their password:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker login registry.example.com
</code></pre></div></div>

<h2 id="6-ci-a-runner-that-builds-docker-images">6. CI: a runner that builds Docker images</h2>

<p>GitLab only coordinates CI; jobs run on a <strong>runner</strong>. We’ll run the runner as a container on a separate machine (ideally, since builds are heavy) or on the same host.</p>

<pre><code class="language-mermaid">flowchart TD
  dev([git push]) --&gt; GL[GitLab]
  GL -- "job for branch/tag" --&gt; R[gitlab-runner]
  R -- "starts job container docker:27-cli" --&gt; J[CI job]
  J -- "/var/run/docker.sock" --&gt; D[(Host Docker daemon)]
  D -- "docker build" --&gt; I[image]
  J -- "docker push" --&gt; REG[(GitLab Container Registry)]
  REG -. "docker pull" .-&gt; S[Deploy server]
</code></pre>

<h3 id="start-and-register-the-runner">Start and register the runner</h3>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker run <span class="nt">-d</span> <span class="nt">--name</span> gitlab-runner <span class="nt">--restart</span> unless-stopped <span class="se">\</span>
  <span class="nt">-v</span> /srv/gitlab-runner/config:/etc/gitlab-runner <span class="se">\</span>
  <span class="nt">-v</span> /var/run/docker.sock:/var/run/docker.sock <span class="se">\</span>
  gitlab/gitlab-runner:latest
</code></pre></div></div>

<p>In GitLab, create the runner first: <strong>Admin Area → CI/CD → Runners → New instance runner</strong> (or a project’s <strong>Settings → CI/CD → Runners</strong>). Set its tags there, for example <code class="language-plaintext highlighter-rouge">docker</code>. GitLab then shows an authentication token starting with <code class="language-plaintext highlighter-rouge">glrt-</code>. (The older “registration token” flow is deprecated since GitLab 16.)</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker <span class="nb">exec</span> <span class="nt">-it</span> gitlab-runner gitlab-runner register <span class="se">\</span>
  <span class="nt">--url</span> https://gitlab.example.com <span class="se">\</span>
  <span class="nt">--token</span> glrt-xxxxxxxxxxxxxxxxxxxx <span class="se">\</span>
  <span class="nt">--executor</span> docker <span class="se">\</span>
  <span class="nt">--docker-image</span> alpine:3.20
</code></pre></div></div>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">--executor docker</code></strong>: each job runs in its own container, started from the image the job names.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">--docker-image alpine:3.20</code></strong>: the default image for jobs that don’t name one.</li>
</ul>

<h3 id="the-runners-config">The runner’s config</h3>

<p>Registration writes <code class="language-plaintext highlighter-rouge">/srv/gitlab-runner/config/config.toml</code>. For jobs that build images, it should look like this:</p>

<div class="language-toml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">concurrent</span> <span class="o">=</span><span class="w"> </span><span class="mi">2</span>

<span class="k">[[</span><span class="n">runners</span><span class="k">]]</span>
  <span class="n">name</span> <span class="o">=</span><span class="w"> </span><span class="s">"docker-builder"</span>
  <span class="n">url</span> <span class="o">=</span><span class="w"> </span><span class="s">"https://gitlab.example.com"</span>
  <span class="n">token</span> <span class="o">=</span><span class="w"> </span><span class="s">"glrt-xxxxxxxxxxxxxxxxxxxx"</span>
  <span class="n">executor</span> <span class="o">=</span><span class="w"> </span><span class="s">"docker"</span>

  <span class="k">[</span><span class="n">runners</span><span class="k">.</span><span class="n">docker</span><span class="k">]</span>
    <span class="n">image</span> <span class="o">=</span><span class="w"> </span><span class="s">"alpine:3.20"</span>
    <span class="n">privileged</span> <span class="o">=</span><span class="w"> </span><span class="kc">false</span>
    <span class="n">pull_policy</span> <span class="o">=</span><span class="w"> </span><span class="s">"if-not-present"</span>
    <span class="n">volumes</span> <span class="o">=</span><span class="w"> </span><span class="p">[</span><span class="s">"/cache"</span><span class="p">,</span> <span class="s">"/var/run/docker.sock:/var/run/docker.sock"</span><span class="p">]</span>
</code></pre></div></div>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">concurrent = 2</code></strong>: how many jobs this runner process executes at once.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">privileged = false</code></strong>: jobs don’t get elevated privileges.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">pull_policy = "if-not-present"</code></strong>: reuse images already on the machine instead of pulling on every job.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">volumes</code></strong>: <code class="language-plaintext highlighter-rouge">/cache</code> is a volume for the runner’s job cache; the Docker socket line is <strong>socket binding</strong>. Job containers talk to the host’s Docker daemon, so <code class="language-plaintext highlighter-rouge">docker build</code> inside a job works without Docker-in-Docker.</li>
</ul>

<p>The runner watches <code class="language-plaintext highlighter-rouge">config.toml</code> and reloads it within seconds; there’s no need to restart it after edits.</p>

<p>Socket binding is simple and fast, and builds reuse the host’s layer cache. The trade-off is the same as with Jenkins: any job can control the host’s Docker daemon, including other projects’ containers. Keep socket-bound runners for trusted projects. The alternative, <strong>Docker-in-Docker</strong>, gives each job its own daemon in a <code class="language-plaintext highlighter-rouge">docker:dind</code> service container. It’s better isolated, but it needs <code class="language-plaintext highlighter-rouge">privileged = true</code> and a cold cache per job. Pick one per runner, and don’t mix the two.</p>

<h3 id="the-pipeline">The pipeline</h3>

<p><code class="language-plaintext highlighter-rouge">.gitlab-ci.yml</code> in the project:</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">stages</span><span class="pi">:</span>
  <span class="pi">-</span> <span class="s">build</span>

<span class="na">build-image</span><span class="pi">:</span>
  <span class="na">stage</span><span class="pi">:</span> <span class="s">build</span>
  <span class="na">image</span><span class="pi">:</span> <span class="s">docker:27-cli</span>
  <span class="na">tags</span><span class="pi">:</span> <span class="pi">[</span><span class="nv">docker</span><span class="pi">]</span>
  <span class="na">before_script</span><span class="pi">:</span>
    <span class="pi">-</span> <span class="s">echo "$CI_REGISTRY_PASSWORD" | docker login -u "$CI_REGISTRY_USER" --password-stdin "$CI_REGISTRY"</span>
  <span class="na">script</span><span class="pi">:</span>
    <span class="pi">-</span> <span class="s">docker build --pull -t "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA" .</span>
    <span class="pi">-</span> <span class="s">docker push "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA"</span>
    <span class="pi">-</span> <span class="pi">|</span>
      <span class="s">if [ "$CI_COMMIT_BRANCH" = "$CI_DEFAULT_BRANCH" ]; then</span>
        <span class="s">docker tag "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA" "$CI_REGISTRY_IMAGE:latest"</span>
        <span class="s">docker push "$CI_REGISTRY_IMAGE:latest"</span>
      <span class="s">fi</span>
</code></pre></div></div>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">image: docker:27-cli</code></strong>: the job container only needs the Docker client; the daemon is the host’s, through the bound socket.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">tags: [docker]</code></strong>: only runners carrying the <code class="language-plaintext highlighter-rouge">docker</code> tag pick this job up. If a job sits at “stuck: no runners”, the tags don’t match.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">$CI_REGISTRY</code>, <code class="language-plaintext highlighter-rouge">$CI_REGISTRY_IMAGE</code>, <code class="language-plaintext highlighter-rouge">$CI_REGISTRY_USER</code>, <code class="language-plaintext highlighter-rouge">$CI_REGISTRY_PASSWORD</code></strong>: predefined by GitLab when the registry is enabled. The user is <code class="language-plaintext highlighter-rouge">gitlab-ci-token</code>, and the password is a job token that’s valid only while this job runs. You don’t create or store any credentials.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">--password-stdin</code></strong>: pass the password on standard input, so it never appears in the process list or the job log.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">--pull</code></strong>: always check for a newer base image, so security fixes in <code class="language-plaintext highlighter-rouge">FROM</code> images reach your builds.</li>
  <li><strong>Tag with <code class="language-plaintext highlighter-rouge">$CI_COMMIT_SHORT_SHA</code></strong>: every build gets a unique, traceable tag. <code class="language-plaintext highlighter-rouge">latest</code> is moved only on the default branch, so feature branches can’t overwrite what production pulls.</li>
</ul>

<h2 id="7-upgrading-gitlab">7. Upgrading GitLab</h2>

<p>GitLab upgrades have <strong>required stops</strong>: you can’t jump from any version to any other, because database migrations must run in order. The official <a href="https://gitlab-com.gitlab.io/support/toolbox/upgrade-path/">Upgrade Path tool</a> lists the exact versions to pass through for your starting point.</p>

<pre><code class="language-mermaid">flowchart LR
  subgraph prep["Prepare"]
    direction TB
    A[Back up: gitlab-backup + config/] --&gt; B[Look up the path in the Upgrade Path tool]
  end
  subgraph stop["For each upgrade stop"]
    direction TB
    C[Set image: to the next stop in compose.yml] --&gt; D[docker compose up -d]
    D --&gt; E[Follow the logs until migrations finish and the UI answers]
    E --&gt; F@{ shape: hex, label: "Migrations done?" }
    F -- "no: check Admin → Monitoring" --&gt; F
    F -- yes --&gt; G@{ shape: hex, label: "More stops?" }
    G -- yes --&gt; C
    G -- no --&gt; H[Done]
  end
  prep --&gt; stop
</code></pre>

<ul>
  <li><strong>One stop at a time.</strong> Change the <code class="language-plaintext highlighter-rouge">image:</code> tag to the next version on the path, then <code class="language-plaintext highlighter-rouge">docker compose up -d</code>. The container runs the migrations on start.</li>
  <li><strong>Wait for background migrations</strong> (Admin Area → Monitoring → Background migrations) before taking the next step. Skipping ahead while they’re still running is the classic way to break an upgrade.</li>
  <li><strong>If <code class="language-plaintext highlighter-rouge">reconfigure</code> aborts</strong> with “Removed configurations found in gitlab.rb”, a setting you use was removed in the new version. The log names it. Go back to the previous tag, remove or replace the setting in <code class="language-plaintext highlighter-rouge">gitlab.rb</code>, run <code class="language-plaintext highlighter-rouge">gitlab-ctl reconfigure</code> there, then try the upgrade again.</li>
</ul>

<h2 id="troubleshooting">Troubleshooting</h2>

<table>
  <thead>
    <tr>
      <th>Symptom</th>
      <th>Likely cause</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">502</code> right after start or upgrade</td>
      <td>Still booting or migrating; watch <code class="language-plaintext highlighter-rouge">docker compose logs -f</code>.</td>
    </tr>
    <tr>
      <td>Clone URL shows port 22 but SSH is on 2222</td>
      <td><code class="language-plaintext highlighter-rouge">gitlab_shell_ssh_port</code> isn’t set.</td>
    </tr>
    <tr>
      <td>Job stuck: “no runners online assigned”</td>
      <td>Tags on the job and the runner don’t match, or “Run untagged jobs” is off.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">Uploading artifacts … too large archive</code></td>
      <td>Raise <strong>Admin → Settings → CI/CD → Maximum artifacts size</strong>, and <code class="language-plaintext highlighter-rouge">client_max_body_size</code> in any proxy in front.</td>
    </tr>
    <tr>
      <td>CI variables unreadable after a restore</td>
      <td><code class="language-plaintext highlighter-rouge">gitlab-secrets.json</code> wasn’t restored with the backup.</td>
    </tr>
  </tbody>
</table>

<p><a href="/portfolio-site/blog/2025/07/13/chapter-1-6-docker-mysql/">Chapter 1.6</a> moves on to running databases in containers, starting with MySQL.</p>]]></content><author><name>Echo Yin</name></author><category term="devops" /><category term="Platform Engineering" /><category term="DevOps" /><category term="Chapter One" /><category term="Docker" /><summary type="html"><![CDATA[Run GitLab CE in a container with Docker Compose, give it working SSH clone URLs, attach a CI runner that builds and pushes Docker images, and set up the parts people skip until it's too late: backups that include the secrets, restores, and version upgrades that follow the required path.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://e-choness.github.io/portfolio-site/assets/images/blogs/docker-gitlab.webp" /><media:content medium="image" url="https://e-choness.github.io/portfolio-site/assets/images/blogs/docker-gitlab.webp" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Chapter 1.6 - MySQL in Docker: Data That Survives, Config That Works</title><link href="https://e-choness.github.io/portfolio-site/blog/2025/07/13/chapter-1-6-docker-mysql/" rel="alternate" type="text/html" title="Chapter 1.6 - MySQL in Docker: Data That Survives, Config That Works" /><published>2025-07-13T00:00:00+00:00</published><updated>2025-07-13T00:00:00+00:00</updated><id>https://e-choness.github.io/portfolio-site/blog/2025/07/13/chapter-1-6-docker-mysql</id><content type="html" xml:base="https://e-choness.github.io/portfolio-site/blog/2025/07/13/chapter-1-6-docker-mysql/"><![CDATA[<p>Databases are the containers people are most nervous about, and reasonably so: a web server container can be thrown away, but the data can’t. The good news is that the rules are few. Keep the data in a <strong>volume</strong>, never inside the container. Keep configuration in a <strong>file on the host</strong>. And back up with the database’s own tools rather than by copying files.</p>

<h2 id="the-shape-of-it">The shape of it</h2>

<pre><code class="language-mermaid">flowchart LR
  subgraph Host
    cnf["./mysql/conf.d/app.cnf&lt;br/&gt;(edited on the host)"]
    env["./mysql.env&lt;br/&gt;passwords"]
    vol[("mysql_data volume&lt;br/&gt;managed by Docker")]
  end
  subgraph C["mysql container (replaceable)"]
    conf["/etc/mysql/conf.d/app.cnf"]
    data["/var/lib/mysql"]
    d[mysqld]
  end
  cnf -- "bind mount :ro" --&gt; conf
  vol -- "named volume" --&gt; data
  env -. "environment, first start" .-&gt; d
  conf --&gt; d
  data &lt;--&gt; d
  app([App containers]) -- "mysql:3306 on a Docker network" --&gt; d
</code></pre>

<p>The container itself holds nothing you can’t recreate. Remove it, upgrade it, move it to another host: as long as the same volume and config are attached, MySQL picks up exactly where it stopped.</p>

<h2 id="choosing-a-version">Choosing a version</h2>

<p>MySQL now has two release tracks:</p>

<ul>
  <li><strong>LTS</strong> (8.4): bug and security fixes only, supported for years. <strong>This is what you want for data you care about.</strong></li>
  <li><strong>Innovation</strong> (9.x): new features every quarter, each release supported only until the next.</li>
</ul>

<p><code class="language-plaintext highlighter-rouge">mysql:latest</code> follows Innovation. Pin the LTS line instead:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker pull mysql:8.4
</code></pre></div></div>

<h2 id="running-it">Running it</h2>

<p>Put the passwords in a file rather than on the command line, where they’d end up in your shell history and in <code class="language-plaintext highlighter-rouge">ps</code> output. Create <code class="language-plaintext highlighter-rouge">mysql.env</code>:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">MYSQL_ROOT_PASSWORD</span><span class="o">=</span>change-me-to-something-long
<span class="nv">MYSQL_DATABASE</span><span class="o">=</span>shop
<span class="nv">MYSQL_USER</span><span class="o">=</span>shop
<span class="nv">MYSQL_PASSWORD</span><span class="o">=</span>another-long-random-password
</code></pre></div></div>

<p>and restrict it: <code class="language-plaintext highlighter-rouge">chmod 600 mysql.env</code>. Then:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker network create backend

docker run <span class="nt">-d</span> <span class="nt">--name</span> mysql <span class="se">\</span>
  <span class="nt">--network</span> backend <span class="se">\</span>
  <span class="nt">--restart</span> unless-stopped <span class="se">\</span>
  <span class="nt">-p</span> 127.0.0.1:3306:3306 <span class="se">\</span>
  <span class="nt">--env-file</span> ./mysql.env <span class="se">\</span>
  <span class="nt">-e</span> <span class="nv">TZ</span><span class="o">=</span>America/Edmonton <span class="se">\</span>
  <span class="nt">-v</span> mysql_data:/var/lib/mysql <span class="se">\</span>
  <span class="nt">-v</span> <span class="s2">"</span><span class="nv">$PWD</span><span class="s2">/mysql/conf.d:/etc/mysql/conf.d:ro"</span> <span class="se">\</span>
  mysql:8.4
</code></pre></div></div>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">--network backend</code></strong>: your application containers join the same network and reach the database as <code class="language-plaintext highlighter-rouge">mysql:3306</code> (Docker’s DNS resolves the container name).</li>
  <li><strong><code class="language-plaintext highlighter-rouge">-p 127.0.0.1:3306:3306</code></strong>: publish the port on the host’s loopback only, so you can connect from the host with a client, but the database isn’t exposed to the network. Drop the line entirely if only containers need access.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">--env-file ./mysql.env</code></strong>: the variables above:
    <ul>
      <li><code class="language-plaintext highlighter-rouge">MYSQL_ROOT_PASSWORD</code>: the root password.</li>
      <li><code class="language-plaintext highlighter-rouge">MYSQL_DATABASE</code>: a database to create.</li>
      <li><code class="language-plaintext highlighter-rouge">MYSQL_USER</code> / <code class="language-plaintext highlighter-rouge">MYSQL_PASSWORD</code>: an application user with full rights on that database <em>only</em>. Your app connects as this user, never as root.</li>
    </ul>
  </li>
  <li><strong><code class="language-plaintext highlighter-rouge">-e TZ=…</code></strong>: the container’s time zone. MySQL takes its <code class="language-plaintext highlighter-rouge">system_time_zone</code> from it, so <code class="language-plaintext highlighter-rouge">NOW()</code> matches your local time.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">-v mysql_data:/var/lib/mysql</code></strong>: the data directory in a named volume. Docker creates it on first use.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">-v …/conf.d:/etc/mysql/conf.d:ro</code></strong>: your configuration (next section), read-only.</li>
</ul>

<p><code class="language-plaintext highlighter-rouge">docker logs -f mysql</code> shows the first-start initialization, then <code class="language-plaintext highlighter-rouge">ready for connections</code>.</p>

<h3 id="the-first-start-surprise">The first-start surprise</h3>

<p>Those <code class="language-plaintext highlighter-rouge">MYSQL_*</code> variables are applied <strong>only when the data directory is empty</strong>, that is, on the very first start with a new volume. After that, MySQL uses what’s stored in the volume, and the variables are ignored. If you change <code class="language-plaintext highlighter-rouge">MYSQL_ROOT_PASSWORD</code> later and restart, the password doesn’t change. That’s by design: the entrypoint won’t overwrite an existing database. To change credentials on a running database, use SQL (<code class="language-plaintext highlighter-rouge">ALTER USER …</code>).</p>

<p>The same rule applies to initialization scripts. Any <code class="language-plaintext highlighter-rouge">.sql</code> or <code class="language-plaintext highlighter-rouge">.sh</code> file mounted into <code class="language-plaintext highlighter-rouge">/docker-entrypoint-initdb.d/</code> runs once, on that first start, in alphabetical order. That’s handy for creating a schema or seed data:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">-v</span> <span class="s2">"</span><span class="nv">$PWD</span><span class="s2">/initdb:/docker-entrypoint-initdb.d:ro"</span>
</code></pre></div></div>

<h2 id="configuration-that-works">Configuration that works</h2>

<p>Create <code class="language-plaintext highlighter-rouge">mysql/conf.d/app.cnf</code>. The official image reads every <code class="language-plaintext highlighter-rouge">.cnf</code> file in <code class="language-plaintext highlighter-rouge">/etc/mysql/conf.d/</code> on top of its defaults:</p>

<div class="language-ini highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nn">[mysqld]</span><span class="w">
</span><span class="c"># Full Unicode, including emoji
</span><span class="py">character-set-server</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="s">utf8mb4</span>
<span class="py">collation-server</span><span class="w">     </span><span class="p">=</span><span class="w"> </span><span class="s">utf8mb4_0900_ai_ci</span>
<span class="w">
</span><span class="c"># Binary log: needed for replication and point-in-time recovery
</span><span class="py">server-id</span><span class="w">                  </span><span class="p">=</span><span class="w"> </span><span class="s">1</span>
<span class="py">binlog_expire_logs_seconds</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="s">604800</span>
<span class="py">max_binlog_size</span><span class="w">            </span><span class="p">=</span><span class="w"> </span><span class="s">100M</span>
<span class="w">
</span><span class="c"># Memory for caching data and indexes: the most important tuning knob
</span><span class="py">innodb_buffer_pool_size</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="s">1G</span>
<span class="w">
</span><span class="c"># Connections
</span><span class="py">max_connections</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="s">200</span>
<span class="w">
</span><span class="nn">[client]</span><span class="w">
</span><span class="py">default-character-set</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="s">utf8mb4</span>
</code></pre></div></div>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">character-set-server</code> / <code class="language-plaintext highlighter-rouge">collation-server</code></strong>: store text as <code class="language-plaintext highlighter-rouge">utf8mb4</code>, real 4-byte UTF-8 (MySQL’s older <code class="language-plaintext highlighter-rouge">utf8</code> can’t store emoji). <code class="language-plaintext highlighter-rouge">utf8mb4_0900_ai_ci</code> is MySQL 8’s default collation: accent- and case-insensitive comparisons, based on a recent Unicode standard.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">server-id</code></strong>: a unique number per server; required as soon as you add replication.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">binlog_expire_logs_seconds</code></strong>: the binary log (on by default since MySQL 8) records every change. Keeping 7 days of it lets you replay changes after restoring the last dump, known as point-in-time recovery. Older logs are purged automatically.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">innodb_buffer_pool_size</code></strong>: how much memory InnoDB uses to cache data and indexes. On a dedicated database host, 50–70% of RAM is typical; on a shared machine, size it so MySQL and everything else fit. If it’s too large, the container gets killed for exceeding its memory.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">max_connections</code></strong>: the ceiling on concurrent connections. Your application’s connection pool size, times its replica count, has to fit under it.</li>
</ul>

<p><strong>Leave these to the image:</strong> <code class="language-plaintext highlighter-rouge">datadir</code>, <code class="language-plaintext highlighter-rouge">socket</code> and <code class="language-plaintext highlighter-rouge">pid-file</code>. Moving the socket, in particular, breaks the <code class="language-plaintext highlighter-rouge">mysql</code> client inside the container and the image’s own startup scripts. You’ll also find old guides setting <code class="language-plaintext highlighter-rouge">character-set-client-handshake</code>, which was removed in MySQL 8.0; setting it now stops the server from starting.</p>

<p><strong>One setting to decide on day one:</strong> <code class="language-plaintext highlighter-rouge">lower_case_table_names</code>. MySQL 8 only accepts it when the data directory is <strong>first initialized</strong>. Setting it later, or changing it, makes the server refuse to start. If you need case-insensitive table names (common when migrating from Windows), put <code class="language-plaintext highlighter-rouge">lower_case_table_names = 1</code> in the file <em>before</em> the first start.</p>

<p>After editing the file, restart to apply it: <code class="language-plaintext highlighter-rouge">docker restart mysql</code>. Many settings can also be changed live with <code class="language-plaintext highlighter-rouge">SET PERSIST</code>, which MySQL writes to <code class="language-plaintext highlighter-rouge">mysqld-auto.cnf</code> inside the volume.</p>

<h2 id="connecting">Connecting</h2>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># a client session inside the container</span>
docker <span class="nb">exec</span> <span class="nt">-it</span> mysql mysql <span class="nt">-u</span> shop <span class="nt">-p</span> shop

<span class="c"># from the host, through the loopback-published port</span>
mysql <span class="nt">-h</span> 127.0.0.1 <span class="nt">-P</span> 3306 <span class="nt">-u</span> shop <span class="nt">-p</span> shop
</code></pre></div></div>

<p>From another container on the <code class="language-plaintext highlighter-rouge">backend</code> network, the connection string is <code class="language-plaintext highlighter-rouge">mysql://shop:…@mysql:3306/shop</code>: the hostname is the container name.</p>

<p>Check that the settings took effect:</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">SHOW</span> <span class="n">VARIABLES</span> <span class="k">LIKE</span> <span class="s1">'character_set_server'</span><span class="p">;</span>
<span class="k">SHOW</span> <span class="n">VARIABLES</span> <span class="k">LIKE</span> <span class="s1">'innodb_buffer_pool_size'</span><span class="p">;</span>
<span class="k">SHOW</span> <span class="nb">BINARY</span> <span class="n">LOGS</span><span class="p">;</span>
<span class="k">SELECT</span> <span class="n">NOW</span><span class="p">(),</span> <span class="o">@@</span><span class="n">system_time_zone</span><span class="p">;</span>
</code></pre></div></div>

<h2 id="health-checks">Health checks</h2>

<p>“The container is running” doesn’t mean “MySQL accepts connections”: the first start takes a while. In Compose, a health check makes dependent services wait:</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">services</span><span class="pi">:</span>
  <span class="na">mysql</span><span class="pi">:</span>
    <span class="na">image</span><span class="pi">:</span> <span class="s">mysql:8.4</span>
    <span class="na">env_file</span><span class="pi">:</span> <span class="s">mysql.env</span>
    <span class="na">volumes</span><span class="pi">:</span>
      <span class="pi">-</span> <span class="s">mysql_data:/var/lib/mysql</span>
      <span class="pi">-</span> <span class="s">./mysql/conf.d:/etc/mysql/conf.d:ro</span>
    <span class="na">healthcheck</span><span class="pi">:</span>
      <span class="na">test</span><span class="pi">:</span> <span class="pi">[</span><span class="s2">"</span><span class="s">CMD"</span><span class="pi">,</span> <span class="s2">"</span><span class="s">mysqladmin"</span><span class="pi">,</span> <span class="s2">"</span><span class="s">ping"</span><span class="pi">,</span> <span class="s2">"</span><span class="s">-h"</span><span class="pi">,</span> <span class="s2">"</span><span class="s">127.0.0.1"</span><span class="pi">,</span> <span class="s2">"</span><span class="s">--silent"</span><span class="pi">]</span>
      <span class="na">interval</span><span class="pi">:</span> <span class="s">10s</span>
      <span class="na">timeout</span><span class="pi">:</span> <span class="s">5s</span>
      <span class="na">retries</span><span class="pi">:</span> <span class="m">10</span>
      <span class="na">start_period</span><span class="pi">:</span> <span class="s">30s</span>

  <span class="na">api</span><span class="pi">:</span>
    <span class="na">image</span><span class="pi">:</span> <span class="s">yourname/shop-api:1.4.2</span>
    <span class="na">depends_on</span><span class="pi">:</span>
      <span class="na">mysql</span><span class="pi">:</span>
        <span class="na">condition</span><span class="pi">:</span> <span class="s">service_healthy</span>

<span class="na">volumes</span><span class="pi">:</span>
  <span class="na">mysql_data</span><span class="pi">:</span>
</code></pre></div></div>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">mysqladmin ping</code></strong>: succeeds only once the server answers. <code class="language-plaintext highlighter-rouge">-h 127.0.0.1</code> forces a TCP connection, which isn’t available during initialization, so the check can’t pass too early.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">start_period: 30s</code></strong>: failures during the first 30 seconds don’t count against <code class="language-plaintext highlighter-rouge">retries</code>.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">condition: service_healthy</code></strong>: <code class="language-plaintext highlighter-rouge">api</code> isn’t started until MySQL’s check passes. Plain <code class="language-plaintext highlighter-rouge">depends_on: [mysql]</code> only waits for the container to <em>start</em>.</li>
</ul>

<h2 id="backups">Backups</h2>

<p>Don’t copy the volume’s files while MySQL is running. InnoDB keeps changes in memory and in its logs, so a live file copy is inconsistent and may not start. Use <code class="language-plaintext highlighter-rouge">mysqldump</code>:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker <span class="nb">exec </span>mysql sh <span class="nt">-c</span> <span class="se">\</span>
  <span class="s1">'exec mysqldump --all-databases --single-transaction --routines --events -uroot -p"$MYSQL_ROOT_PASSWORD"'</span> <span class="se">\</span>
  | <span class="nb">gzip</span> <span class="o">&gt;</span> <span class="s2">"backup-</span><span class="si">$(</span><span class="nb">date</span> +%F<span class="si">)</span><span class="s2">.sql.gz"</span>
</code></pre></div></div>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">sh -c '…'</code></strong>: run inside the container, so <code class="language-plaintext highlighter-rouge">$MYSQL_ROOT_PASSWORD</code> is expanded from the <em>container’s</em> environment. The password never appears on your host’s command line.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">--single-transaction</code></strong>: take a consistent snapshot of InnoDB tables without locking them; the app keeps running during the backup.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">--routines --events</code></strong>: include stored procedures and scheduled events, which are skipped by default.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">| gzip</code></strong>: SQL dumps compress very well.</li>
</ul>

<p>Restoring:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">gunzip</span> <span class="nt">-c</span> backup-2025-07-13.sql.gz | docker <span class="nb">exec</span> <span class="nt">-i</span> mysql sh <span class="nt">-c</span> <span class="s1">'exec mysql -uroot -p"$MYSQL_ROOT_PASSWORD"'</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">-i</code> connects your pipe to the container’s standard input. Schedule the dump nightly with cron, copy it off the machine, and test a restore into a scratch container now and then:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker run <span class="nt">-d</span> <span class="nt">--name</span> restore-test <span class="nt">-e</span> <span class="nv">MYSQL_ROOT_PASSWORD</span><span class="o">=</span><span class="nb">test </span>mysql:8.4
</code></pre></div></div>

<p>For large databases, where a dump takes too long, look at Percona XtraBackup or MySQL Shell’s dump utilities.</p>

<h2 id="upgrading">Upgrading</h2>

<p>Within the LTS line (8.4.x to 8.4.y), upgrading is just pulling the new image and recreating the container with the same volume and config. The server upgrades its data dictionary automatically on start (no more <code class="language-plaintext highlighter-rouge">mysql_upgrade</code> since 8.0.16).</p>

<p>Between major lines (8.0 → 8.4), take a dump first, read the release notes for removed settings, then change the tag. Downgrades aren’t supported: once a newer version has started on the volume, your way back is the dump.</p>

<h2 id="a-checklist">A checklist</h2>

<ul>
  <li>Data in a named volume; configuration mounted read-only.</li>
  <li>Passwords in an env file with <code class="language-plaintext highlighter-rouge">600</code> permissions, or in Docker/Compose secrets.</li>
  <li>The app connects as its own user, never root.</li>
  <li>The port isn’t published to the network unless something outside Docker really needs it.</li>
  <li>A memory limit on the container that’s larger than <code class="language-plaintext highlighter-rouge">innodb_buffer_pool_size</code> plus headroom.</li>
  <li>Nightly <code class="language-plaintext highlighter-rouge">mysqldump</code>, copied off the host, restore tested.</li>
</ul>

<p><a href="/portfolio-site/blog/2025/07/14/chapter-1-7-docker-redis/">Chapter 1.7</a> applies the same approach to Redis, where the default configuration hides a few traps of its own.</p>]]></content><author><name>Echo Yin</name></author><category term="devops" /><category term="Platform Engineering" /><category term="DevOps" /><category term="Chapter One" /><category term="Docker" /><summary type="html"><![CDATA[Run MySQL 8.4 in a container the way you'd want to run it in production: data in a volume, credentials out of your shell history, a my.cnf that doesn't stop the server from starting, health checks, consistent backups and upgrades. Plus the first-start behaviour that surprises almost everyone.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://e-choness.github.io/portfolio-site/assets/images/blogs/docker-mysql.webp" /><media:content medium="image" url="https://e-choness.github.io/portfolio-site/assets/images/blogs/docker-mysql.webp" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Chapter 1.3 - Nginx in Docker: Static Sites, Reverse Proxy and HTTPS</title><link href="https://e-choness.github.io/portfolio-site/blog/2025/07/12/chapter-1-3-docker-nginx/" rel="alternate" type="text/html" title="Chapter 1.3 - Nginx in Docker: Static Sites, Reverse Proxy and HTTPS" /><published>2025-07-12T00:00:00+00:00</published><updated>2025-07-12T00:00:00+00:00</updated><id>https://e-choness.github.io/portfolio-site/blog/2025/07/12/chapter-1-3-docker-nginx</id><content type="html" xml:base="https://e-choness.github.io/portfolio-site/blog/2025/07/12/chapter-1-3-docker-nginx/"><![CDATA[<p>Nginx is usually the first thing a request meets: it serves static files, forwards everything else to your application, and handles TLS so your app doesn’t have to. It’s also a very good first “real” container, because it shows the pattern almost every service follows: <strong>the image stays stock, and everything specific to you (config, content, certificates) is mounted in from the host.</strong></p>

<p>We’ll build up in three steps: a static site, a reverse proxy in front of the app from <a href="/portfolio-site/blog/2025/07/10/chapter-1-1-docker-basics/">Chapter 1.1</a>, then HTTPS.</p>

<h2 id="step-0-stock-nginx">Step 0: stock Nginx</h2>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker run <span class="nt">-d</span> <span class="nt">--name</span> web <span class="nt">-p</span> 8080:80 nginx:1.27
curl <span class="nt">-I</span> http://localhost:8080
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">HTTP/1.1 200 OK</code> and the Nginx welcome page. Pin a version tag (<code class="language-plaintext highlighter-rouge">nginx:1.27</code>) rather than <code class="language-plaintext highlighter-rouge">latest</code>, so a routine pull doesn’t upgrade your web server under you.</p>

<p>Two things the official image does that you’ll rely on:</p>

<ul>
  <li><strong>Logs go to stdout/stderr.</strong> <code class="language-plaintext highlighter-rouge">/var/log/nginx/access.log</code> and <code class="language-plaintext highlighter-rouge">error.log</code> are symlinks to them, so <code class="language-plaintext highlighter-rouge">docker logs web</code> shows every request.</li>
  <li><strong>Config is modular.</strong> The main <code class="language-plaintext highlighter-rouge">/etc/nginx/nginx.conf</code> includes every file in <code class="language-plaintext highlighter-rouge">/etc/nginx/conf.d/*.conf</code>. You almost never touch the main file; you add or replace files in <code class="language-plaintext highlighter-rouge">conf.d</code>.</li>
</ul>

<p><code class="language-plaintext highlighter-rouge">docker rm -f web</code> when you’re done looking.</p>

<h2 id="step-1-serving-a-static-site">Step 1: serving a static site</h2>

<p>Put your site in a directory, for example <code class="language-plaintext highlighter-rouge">~/site/index.html</code>, and mount it over Nginx’s default web root:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker run <span class="nt">-d</span> <span class="nt">--name</span> web <span class="se">\</span>
  <span class="nt">-p</span> 8080:80 <span class="se">\</span>
  <span class="nt">-v</span> ~/site:/usr/share/nginx/html:ro <span class="se">\</span>
  nginx:1.27
</code></pre></div></div>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">-v ~/site:/usr/share/nginx/html</code></strong>: a <strong>bind mount</strong>. The container’s web root <em>is</em> your host directory, so edits to <code class="language-plaintext highlighter-rouge">index.html</code> show up on the next request with no rebuild or restart.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">:ro</code></strong>: read-only inside the container. Nginx only needs to read the files, and a compromised web server then can’t modify your site.</li>
</ul>

<h2 id="step-2-a-reverse-proxy-in-front-of-an-app">Step 2: a reverse proxy in front of an app</h2>

<p>Now the more common setup: Nginx in front, the application behind it, never exposed directly.</p>

<pre><code class="language-mermaid">flowchart LR
  u([Browser]) -- ":80 / :443" --&gt; n[nginx container]
  subgraph net["Docker network: web"]
    n -- "http://app:3000" --&gt; a[app container&lt;br/&gt;hello-docker]
  end
</code></pre>

<p>Create a network and start the app on it, <strong>without</strong> publishing its port:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker network create web
docker run <span class="nt">-d</span> <span class="nt">--name</span> app <span class="nt">--network</span> web hello-docker:1.0
</code></pre></div></div>

<p>On a user-defined network, containers reach each other by name through Docker’s built-in DNS: from the Nginx container, <code class="language-plaintext highlighter-rouge">app</code> resolves to the app container’s IP. Because the app publishes no port, the only way in is through Nginx. (Networks get a full chapter in <a href="/portfolio-site/blog/2025/07/14/chapter-1-8-docker-network/">1.8</a>.)</p>

<p>Write the proxy config to <code class="language-plaintext highlighter-rouge">~/nginx/conf.d/default.conf</code>:</p>

<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">server</span> <span class="p">{</span>
    <span class="kn">listen</span> <span class="mi">80</span><span class="p">;</span>
    <span class="kn">server_name</span> <span class="s">_</span><span class="p">;</span>

    <span class="kn">location</span> <span class="n">/</span> <span class="p">{</span>
        <span class="kn">proxy_pass</span> <span class="s">http://app:3000</span><span class="p">;</span>

        <span class="kn">proxy_set_header</span> <span class="s">Host</span>              <span class="nv">$host</span><span class="p">;</span>
        <span class="kn">proxy_set_header</span> <span class="s">X-Real-IP</span>         <span class="nv">$remote_addr</span><span class="p">;</span>
        <span class="kn">proxy_set_header</span> <span class="s">X-Forwarded-For</span>   <span class="nv">$proxy_add_x_forwarded_for</span><span class="p">;</span>
        <span class="kn">proxy_set_header</span> <span class="s">X-Forwarded-Proto</span> <span class="nv">$scheme</span><span class="p">;</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>What each part does:</p>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">listen 80</code></strong>: accept plain HTTP on port 80 inside the container.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">server_name _</code></strong>: a catch-all; this block answers for any hostname. With several sites you’d list real names instead.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">location /</code></strong>: applies to every path.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">proxy_pass http://app:3000</code></strong>: forward the request to the <code class="language-plaintext highlighter-rouge">app</code> container on port 3000, resolved by Docker’s DNS.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">proxy_set_header ...</code></strong>: without these, your app would see every request as coming <em>from Nginx</em>. They pass along the original <code class="language-plaintext highlighter-rouge">Host</code> header, the client’s real IP (<code class="language-plaintext highlighter-rouge">X-Real-IP</code>, <code class="language-plaintext highlighter-rouge">X-Forwarded-For</code>) and whether the client used HTTP or HTTPS (<code class="language-plaintext highlighter-rouge">X-Forwarded-Proto</code>), which your app needs to build correct redirect URLs.</li>
</ul>

<p>Run Nginx on the same network with that directory mounted over <code class="language-plaintext highlighter-rouge">conf.d</code>:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker run <span class="nt">-d</span> <span class="nt">--name</span> proxy <span class="se">\</span>
  <span class="nt">--network</span> web <span class="se">\</span>
  <span class="nt">-p</span> 8080:80 <span class="se">\</span>
  <span class="nt">-v</span> ~/nginx/conf.d:/etc/nginx/conf.d:ro <span class="se">\</span>
  nginx:1.27

curl http://localhost:8080
<span class="c"># Hello from 9b1e4c3a0f12   (the app container's hostname)</span>
</code></pre></div></div>

<h2 id="step-3-https-with-lets-encrypt">Step 3: HTTPS with Let’s Encrypt</h2>

<p>For a public site you need a domain pointing at your server and a certificate. Let’s Encrypt issues free certificates through <code class="language-plaintext highlighter-rouge">certbot</code>, which proves you control the domain by placing a file that Let’s Encrypt then fetches over plain HTTP at <code class="language-plaintext highlighter-rouge">http://your-domain/.well-known/acme-challenge/...</code>.</p>

<p>The layout keeps everything on the host and mounts it into the container read-only:</p>

<pre><code class="language-mermaid">flowchart TD
  u([Browser]) -- "http :80&lt;br/&gt;https :443" --&gt; n
  le([Let's Encrypt]) -- "http :80&lt;br/&gt;/.well-known/acme-challenge" --&gt; n
  subgraph C["nginx container"]
    n[nginx]
  end
  subgraph H["Host (mounted :ro)"]
    conf["~/nginx/conf.d"]
    acme["/srv/certbot&lt;br/&gt;challenge files"]
    certs["/etc/letsencrypt&lt;br/&gt;certificates, renewed by certbot"]
    conf ~~~ acme ~~~ certs
  end
  conf -. "/etc/nginx/conf.d" .-&gt; n
  acme -. "/var/www/certbot" .-&gt; n
  certs -. "/etc/letsencrypt" .-&gt; n
  n -- "http://app:3000" --&gt; a[app container]
</code></pre>

<h3 id="3a-serve-the-challenge-directory-over-http">3a. Serve the challenge directory over HTTP</h3>

<p>Replace <code class="language-plaintext highlighter-rouge">default.conf</code> with a port-80 block that answers challenges and redirects everything else to HTTPS:</p>

<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">server</span> <span class="p">{</span>
    <span class="kn">listen</span> <span class="mi">80</span><span class="p">;</span>
    <span class="kn">server_name</span> <span class="s">example.com</span> <span class="s">www.example.com</span><span class="p">;</span>

    <span class="c1"># Let's Encrypt fetches proof-of-control files from here</span>
    <span class="kn">location</span> <span class="n">/.well-known/acme-challenge/</span> <span class="p">{</span>
        <span class="kn">root</span> <span class="n">/var/www/certbot</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="c1"># Everything else moves to HTTPS</span>
    <span class="kn">location</span> <span class="n">/</span> <span class="p">{</span>
        <span class="kn">return</span> <span class="mi">301</span> <span class="s">https://</span><span class="nv">$host$request_uri</span><span class="p">;</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">location /.well-known/acme-challenge/</code></strong> with <strong><code class="language-plaintext highlighter-rouge">root /var/www/certbot</code></strong>: requests under that path are served from the challenge directory, which we’ll mount from the host.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">return 301 https://$host$request_uri</code></strong>: a permanent redirect to the same host and path over HTTPS. Plain HTTP serves nothing else.</li>
</ul>

<p>Start Nginx with the challenge directory mounted:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">sudo mkdir</span> <span class="nt">-p</span> /srv/certbot
docker <span class="nb">rm</span> <span class="nt">-f</span> proxy
docker run <span class="nt">-d</span> <span class="nt">--name</span> proxy <span class="se">\</span>
  <span class="nt">--network</span> web <span class="se">\</span>
  <span class="nt">--restart</span> unless-stopped <span class="se">\</span>
  <span class="nt">-p</span> 80:80 <span class="nt">-p</span> 443:443 <span class="se">\</span>
  <span class="nt">-v</span> ~/nginx/conf.d:/etc/nginx/conf.d:ro <span class="se">\</span>
  <span class="nt">-v</span> /srv/certbot:/var/www/certbot:ro <span class="se">\</span>
  <span class="nt">-v</span> /etc/letsencrypt:/etc/letsencrypt:ro <span class="se">\</span>
  nginx:1.27
</code></pre></div></div>

<p>Mount the whole <code class="language-plaintext highlighter-rouge">/etc/letsencrypt</code> directory, not just <code class="language-plaintext highlighter-rouge">live/</code>: the files in <code class="language-plaintext highlighter-rouge">live/</code> are symlinks into <code class="language-plaintext highlighter-rouge">archive/</code>, and they’d dangle inside the container without it.</p>

<h3 id="3b-get-the-certificate">3b. Get the certificate</h3>

<p>Install certbot on the host (<code class="language-plaintext highlighter-rouge">sudo apt install certbot</code>), then:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">sudo </span>certbot certonly <span class="nt">--webroot</span> <span class="nt">-w</span> /srv/certbot <span class="se">\</span>
  <span class="nt">-d</span> example.com <span class="nt">-d</span> www.example.com <span class="se">\</span>
  <span class="nt">--email</span> you@example.com <span class="nt">--agree-tos</span>
</code></pre></div></div>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">certonly</code></strong>: obtain the certificate, but don’t try to edit any web server config; we manage Nginx ourselves.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">--webroot -w /srv/certbot</code></strong>: write the challenge file into <code class="language-plaintext highlighter-rouge">/srv/certbot</code>, which Nginx serves from step 3a.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">-d</code></strong>: every hostname the certificate should cover.</li>
</ul>

<p>The certificate and key land in <code class="language-plaintext highlighter-rouge">/etc/letsencrypt/live/example.com/</code>, which the container can already see.</p>

<h3 id="3c-add-the-https-server">3c. Add the HTTPS server</h3>

<p>Append a second block to <code class="language-plaintext highlighter-rouge">default.conf</code>:</p>

<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">server</span> <span class="p">{</span>
    <span class="kn">listen</span> <span class="mi">443</span> <span class="s">ssl</span><span class="p">;</span>
    <span class="kn">http2</span> <span class="no">on</span><span class="p">;</span>
    <span class="kn">server_name</span> <span class="s">example.com</span> <span class="s">www.example.com</span><span class="p">;</span>

    <span class="kn">ssl_certificate</span>     <span class="n">/etc/letsencrypt/live/example.com/fullchain.pem</span><span class="p">;</span>
    <span class="kn">ssl_certificate_key</span> <span class="n">/etc/letsencrypt/live/example.com/privkey.pem</span><span class="p">;</span>
    <span class="kn">ssl_protocols</span>       <span class="s">TLSv1.2</span> <span class="s">TLSv1.3</span><span class="p">;</span>

    <span class="kn">location</span> <span class="n">/</span> <span class="p">{</span>
        <span class="kn">proxy_pass</span> <span class="s">http://app:3000</span><span class="p">;</span>
        <span class="kn">proxy_set_header</span> <span class="s">Host</span>              <span class="nv">$host</span><span class="p">;</span>
        <span class="kn">proxy_set_header</span> <span class="s">X-Real-IP</span>         <span class="nv">$remote_addr</span><span class="p">;</span>
        <span class="kn">proxy_set_header</span> <span class="s">X-Forwarded-For</span>   <span class="nv">$proxy_add_x_forwarded_for</span><span class="p">;</span>
        <span class="kn">proxy_set_header</span> <span class="s">X-Forwarded-Proto</span> <span class="nv">$scheme</span><span class="p">;</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">listen 443 ssl</code></strong> and <strong><code class="language-plaintext highlighter-rouge">http2 on</code></strong>: TLS on port 443, with HTTP/2 enabled. (<code class="language-plaintext highlighter-rouge">http2 on</code> is the current syntax; older guides put <code class="language-plaintext highlighter-rouge">http2</code> on the <code class="language-plaintext highlighter-rouge">listen</code> line.)</li>
  <li><strong><code class="language-plaintext highlighter-rouge">ssl_certificate</code></strong>: <code class="language-plaintext highlighter-rouge">fullchain.pem</code> is your certificate <em>plus</em> the intermediate certificates; browsers need the full chain.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">ssl_certificate_key</code></strong>: the private key. It never leaves the host, and it’s mounted read-only.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">ssl_protocols TLSv1.2 TLSv1.3</code></strong>: refuse the old, broken protocol versions.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">location /</code></strong>: the same proxy settings as before, now reached over HTTPS.</li>
</ul>

<p>Test the config, then reload it without dropping connections:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker <span class="nb">exec </span>proxy nginx <span class="nt">-t</span>          <span class="c"># syntax check; fix anything it reports first</span>
docker <span class="nb">exec </span>proxy nginx <span class="nt">-s</span> reload   <span class="c"># apply without restarting the container</span>
</code></pre></div></div>

<h3 id="3d-renewal">3d. Renewal</h3>

<p>Let’s Encrypt certificates last 90 days. The certbot package installs a timer that renews them automatically; Nginx only needs to reload afterwards to pick up the new files. Certbot runs every executable script in its deploy-hooks directory after a successful renewal, so add one:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">sudo tee</span> /etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh <span class="o">&gt;</span> /dev/null <span class="o">&lt;&lt;</span><span class="sh">'</span><span class="no">EOF</span><span class="sh">'
#!/bin/sh
docker exec proxy nginx -s reload
</span><span class="no">EOF
</span><span class="nb">sudo chmod</span> +x /etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh

<span class="nb">sudo </span>certbot renew <span class="nt">--dry-run</span>
</code></pre></div></div>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">tee ... &lt;&lt;'EOF'</code></strong>: write the script as root (a plain <code class="language-plaintext highlighter-rouge">&gt;</code> redirect would run as your user and fail on a root-owned directory).</li>
  <li><strong><code class="language-plaintext highlighter-rouge">deploy/</code></strong>: hooks here run only when a certificate was actually renewed, not on every check.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">--dry-run</code></strong>: rehearses a full renewal against Let’s Encrypt’s staging server without replacing your certificate. If it passes, real renewals will too, and each one reloads Nginx on its own.</li>
</ul>

<h2 id="day-to-day-commands">Day-to-day commands</h2>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker logs <span class="nt">-f</span> proxy                 <span class="c"># access and error log, live</span>
docker <span class="nb">exec </span>proxy nginx <span class="nt">-t</span>           <span class="c"># validate config after editing</span>
docker <span class="nb">exec </span>proxy nginx <span class="nt">-s</span> reload    <span class="c"># apply it</span>
docker <span class="nb">exec</span> <span class="nt">-it</span> proxy sh             <span class="c"># look around inside (Debian-based image: bash works too)</span>
</code></pre></div></div>

<p>Because the config, content and certificates all live on the host, upgrading Nginx is just a matter of pulling the new tag and recreating the container with the same <code class="language-plaintext highlighter-rouge">docker run</code> line. Nothing inside the old container needs saving. Typing those long <code class="language-plaintext highlighter-rouge">docker run</code> commands by hand gets old quickly, though; <a href="/portfolio-site/blog/2025/07/16/chapter-1-9-docker-compose/">Chapter 1.9</a> moves this whole setup into a Compose file.</p>

<p><a href="/portfolio-site/blog/2025/07/12/chapter-1-4-docker-jenkins/">Chapter 1.4</a> runs a service with more moving parts: Jenkins, building and deploying projects inside containers of its own.</p>]]></content><author><name>Echo Yin</name></author><category term="devops" /><category term="Platform Engineering" /><category term="DevOps" /><category term="Chapter One" /><category term="Docker" /><summary type="html"><![CDATA[Run Nginx as a container three ways: serving a static site, proxying to an app container over a Docker network, and terminating HTTPS with Let's Encrypt certificates that renew without downtime. Every config block is explained line by line.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://e-choness.github.io/portfolio-site/assets/images/blogs/docker-nginx.webp" /><media:content medium="image" url="https://e-choness.github.io/portfolio-site/assets/images/blogs/docker-nginx.webp" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Chapter 1.4 - Jenkins in Docker: Every Build in a Clean Container</title><link href="https://e-choness.github.io/portfolio-site/blog/2025/07/12/chapter-1-4-docker-jenkins/" rel="alternate" type="text/html" title="Chapter 1.4 - Jenkins in Docker: Every Build in a Clean Container" /><published>2025-07-12T00:00:00+00:00</published><updated>2025-07-12T00:00:00+00:00</updated><id>https://e-choness.github.io/portfolio-site/blog/2025/07/12/chapter-1-4-docker-jenkins</id><content type="html" xml:base="https://e-choness.github.io/portfolio-site/blog/2025/07/12/chapter-1-4-docker-jenkins/"><![CDATA[<p>A long-lived Jenkins server tends to accumulate things: three Node versions, two JDKs, a Maven someone upgraded by hand. Builds start depending on whatever happens to be installed, and nobody dares touch the machine.</p>

<p>Docker removes that problem at both ends:</p>

<ul>
  <li><strong>Jenkins itself runs in a container</strong>, with its state in a volume. Upgrading means pulling a new image.</li>
  <li><strong>Every build runs in a fresh container</strong> of whatever toolchain the project asks for: <code class="language-plaintext highlighter-rouge">node:22</code> for one job, <code class="language-plaintext highlighter-rouge">maven:3.9</code> for the next. Nothing is installed on the server, and two projects can use different versions side by side.</li>
</ul>

<h2 id="how-the-pieces-fit">How the pieces fit</h2>

<p>The Jenkins container doesn’t run Docker <em>inside</em> itself. It gets the host’s Docker socket mounted in, so when a pipeline asks for a <code class="language-plaintext highlighter-rouge">node:22</code> container, the host’s daemon starts it as a <strong>sibling</strong> of Jenkins:</p>

<pre><code class="language-mermaid">flowchart TD
  dev([Developer]) -- "Build with Parameters" --&gt; J
  G[(Git server)] -- checkout --&gt; J
  subgraph Host["Server (Docker host)"]
    J["jenkins container · Docker CLI only"] -- "/var/run/docker.sock" --&gt; D[(Host Docker daemon)]
    D -- "docker run" --&gt; N["node:22 build container · workspace shared"]
    D -- "docker run" --&gt; M["maven build container · ~/.m2 cache mounted"]
  end
  N -- "scp dist/" --&gt; T[(Deploy target)]
  M -- "scp jar + ssh restart" --&gt; T
</code></pre>

<p><strong>A security note before you start.</strong> Access to the Docker socket is root access to the host: anything that can talk to it can start a privileged container that mounts <code class="language-plaintext highlighter-rouge">/</code>. Mounting it into Jenkins means that anyone who can edit a Jenkinsfile, or log in to Jenkins, effectively has root on this server. That’s acceptable for a team’s own build box; it’s not acceptable on a machine shared with things you need to protect. The alternative is dedicated build agents, where the controller never touches Docker itself.</p>

<h2 id="1-a-jenkins-image-with-the-docker-cli">1. A Jenkins image with the Docker CLI</h2>

<p>The official image doesn’t include the <code class="language-plaintext highlighter-rouge">docker</code> command, and the plugins we need have to be installed. Create a <code class="language-plaintext highlighter-rouge">Dockerfile</code>:</p>

<div class="language-dockerfile highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">FROM</span><span class="s"> jenkins/jenkins:lts-jdk21</span>

<span class="k">USER</span><span class="s"> root</span>

<span class="c"># Docker CLI only (no daemon): the static binary from download.docker.com</span>
<span class="k">ARG</span><span class="s"> DOCKER_VERSION=27.3.1</span>
<span class="k">RUN </span>curl <span class="nt">-fsSL</span> <span class="s2">"https://download.docker.com/linux/static/stable/x86_64/docker-</span><span class="k">${</span><span class="nv">DOCKER_VERSION</span><span class="k">}</span><span class="s2">.tgz"</span> <span class="se">\
</span>    | <span class="nb">tar</span> <span class="nt">-xz</span> <span class="nt">--strip-components</span><span class="o">=</span>1 <span class="nt">-C</span> /usr/local/bin docker/docker

<span class="c"># The socket belongs to the host's "docker" group. The same GID inside the</span>
<span class="c"># image lets the jenkins user use it without being root.</span>
<span class="k">ARG</span><span class="s"> DOCKER_GID=999</span>
<span class="k">RUN </span><span class="o">(</span>getent group <span class="k">${</span><span class="nv">DOCKER_GID</span><span class="k">}</span> <span class="o">||</span> groupadd <span class="nt">-g</span> <span class="k">${</span><span class="nv">DOCKER_GID</span><span class="k">}</span> docker<span class="o">)</span> <span class="se">\
</span>    <span class="o">&amp;&amp;</span> usermod <span class="nt">-aG</span> <span class="k">${</span><span class="nv">DOCKER_GID</span><span class="k">}</span> jenkins

<span class="k">USER</span><span class="s"> jenkins</span>

<span class="c"># Plugins baked into the image, so a rebuilt container comes up ready</span>
<span class="k">RUN </span>jenkins-plugin-cli <span class="nt">--plugins</span> <span class="se">\
</span>    workflow-aggregator <span class="se">\
</span>    docker-workflow <span class="se">\
</span>    git <span class="se">\
</span>    credentials-binding <span class="se">\
</span>    ssh-credentials <span class="se">\
</span>    junit
</code></pre></div></div>

<p>Line by line:</p>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">FROM jenkins/jenkins:lts-jdk21</code></strong>: the Long-Term Support line on Java 21. LTS releases are the ones to run in production; weekly releases change too often.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">USER root</code></strong>: package-level changes need root; we switch back afterwards.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">ARG DOCKER_VERSION</code> + <code class="language-plaintext highlighter-rouge">RUN curl … | tar</code></strong>: download Docker’s static binaries and extract only the <code class="language-plaintext highlighter-rouge">docker</code> client into <code class="language-plaintext highlighter-rouge">/usr/local/bin</code>. <code class="language-plaintext highlighter-rouge">--strip-components=1</code> drops the <code class="language-plaintext highlighter-rouge">docker/</code> directory prefix from the archive. Keep the CLI version close to the host’s daemon version.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">ARG DOCKER_GID</code> + <code class="language-plaintext highlighter-rouge">groupadd</code>/<code class="language-plaintext highlighter-rouge">usermod</code></strong>: this is the step most setups get wrong. On the host, <code class="language-plaintext highlighter-rouge">/var/run/docker.sock</code> is owned by the group <code class="language-plaintext highlighter-rouge">docker</code> with some numeric ID (often 999, but it varies). File permissions are checked by <em>number</em>, so the jenkins user must belong to a group with that same GID or every build fails with <code class="language-plaintext highlighter-rouge">permission denied … docker.sock</code>. <code class="language-plaintext highlighter-rouge">getent group ${DOCKER_GID} || groupadd …</code> creates the group only if no group in the image already has that number; <code class="language-plaintext highlighter-rouge">usermod -aG</code> accepts the number either way.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">USER jenkins</code></strong>: Jenkins runs unprivileged, as in the official image.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">jenkins-plugin-cli --plugins …</code></strong>: installs plugins at build time. <code class="language-plaintext highlighter-rouge">workflow-aggregator</code> is Pipeline itself, <code class="language-plaintext highlighter-rouge">docker-workflow</code> lets pipelines run in containers, <code class="language-plaintext highlighter-rouge">credentials-binding</code> and <code class="language-plaintext highlighter-rouge">ssh-credentials</code> handle secrets, and <code class="language-plaintext highlighter-rouge">junit</code> publishes test reports.</li>
</ul>

<p>Build it with the host’s docker GID:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker build <span class="se">\</span>
  <span class="nt">--build-arg</span> <span class="nv">DOCKER_GID</span><span class="o">=</span><span class="s2">"</span><span class="si">$(</span>getent group docker | <span class="nb">cut</span> <span class="nt">-d</span>: <span class="nt">-f3</span><span class="si">)</span><span class="s2">"</span> <span class="se">\</span>
  <span class="nt">-t</span> my-jenkins:lts-jdk21 <span class="nb">.</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">getent group docker</code> prints <code class="language-plaintext highlighter-rouge">docker:x:999:…</code>; <code class="language-plaintext highlighter-rouge">cut -d: -f3</code> takes the third colon-separated field, the GID. Run this on the server that will host Jenkins, or pass that server’s number.</p>

<h2 id="2-run-it-with-compose">2. Run it with Compose</h2>

<p>Save as <code class="language-plaintext highlighter-rouge">compose.yml</code> next to the Dockerfile:</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">services</span><span class="pi">:</span>
  <span class="na">jenkins</span><span class="pi">:</span>
    <span class="na">image</span><span class="pi">:</span> <span class="s">my-jenkins:lts-jdk21</span>
    <span class="na">restart</span><span class="pi">:</span> <span class="s">unless-stopped</span>
    <span class="na">ports</span><span class="pi">:</span>
      <span class="pi">-</span> <span class="s2">"</span><span class="s">8086:8080"</span>
    <span class="na">volumes</span><span class="pi">:</span>
      <span class="pi">-</span> <span class="s">jenkins_home:/var/jenkins_home</span>
      <span class="pi">-</span> <span class="s">/var/run/docker.sock:/var/run/docker.sock</span>

<span class="na">volumes</span><span class="pi">:</span>
  <span class="na">jenkins_home</span><span class="pi">:</span>
</code></pre></div></div>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">ports: "8086:8080"</code></strong>: the web UI on host port 8086. Port 50000, which you’ll see in other guides, is only for inbound agents; this setup doesn’t use any.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">jenkins_home:/var/jenkins_home</code></strong>: <em>all</em> Jenkins state (jobs, build history, credentials, plugins) lives here. Back up this volume and you’ve backed up Jenkins.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">/var/run/docker.sock:/var/run/docker.sock</code></strong>: the host’s Docker socket, as discussed above.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">restart: unless-stopped</code></strong>: come back after reboots.</li>
</ul>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker compose up <span class="nt">-d</span>
docker compose logs <span class="nt">-f</span> jenkins          <span class="c"># wait for "Jenkins is fully up and running"</span>
docker compose <span class="nb">exec </span>jenkins <span class="nb">cat</span> /var/jenkins_home/secrets/initialAdminPassword
</code></pre></div></div>

<p>Open <code class="language-plaintext highlighter-rouge">http://your-server:8086</code>, paste the initial admin password, choose <strong>Install suggested plugins</strong>, and create your admin user. To check the Docker wiring, run <code class="language-plaintext highlighter-rouge">docker compose exec jenkins docker ps</code>: it should list the Jenkins container itself.</p>

<p><code class="language-plaintext highlighter-rouge">docker compose down</code> stops and removes the container but <strong>keeps</strong> the <code class="language-plaintext highlighter-rouge">jenkins_home</code> volume; only <code class="language-plaintext highlighter-rouge">down -v</code> deletes it.</p>

<h2 id="3-credentials">3. Credentials</h2>

<p>Deployments need an SSH key that the target server accepts. Generate a dedicated one, never your personal key:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>ssh-keygen <span class="nt">-t</span> ed25519 <span class="nt">-f</span> jenkins_deploy <span class="nt">-C</span> <span class="s2">"jenkins deploy"</span> <span class="nt">-N</span> <span class="s2">""</span>
ssh-copy-id <span class="nt">-i</span> jenkins_deploy.pub deploy@203.0.113.20
</code></pre></div></div>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">-f jenkins_deploy</code></strong>: write the pair to <code class="language-plaintext highlighter-rouge">jenkins_deploy</code> and <code class="language-plaintext highlighter-rouge">jenkins_deploy.pub</code>.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">-N ""</code></strong>: no passphrase, since Jenkins has to use it unattended; protect it through Jenkins’ credential store instead.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">ssh-copy-id</code></strong>: appends the public key to the <code class="language-plaintext highlighter-rouge">deploy</code> user’s <code class="language-plaintext highlighter-rouge">authorized_keys</code> on the target.</li>
</ul>

<p>In Jenkins, go to <strong>Manage Jenkins → Credentials → (global) → Add Credentials</strong>, choose <strong>SSH Username with private key</strong>, set the ID to <code class="language-plaintext highlighter-rouge">deploy-key</code>, the username to <code class="language-plaintext highlighter-rouge">deploy</code>, and paste the contents of <code class="language-plaintext highlighter-rouge">jenkins_deploy</code>. Add your Git credentials the same way if the repositories are private. Then delete the private key file from wherever you generated it.</p>

<h2 id="4-a-nodejs-pipeline">4. A Node.js pipeline</h2>

<p>Create a <strong>Pipeline</strong> job, set <strong>Definition</strong> to <strong>Pipeline script from SCM</strong>, point it at the application’s repository, and commit this as <code class="language-plaintext highlighter-rouge">Jenkinsfile</code> in that repository:</p>

<div class="language-groovy highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">pipeline</span> <span class="o">{</span>
    <span class="n">agent</span> <span class="o">{</span>
        <span class="n">docker</span> <span class="o">{</span>
            <span class="n">image</span> <span class="s1">'node:22'</span>
            <span class="n">args</span> <span class="s1">'-v /var/cache/jenkins-npm:/tmp/npm-cache'</span>
        <span class="o">}</span>
    <span class="o">}</span>

    <span class="n">parameters</span> <span class="o">{</span>
        <span class="n">choice</span><span class="o">(</span><span class="nl">name:</span> <span class="s1">'TARGET'</span><span class="o">,</span> <span class="nl">choices:</span> <span class="o">[</span><span class="s1">'staging'</span><span class="o">,</span> <span class="s1">'production'</span><span class="o">],</span> <span class="nl">description:</span> <span class="s1">'Where to deploy'</span><span class="o">)</span>
    <span class="o">}</span>

    <span class="n">environment</span> <span class="o">{</span>
        <span class="n">DEPLOY_DIR</span> <span class="o">=</span> <span class="s1">'/var/www/shop'</span>
    <span class="o">}</span>

    <span class="n">stages</span> <span class="o">{</span>
        <span class="n">stage</span><span class="o">(</span><span class="s1">'Install'</span><span class="o">)</span> <span class="o">{</span>
            <span class="n">steps</span> <span class="o">{</span>
                <span class="n">sh</span> <span class="s1">'npm ci --cache /tmp/npm-cache'</span>
            <span class="o">}</span>
        <span class="o">}</span>
        <span class="n">stage</span><span class="o">(</span><span class="s1">'Test'</span><span class="o">)</span> <span class="o">{</span>
            <span class="n">steps</span> <span class="o">{</span>
                <span class="n">sh</span> <span class="s1">'npm test'</span>
            <span class="o">}</span>
        <span class="o">}</span>
        <span class="n">stage</span><span class="o">(</span><span class="s1">'Build'</span><span class="o">)</span> <span class="o">{</span>
            <span class="n">steps</span> <span class="o">{</span>
                <span class="n">sh</span> <span class="s1">'npm run build'</span>
            <span class="o">}</span>
        <span class="o">}</span>
        <span class="n">stage</span><span class="o">(</span><span class="s1">'Deploy'</span><span class="o">)</span> <span class="o">{</span>
            <span class="n">steps</span> <span class="o">{</span>
                <span class="n">script</span> <span class="o">{</span>
                    <span class="n">env</span><span class="o">.</span><span class="na">DEPLOY_HOST</span> <span class="o">=</span> <span class="n">params</span><span class="o">.</span><span class="na">TARGET</span> <span class="o">==</span> <span class="s1">'production'</span> <span class="o">?</span> <span class="s1">'203.0.113.20'</span> <span class="o">:</span> <span class="s1">'203.0.113.21'</span>
                <span class="o">}</span>
                <span class="n">withCredentials</span><span class="o">([</span><span class="n">sshUserPrivateKey</span><span class="o">(</span><span class="nl">credentialsId:</span> <span class="s1">'deploy-key'</span><span class="o">,</span>
                                                   <span class="nl">keyFileVariable:</span> <span class="s1">'SSH_KEY'</span><span class="o">,</span>
                                                   <span class="nl">usernameVariable:</span> <span class="s1">'SSH_USER'</span><span class="o">)])</span> <span class="o">{</span>
                    <span class="n">sh</span> <span class="s1">'''
                        ssh -i "$SSH_KEY" -o StrictHostKeyChecking=accept-new \
                            "$SSH_USER@$DEPLOY_HOST" "rm -rf $DEPLOY_DIR/next &amp;&amp; mkdir -p $DEPLOY_DIR/next"
                        scp -i "$SSH_KEY" -o StrictHostKeyChecking=accept-new -r dist/. \
                            "$SSH_USER@$DEPLOY_HOST:$DEPLOY_DIR/next/"
                        ssh -i "$SSH_KEY" "$SSH_USER@$DEPLOY_HOST" \
                            "rm -rf $DEPLOY_DIR/previous; mv $DEPLOY_DIR/current $DEPLOY_DIR/previous 2&gt;/dev/null; mv $DEPLOY_DIR/next $DEPLOY_DIR/current"
                    '''</span>
                <span class="o">}</span>
            <span class="o">}</span>
        <span class="o">}</span>
    <span class="o">}</span>

    <span class="n">post</span> <span class="o">{</span>
        <span class="n">success</span> <span class="o">{</span> <span class="n">echo</span> <span class="s2">"Deployed to ${params.TARGET}"</span> <span class="o">}</span>
        <span class="n">failure</span> <span class="o">{</span> <span class="n">echo</span> <span class="s1">'Build failed; check the stage logs above'</span> <span class="o">}</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<p>Block by block:</p>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">agent { docker { image 'node:22' … } }</code></strong>: run the whole pipeline inside a <code class="language-plaintext highlighter-rouge">node:22</code> container. Jenkins checks out the repository first and shares the workspace with the container (when Jenkins itself runs in a container, the plugin does this with <code class="language-plaintext highlighter-rouge">--volumes-from</code>), so <code class="language-plaintext highlighter-rouge">npm</code> sees your code.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">args '-v /var/cache/jenkins-npm:/tmp/npm-cache'</code></strong>: extra <code class="language-plaintext highlighter-rouge">docker run</code> arguments. <strong>The left side is a path on the Docker host</strong>, not inside the Jenkins container, because it’s the host’s daemon that starts the build container. Create it once on the server with <code class="language-plaintext highlighter-rouge">sudo mkdir -p /var/cache/jenkins-npm &amp;&amp; sudo chown 1000:1000 /var/cache/jenkins-npm</code>: builds run as Jenkins’ user ID, 1000.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">parameters { choice(...) }</code></strong>: adds a <strong>Build with Parameters</strong> dropdown. Jenkins registers parameters on the first run, so that run uses the defaults.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">environment { DEPLOY_DIR = … }</code></strong>: variables available to every <code class="language-plaintext highlighter-rouge">sh</code> step.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">npm ci --cache /tmp/npm-cache</code></strong>: install exactly what <code class="language-plaintext highlighter-rouge">package-lock.json</code> specifies, with downloads cached on the host between builds.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">stage('Test')</code></strong>: a failing command fails the stage, and the pipeline stops before anything is deployed.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">script { env.DEPLOY_HOST = … }</code></strong>: a bit of Groovy to pick the target host from the parameter.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">withCredentials([sshUserPrivateKey(...)])</code></strong>: writes the <code class="language-plaintext highlighter-rouge">deploy-key</code> credential to a temporary file for the duration of the block and exposes its path as <code class="language-plaintext highlighter-rouge">$SSH_KEY</code> and the username as <code class="language-plaintext highlighter-rouge">$SSH_USER</code>. The key is masked in the log and deleted afterwards.</li>
  <li><strong>The <code class="language-plaintext highlighter-rouge">sh '''…'''</code> block</strong>: uploads into a fresh <code class="language-plaintext highlighter-rouge">next/</code> directory, then swaps it into place, keeping the old release as <code class="language-plaintext highlighter-rouge">previous/</code>. A half-finished upload never serves traffic, and rolling back is one <code class="language-plaintext highlighter-rouge">mv</code>.
    <ul>
      <li><code class="language-plaintext highlighter-rouge">StrictHostKeyChecking=accept-new</code> trusts a server’s host key the first time and refuses if it later changes. That’s safer than the common <code class="language-plaintext highlighter-rouge">=no</code>, which accepts anything, including an attacker.</li>
      <li>The triple single quotes matter: Groovy doesn’t interpolate <code class="language-plaintext highlighter-rouge">'''</code> strings, so <code class="language-plaintext highlighter-rouge">$SSH_KEY</code> is expanded by the shell, which keeps the secret out of Groovy and out of the logs.</li>
    </ul>
  </li>
  <li><strong><code class="language-plaintext highlighter-rouge">post { … }</code></strong>: runs after all stages, by outcome. This is the place for chat notifications.</li>
</ul>

<h2 id="5-a-java--maven-pipeline">5. A Java / Maven pipeline</h2>

<p>For Maven there’s no need for a custom image: the official <code class="language-plaintext highlighter-rouge">maven</code> images bundle a JDK.</p>

<div class="language-groovy highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">pipeline</span> <span class="o">{</span>
    <span class="n">agent</span> <span class="o">{</span>
        <span class="n">docker</span> <span class="o">{</span>
            <span class="n">image</span> <span class="s1">'maven:3.9-eclipse-temurin-21'</span>
            <span class="n">args</span> <span class="s1">'-v /var/cache/jenkins-m2:/var/maven/.m2'</span>
        <span class="o">}</span>
    <span class="o">}</span>

    <span class="n">environment</span> <span class="o">{</span>
        <span class="n">DEPLOY_HOST</span> <span class="o">=</span> <span class="s1">'203.0.113.20'</span>
        <span class="n">APP_DIR</span>     <span class="o">=</span> <span class="s1">'/opt/shop-api'</span>
    <span class="o">}</span>

    <span class="n">stages</span> <span class="o">{</span>
        <span class="n">stage</span><span class="o">(</span><span class="s1">'Build &amp; test'</span><span class="o">)</span> <span class="o">{</span>
            <span class="n">steps</span> <span class="o">{</span>
                <span class="n">sh</span> <span class="s1">'mvn -B -Dmaven.repo.local=/var/maven/.m2/repository clean package'</span>
            <span class="o">}</span>
        <span class="o">}</span>
        <span class="n">stage</span><span class="o">(</span><span class="s1">'Deploy'</span><span class="o">)</span> <span class="o">{</span>
            <span class="n">steps</span> <span class="o">{</span>
                <span class="n">withCredentials</span><span class="o">([</span><span class="n">sshUserPrivateKey</span><span class="o">(</span><span class="nl">credentialsId:</span> <span class="s1">'deploy-key'</span><span class="o">,</span>
                                                   <span class="nl">keyFileVariable:</span> <span class="s1">'SSH_KEY'</span><span class="o">,</span>
                                                   <span class="nl">usernameVariable:</span> <span class="s1">'SSH_USER'</span><span class="o">)])</span> <span class="o">{</span>
                    <span class="n">sh</span> <span class="s1">'''
                        scp -i "$SSH_KEY" -o StrictHostKeyChecking=accept-new \
                            target/shop-api.jar "$SSH_USER@$DEPLOY_HOST:$APP_DIR/shop-api.jar.new"
                        ssh -i "$SSH_KEY" "$SSH_USER@$DEPLOY_HOST" \
                            "mv $APP_DIR/shop-api.jar.new $APP_DIR/shop-api.jar &amp;&amp; sudo systemctl restart shop-api"
                    '''</span>
                <span class="o">}</span>
            <span class="o">}</span>
        <span class="o">}</span>
    <span class="o">}</span>

    <span class="n">post</span> <span class="o">{</span>
        <span class="n">always</span> <span class="o">{</span>
            <span class="n">junit</span> <span class="nl">allowEmptyResults:</span> <span class="kc">true</span><span class="o">,</span> <span class="nl">testResults:</span> <span class="s1">'**/target/surefire-reports/*.xml'</span>
        <span class="o">}</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<p>What’s different from the Node pipeline:</p>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">image 'maven:3.9-eclipse-temurin-21'</code></strong>: Maven 3.9 on the Eclipse Temurin JDK 21. Match the JDK to your project; tags exist for 17, 21 and newer.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">-v /var/cache/jenkins-m2:/var/maven/.m2</code></strong> plus <strong><code class="language-plaintext highlighter-rouge">-Dmaven.repo.local=…</code></strong>: keep the downloaded dependency repository on the host between builds, so each build doesn’t re-download half of Maven Central. As before, the host directory must be owned by UID 1000.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">mvn -B</code></strong>: batch mode, with no interactive prompts and no download progress bars flooding the log.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">clean package</code></strong>: compile, run the unit tests, build the jar. A failing test fails the build.</li>
  <li><strong>Deploy</strong>: upload as <code class="language-plaintext highlighter-rouge">.jar.new</code>, then rename and restart in one SSH command, so the service never starts from a half-copied file. The <code class="language-plaintext highlighter-rouge">deploy</code> user needs a narrow sudo rule for exactly that one command: <code class="language-plaintext highlighter-rouge">deploy ALL=(root) NOPASSWD: /usr/bin/systemctl restart shop-api</code>.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">junit …</code></strong> in <code class="language-plaintext highlighter-rouge">post { always }</code>: publish the test results even when the build fails, which is exactly when you want to see them. Jenkins then shows test trends and failure details per build.</li>
</ul>

<h2 id="6-when-the-server-cant-reach-docker-hub">6. When the server can’t reach Docker Hub</h2>

<p>Some build servers sit on networks without internet access, or with registry access blocked. Images can be carried over as files: <code class="language-plaintext highlighter-rouge">docker save</code> writes an image, with all its layers, to a tar archive, and <code class="language-plaintext highlighter-rouge">docker load</code> reads it back.</p>

<p>On a machine that can pull:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker pull node:22
docker pull maven:3.9-eclipse-temurin-21
docker save <span class="nt">-o</span> build-images.tar node:22 maven:3.9-eclipse-temurin-21 my-jenkins:lts-jdk21
scp build-images.tar deploy@203.0.113.10:/tmp/
</code></pre></div></div>

<p>On the build server:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker load <span class="nt">-i</span> /tmp/build-images.tar
docker image <span class="nb">ls</span>          <span class="c"># the images appear with their original names and tags</span>
</code></pre></div></div>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">docker save -o file image …</code></strong>: several images can share one archive, and layers they have in common are stored once.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">docker load</code></strong> restores the names and tags too, so the Jenkinsfiles don’t change. Just make sure the tags match exactly what the pipelines ask for.</li>
</ul>

<p>If you do this often, run your own registry inside the network instead (<a href="/portfolio-site/blog/2025/07/11/chapter-1-2-docker-advanced/">Chapter 1.2</a>) and push the images there once.</p>

<h2 id="troubleshooting">Troubleshooting</h2>

<table>
  <thead>
    <tr>
      <th>Symptom</th>
      <th>Cause</th>
      <th>Fix</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">permission denied while trying to connect to the Docker daemon socket</code></td>
      <td>The <code class="language-plaintext highlighter-rouge">docker</code> group GID in the image doesn’t match the host’s.</td>
      <td>Rebuild with <code class="language-plaintext highlighter-rouge">--build-arg DOCKER_GID=$(getent group docker \| cut -d: -f3)</code>.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">docker: not found</code> in the build log</td>
      <td>The Jenkins image has no Docker CLI.</td>
      <td>Use the custom image from step 1.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">EACCES</code> writing to the npm or <code class="language-plaintext highlighter-rouge">.m2</code> cache</td>
      <td>The host cache directory isn’t owned by UID 1000.</td>
      <td><code class="language-plaintext highlighter-rouge">sudo chown -R 1000:1000 /var/cache/jenkins-npm</code>.</td>
    </tr>
    <tr>
      <td>Parameters missing on the first run</td>
      <td>Jenkins only learns about <code class="language-plaintext highlighter-rouge">parameters {}</code> by running the pipeline once.</td>
      <td>Run it once with the defaults.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">Host key verification failed</code></td>
      <td>The target’s host key changed, or was never accepted.</td>
      <td>Check that it’s really your server, then update <code class="language-plaintext highlighter-rouge">known_hosts</code>.</td>
    </tr>
  </tbody>
</table>

<p><a href="/portfolio-site/blog/2025/07/13/chapter-1-5-docker-gitlab/">Chapter 1.5</a> runs the other half of a self-hosted software pipeline: GitLab, with its container registry and CI runners.</p>]]></content><author><name>Echo Yin</name></author><category term="devops" /><category term="Platform Engineering" /><category term="DevOps" /><category term="Chapter One" /><category term="Docker" /><summary type="html"><![CDATA[Run Jenkins as a container and have every pipeline build inside a disposable container of its own: Node.js and Maven builds without installing either on the server, cached dependencies, SSH deploys, and how to get it all onto a server that can't reach Docker Hub. Each Jenkinsfile is broken down block by block.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://e-choness.github.io/portfolio-site/assets/images/blogs/docker-jenkins.webp" /><media:content medium="image" url="https://e-choness.github.io/portfolio-site/assets/images/blogs/docker-jenkins.webp" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Chapter 1.2 - Living with Containers: Lifecycle, Debugging and a Private Registry</title><link href="https://e-choness.github.io/portfolio-site/blog/2025/07/11/chapter-1-2-docker-advanced/" rel="alternate" type="text/html" title="Chapter 1.2 - Living with Containers: Lifecycle, Debugging and a Private Registry" /><published>2025-07-11T00:00:00+00:00</published><updated>2025-07-11T00:00:00+00:00</updated><id>https://e-choness.github.io/portfolio-site/blog/2025/07/11/chapter-1-2-docker-advanced</id><content type="html" xml:base="https://e-choness.github.io/portfolio-site/blog/2025/07/11/chapter-1-2-docker-advanced/"><![CDATA[<p><a href="/portfolio-site/blog/2025/07/10/chapter-1-1-docker-basics/">Chapter 1.1</a> built an image and ran it. This chapter is about everything that happens after <code class="language-plaintext highlighter-rouge">docker run</code>: keeping containers running, finding out why one isn’t, getting files in and out, cleaning up, and storing images somewhere other than Docker Hub.</p>

<h2 id="the-container-lifecycle">The container lifecycle</h2>

<p>A container moves through a small set of states, and almost every <code class="language-plaintext highlighter-rouge">docker</code> command is a transition between two of them:</p>

<pre><code class="language-mermaid">stateDiagram-v2
  [*] --&gt; Created: docker create
  [*] --&gt; Running: docker run
  Created --&gt; Running: docker start
  Running --&gt; Paused: docker pause
  Paused --&gt; Running: docker unpause
  Running --&gt; Exited: docker stop (SIGTERM, then SIGKILL)&lt;br/&gt;docker kill (SIGKILL)&lt;br/&gt;main process exits
  Exited --&gt; Running: docker start / docker restart
  Running --&gt; Running: docker restart
  Exited --&gt; [*]: docker rm
  Running --&gt; [*]: docker rm -f
</code></pre>

<p>Two things in that diagram surprise people:</p>

<ul>
  <li><strong>A container lives exactly as long as its main process.</strong> When the command in <code class="language-plaintext highlighter-rouge">CMD</code> exits, successfully or not, the container stops. A container that “starts and immediately exits” is a process that finished or crashed; its logs will say which.</li>
  <li><strong>Exited isn’t gone.</strong> A stopped container keeps its writable layer, its logs and its configuration until you <code class="language-plaintext highlighter-rouge">docker rm</code> it, which is why <code class="language-plaintext highlighter-rouge">docker start</code> can bring it back exactly as it was.</li>
</ul>

<h2 id="docker-run-flags-youll-actually-use"><code class="language-plaintext highlighter-rouge">docker run</code> flags you’ll actually use</h2>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker run <span class="nt">-d</span> <span class="se">\</span>
  <span class="nt">--name</span> api <span class="se">\</span>
  <span class="nt">-p</span> 8080:3000 <span class="se">\</span>
  <span class="nt">-e</span> <span class="nv">NODE_ENV</span><span class="o">=</span>production <span class="se">\</span>
  <span class="nt">--env-file</span> ./api.env <span class="se">\</span>
  <span class="nt">-v</span> api-data:/app/data <span class="se">\</span>
  <span class="nt">--restart</span> unless-stopped <span class="se">\</span>
  <span class="nt">--memory</span> 512m <span class="nt">--cpus</span> 1.5 <span class="se">\</span>
  <span class="nt">--network</span> backend <span class="se">\</span>
  yourname/api:1.4.2
</code></pre></div></div>

<table>
  <thead>
    <tr>
      <th>Flag</th>
      <th>What it does</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">-d</code></td>
      <td>Run in the background; print the container ID.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">--name api</code></td>
      <td>A stable name for every later command, instead of the random one Docker generates.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">-p 8080:3000</code></td>
      <td>Publish container port 3000 on host port 8080. Add an IP to limit exposure: <code class="language-plaintext highlighter-rouge">-p 127.0.0.1:8080:3000</code>.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">-e KEY=value</code></td>
      <td>Set an environment variable.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">--env-file ./api.env</code></td>
      <td>Load many variables from a file, one <code class="language-plaintext highlighter-rouge">KEY=value</code> per line. Keeps secrets out of your shell history.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">-v api-data:/app/data</code></td>
      <td>Mount a <strong>named volume</strong> at <code class="language-plaintext highlighter-rouge">/app/data</code>, so data survives the container. <code class="language-plaintext highlighter-rouge">-v /host/path:/app/data</code> mounts a host directory instead.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">--restart unless-stopped</code></td>
      <td>Restart policy, see below.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">--memory 512m --cpus 1.5</code></td>
      <td>cgroup limits: the container is killed if it exceeds 512 MB and can use at most 1.5 CPU cores.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">--network backend</code></td>
      <td>Attach to a user-defined network, where containers reach each other by name (<a href="/portfolio-site/blog/2025/07/14/chapter-1-8-docker-network/">Chapter 1.8</a>).</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">--rm</code></td>
      <td>Delete the container when it exits. Ideal for one-off commands; it works together with <code class="language-plaintext highlighter-rouge">-d</code>.</td>
    </tr>
  </tbody>
</table>

<p><strong>Restart policies</strong> decide what Docker does when the main process exits or the daemon restarts:</p>

<table>
  <thead>
    <tr>
      <th>Policy</th>
      <th>Restarts after a crash</th>
      <th>Restarts after a daemon restart / reboot</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">no</code> (default)</td>
      <td>no</td>
      <td>no</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">on-failure[:5]</code></td>
      <td>yes, on non-zero exit (optionally at most 5 times)</td>
      <td>depends on how it last exited; don’t rely on it</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">always</code></td>
      <td>yes</td>
      <td>yes, <strong>even if you had stopped it by hand</strong></td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">unless-stopped</code></td>
      <td>yes</td>
      <td>yes, unless you stopped it by hand</td>
    </tr>
  </tbody>
</table>

<p><code class="language-plaintext highlighter-rouge">unless-stopped</code> is what you usually want for services. Policies can be changed on an existing container without recreating it: <code class="language-plaintext highlighter-rouge">docker update --restart unless-stopped api</code>.</p>

<h2 id="seeing-whats-going-on">Seeing what’s going on</h2>

<h3 id="which-containers-exist">Which containers exist</h3>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker ps                                  <span class="c"># running</span>
docker ps <span class="nt">-a</span>                               <span class="c"># including stopped</span>
docker ps <span class="nt">-a</span> <span class="nt">--filter</span> <span class="nv">status</span><span class="o">=</span>exited        <span class="c"># only the stopped ones</span>
docker ps <span class="nt">--format</span> <span class="s2">"table {{.Names}}</span><span class="se">\t</span><span class="s2">{{.Status}}</span><span class="se">\t</span><span class="s2">{{.Ports}}"</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">--format</code> takes a Go template over each container’s fields. The example above prints a compact name/status/ports table, which is easier to scan than the default output when you run many containers.</p>

<h3 id="what-it-printed">What it printed</h3>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker logs api                    <span class="c"># everything the main process wrote to stdout/stderr</span>
docker logs <span class="nt">-f</span> <span class="nt">--tail</span> 100 api      <span class="c"># last 100 lines, then keep following</span>
docker logs <span class="nt">--since</span> 10m api        <span class="c"># only the last ten minutes</span>
</code></pre></div></div>

<p>Docker captures a container’s standard output and error. That’s why well-behaved container apps log to stdout instead of to files: <code class="language-plaintext highlighter-rouge">docker logs</code>, and every log collector built on top of it, only sees stdout and stderr.</p>

<h3 id="how-its-configured">How it’s configured</h3>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker inspect api                                          <span class="c"># full JSON: config, mounts, network, state</span>
docker inspect <span class="nt">-f</span> <span class="s1">'{{.State.Status}} {{.State.ExitCode}}'</span> api
docker inspect <span class="nt">-f</span> <span class="s1">'{{.NetworkSettings.Networks.backend.IPAddress}}'</span> api
docker inspect <span class="nt">-f</span> <span class="s1">'{{json .Mounts}}'</span> api
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">docker inspect</code> is the source of truth for “what did I actually start?” The <code class="language-plaintext highlighter-rouge">-f</code> templates pull out single fields:</p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">.State.Status</code> and <code class="language-plaintext highlighter-rouge">.State.ExitCode</code>: why a container stopped. Exit code <code class="language-plaintext highlighter-rouge">137</code> means it was killed with SIGKILL, very often by the kernel for exceeding its memory limit (<code class="language-plaintext highlighter-rouge">.State.OOMKilled</code> is then <code class="language-plaintext highlighter-rouge">true</code>). <code class="language-plaintext highlighter-rouge">143</code> means it exited on SIGTERM.</li>
  <li><code class="language-plaintext highlighter-rouge">.NetworkSettings.Networks.&lt;network&gt;.IPAddress</code>: its address on a given network.</li>
  <li><code class="language-plaintext highlighter-rouge">json .Mounts</code>: which volumes and host paths are mounted where.</li>
</ul>

<h3 id="what-its-using">What it’s using</h3>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker stats              <span class="c"># live CPU, memory, network and disk I/O per container</span>
docker top api            <span class="c"># processes inside the container, as seen from the host</span>
docker events             <span class="c"># a live feed of container starts, stops, OOM kills…</span>
</code></pre></div></div>

<h2 id="getting-inside">Getting inside</h2>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker <span class="nb">exec</span> <span class="nt">-it</span> api sh              <span class="c"># a shell in the running container (bash on Debian-based images)</span>
docker <span class="nb">exec </span>api <span class="nb">env</span>                 <span class="c"># run a single command and print its output</span>
docker <span class="nb">exec</span> <span class="nt">-u</span> root <span class="nt">-it</span> api sh      <span class="c"># as root, e.g. to install a debugging tool temporarily</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">docker exec</code> starts an <strong>additional</strong> process inside a running container. It’s the standard way in, and it doesn’t disturb the main process. You’ll also come across <code class="language-plaintext highlighter-rouge">docker attach</code>, which connects your terminal to the container’s <em>main</em> process: pressing Ctrl+C there sends the signal to your app and can stop the container. For debugging, use <code class="language-plaintext highlighter-rouge">exec</code>.</p>

<p>Minimal images often have no shell at all (see <a href="/portfolio-site/blog/2025/07/17/chapter-1-12-docker-multistage/">Chapter 1.12</a>). For those, <code class="language-plaintext highlighter-rouge">docker debug</code> (Docker Desktop) or a throwaway container sharing its namespaces gives you tools without changing the image:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker run <span class="nt">-it</span> <span class="nt">--rm</span> <span class="nt">--network</span> container:api <span class="nt">--pid</span> container:api busybox sh
</code></pre></div></div>

<ul>
  <li><code class="language-plaintext highlighter-rouge">--network container:api</code>: share the target’s network stack, so <code class="language-plaintext highlighter-rouge">localhost</code> is the app.</li>
  <li><code class="language-plaintext highlighter-rouge">--pid container:api</code>: share its process list, so <code class="language-plaintext highlighter-rouge">ps</code> shows the app’s processes.</li>
</ul>

<h3 id="copying-files-in-and-out">Copying files in and out</h3>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker <span class="nb">cp </span>api:/app/logs/error.log <span class="nb">.</span>          <span class="c"># container → host</span>
docker <span class="nb">cp</span> ./fixture.json api:/app/data/      <span class="c"># host → container</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">docker cp</code> works on stopped containers too, which is handy for pulling logs or crash dumps out of something that won’t start.</p>

<h2 id="changing-containers-and-why-you-mostly-shouldnt">Changing containers (and why you mostly shouldn’t)</h2>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker rename api api-old
docker update <span class="nt">--memory</span> 1g <span class="nt">--restart</span> unless-stopped api
docker commit api yourname/api:debug-snapshot
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">docker commit</code> saves a container’s current filesystem as a new image. It’s useful for capturing a broken state to investigate later, but don’t build images this way: nobody can see or reproduce what went into a committed image. Change the Dockerfile and rebuild instead.</p>

<h2 id="keeping-disk-usage-under-control">Keeping disk usage under control</h2>

<p>Images, stopped containers, unused volumes and build cache accumulate quickly on a build machine.</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker system <span class="nb">df</span>                 <span class="c"># what's using space, and how much is reclaimable</span>
docker container prune           <span class="c"># remove all stopped containers</span>
docker image prune               <span class="c"># remove dangling images (untagged leftovers from rebuilds)</span>
docker image prune <span class="nt">-a</span>            <span class="c"># remove every image not used by a container</span>
docker builder prune             <span class="c"># clear the build cache</span>
docker volume prune              <span class="c"># remove unused volumes (this deletes data)</span>
docker system prune              <span class="c"># containers + networks + dangling images in one go</span>
</code></pre></div></div>

<p>Everything except the first command asks for confirmation. Read the prompt, especially for <code class="language-plaintext highlighter-rouge">volume prune</code>: a volume that isn’t attached to a container <em>right now</em> may still hold a database you care about.</p>

<h2 id="running-your-own-registry">Running your own registry</h2>

<p>Docker Hub works until you need private images without a subscription, a machine without internet access, or faster pulls inside your own network. Docker publishes a registry server as an image:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker run <span class="nt">-d</span> <span class="nt">--name</span> registry <span class="se">\</span>
  <span class="nt">-p</span> 5000:5000 <span class="se">\</span>
  <span class="nt">-v</span> registry-data:/var/lib/registry <span class="se">\</span>
  <span class="nt">--restart</span> unless-stopped <span class="se">\</span>
  registry:2
</code></pre></div></div>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">-p 5000:5000</code></strong>: the registry’s HTTP API.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">-v registry-data:/var/lib/registry</code></strong>: the images themselves, kept in a volume so they survive the container.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">registry:2</code></strong>: the official registry server, latest 2.x release.</li>
</ul>

<p><code class="language-plaintext highlighter-rouge">curl http://localhost:5000/v2/</code> answers <code class="language-plaintext highlighter-rouge">{}</code> when it’s up. Pushing an image there is just a matter of naming it with the registry’s address:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker tag hello-docker:1.0 localhost:5000/hello-docker:1.0
docker push localhost:5000/hello-docker:1.0
curl http://localhost:5000/v2/_catalog        <span class="c"># {"repositories":["hello-docker"]}</span>
</code></pre></div></div>

<h3 id="using-it-from-other-machines">Using it from other machines</h3>

<p>Docker only speaks HTTPS to registries, with one exception: addresses on <code class="language-plaintext highlighter-rouge">127.0.0.0/8</code>, which is why <code class="language-plaintext highlighter-rouge">localhost:5000</code> worked above. From another machine, <code class="language-plaintext highlighter-rouge">docker push 192.168.1.10:5000/hello-docker:1.0</code> fails with <code class="language-plaintext highlighter-rouge">http: server gave HTTP response to HTTPS client</code>. There are two fixes:</p>

<ol>
  <li><strong>Put TLS in front of it</strong> (Nginx with a real certificate, <a href="/portfolio-site/blog/2025/07/12/chapter-1-3-docker-nginx/">Chapter 1.3</a>), or run the registry with its own certificate. This is the right answer for anything shared.</li>
  <li><strong>For a lab network only</strong>, tell each client’s daemon to accept plain HTTP for that one address. On Linux, edit <code class="language-plaintext highlighter-rouge">/etc/docker/daemon.json</code>; in Docker Desktop, go to <strong>Settings → Docker Engine</strong>:</li>
</ol>

<div class="language-json highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span><span class="w">
  </span><span class="nl">"insecure-registries"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="s2">"192.168.1.10:5000"</span><span class="p">]</span><span class="w">
</span><span class="p">}</span><span class="w">
</span></code></pre></div></div>

<p>Then restart the daemon (<code class="language-plaintext highlighter-rouge">sudo systemctl restart docker</code>). Note that this registry has <strong>no authentication</strong>: anyone who can reach port 5000 can push and pull. Add <code class="language-plaintext highlighter-rouge">htpasswd</code> auth (see the registry docs) or, for a team, run <strong>Harbor</strong>, which adds users, projects, vulnerability scanning and replication on top.</p>

<h2 id="talking-to-the-daemon-directly">Talking to the daemon directly</h2>

<p>The <code class="language-plaintext highlighter-rouge">docker</code> CLI is a client for the daemon’s REST API, which listens on a Unix socket by default. You can call it yourself:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>curl <span class="nt">--unix-socket</span> /var/run/docker.sock http://localhost/containers/json
</code></pre></div></div>

<p>That returns the same data as <code class="language-plaintext highlighter-rouge">docker ps</code>, as JSON, which is useful in scripts and monitoring tools.</p>

<p>Old tutorials often expose this API over TCP with <code class="language-plaintext highlighter-rouge">-H tcp://0.0.0.0:2375</code>. <strong>Don’t.</strong> An unauthenticated Docker API on the network is full root access to the host for anyone who can reach it, and it’s one of the most scanned-for ports on the internet. To manage a remote host, use SSH instead, which needs no daemon changes at all (<a href="/portfolio-site/blog/2025/07/16/chapter-1-10-docker-machine/">Chapter 1.10</a>):</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker <span class="nt">-H</span> ssh://deploy@203.0.113.10 ps
</code></pre></div></div>

<h2 id="the-errors-youll-hit-first">The errors you’ll hit first</h2>

<table>
  <thead>
    <tr>
      <th>Error</th>
      <th>What it means</th>
      <th>Fix</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">port is already allocated</code></td>
      <td>Something on the host already uses that port.</td>
      <td><code class="language-plaintext highlighter-rouge">ss -tulpn \| grep 8080</code> to find it, or publish a different host port.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">Conflict. The container name "/api" is already in use</code></td>
      <td>A stopped container still has that name.</td>
      <td><code class="language-plaintext highlighter-rouge">docker rm api</code>, or <code class="language-plaintext highlighter-rouge">docker start api</code> if you wanted it back.</td>
    </tr>
    <tr>
      <td>Container exits immediately</td>
      <td>The main process finished or crashed.</td>
      <td><code class="language-plaintext highlighter-rouge">docker logs api</code>; <code class="language-plaintext highlighter-rouge">docker inspect -f</code> for the exit code.</td>
    </tr>
    <tr>
      <td>Exit code <code class="language-plaintext highlighter-rouge">137</code></td>
      <td>Killed with SIGKILL, often out of memory.</td>
      <td>Check <code class="language-plaintext highlighter-rouge">.State.OOMKilled</code>; raise <code class="language-plaintext highlighter-rouge">--memory</code> or fix the leak.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">permission denied ... docker.sock</code></td>
      <td>Your user can’t reach the daemon.</td>
      <td>Use <code class="language-plaintext highlighter-rouge">sudo</code>, or join the <code class="language-plaintext highlighter-rouge">docker</code> group (root-equivalent).</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">no space left on device</code></td>
      <td>Images, cache or volumes filled the disk.</td>
      <td><code class="language-plaintext highlighter-rouge">docker system df</code>, then the prune commands above.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">manifest unknown</code> / <code class="language-plaintext highlighter-rouge">not found</code> on pull</td>
      <td>The tag doesn’t exist, or you’re not logged in to that registry.</td>
      <td>Check the tag on the registry; <code class="language-plaintext highlighter-rouge">docker login</code>.</td>
    </tr>
  </tbody>
</table>

<p><a href="/portfolio-site/blog/2025/07/12/chapter-1-3-docker-nginx/">Chapter 1.3</a> puts these pieces to work on a real service: Nginx serving a site over HTTPS, with its configuration and certificates mounted from the host.</p>]]></content><author><name>Echo Yin</name></author><category term="devops" /><category term="Platform Engineering" /><category term="DevOps" /><category term="Chapter One" /><category term="Docker" /><summary type="html"><![CDATA[The day-to-day side of Docker: the container lifecycle, the docker run flags that matter in practice, how to inspect and debug a running container, keeping disk usage under control, running your own registry, and the errors you'll hit first.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://e-choness.github.io/portfolio-site/assets/images/blogs/docker-advanced.webp" /><media:content medium="image" url="https://e-choness.github.io/portfolio-site/assets/images/blogs/docker-advanced.webp" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Chapter 1.1 - Docker Basics: From “Works on My Machine” to Works Everywhere</title><link href="https://e-choness.github.io/portfolio-site/blog/2025/07/10/chapter-1-1-docker-basics/" rel="alternate" type="text/html" title="Chapter 1.1 - Docker Basics: From “Works on My Machine” to Works Everywhere" /><published>2025-07-10T00:00:00+00:00</published><updated>2025-07-10T00:00:00+00:00</updated><id>https://e-choness.github.io/portfolio-site/blog/2025/07/10/chapter-1-1-docker-basics</id><content type="html" xml:base="https://e-choness.github.io/portfolio-site/blog/2025/07/10/chapter-1-1-docker-basics/"><![CDATA[<p>Every team eventually ships something that runs perfectly on one laptop and fails everywhere else. A different Node version, a missing system library, an environment variable someone set by hand two years ago. The code was fine; the <strong>environment</strong> wasn’t part of what you shipped.</p>

<p>Docker’s answer is to ship the environment too. You describe everything your program needs in a file, build it into an <strong>image</strong>, and run that image as a <strong>container</strong> on any machine with Docker installed. The same image runs on your laptop, in CI and in production.</p>

<p>This chapter covers the core ideas and the commands you’ll use every day, then packages a small web service from an empty directory.</p>

<h2 id="containers-are-not-small-virtual-machines">Containers are not small virtual machines</h2>

<p>A virtual machine emulates a whole computer: virtual hardware, its own kernel, its own boot process. That’s strong isolation, but every VM carries a full operating system, takes seconds to minutes to start, and reserves memory whether it uses it or not.</p>

<p>A container is something much lighter: <strong>an ordinary process on the host</strong>, which the Linux kernel fences off from everything else.</p>

<ul>
  <li><strong>Namespaces</strong> give the process its own view of the system: its own process list (it believes it’s PID 1), its own network interfaces, its own hostname and its own filesystem root.</li>
  <li><strong>cgroups</strong> limit what it can consume: CPU, memory, I/O.</li>
  <li>The <strong>image</strong> supplies the filesystem it sees: an OS userland (Alpine, Debian…), your runtime, your code.</li>
</ul>

<pre><code class="language-mermaid">flowchart TB
  subgraph VM["Virtual machines"]
    direction TB
    va[App A] --- vga[Guest OS]
    vb[App B] --- vgb[Guest OS]
    vga --- hv[Hypervisor]
    vgb --- hv
    hv --- vh[Host OS + hardware]
  end
  subgraph CT["Containers"]
    direction TB
    ca[App A + libs] --- eng[Container runtime]
    cb[App B + libs] --- eng
    eng --- k[Shared host kernel&lt;br/&gt;namespaces + cgroups]
    k --- ch[Hardware]
  end
</code></pre>

<p>Because there’s no guest kernel to boot, a container starts in well under a second and uses only the memory its process actually uses. The trade-off is that all containers share the host’s kernel. That’s why Linux containers need a Linux kernel: on macOS and Windows, Docker Desktop runs a small Linux VM behind the scenes.</p>

<h2 id="installing-docker">Installing Docker</h2>

<ul>
  <li><strong>Linux</strong>: install <strong>Docker Engine</strong> from Docker’s own repository (<a href="https://docs.docker.com/engine/install/ubuntu/">Ubuntu</a>, <a href="https://docs.docker.com/engine/install/debian/">Debian</a>, <a href="https://docs.docker.com/engine/install/fedora/">Fedora</a>, <a href="https://docs.docker.com/engine/install/">others</a>). Distribution packages named <code class="language-plaintext highlighter-rouge">docker.io</code> often lag behind.</li>
  <li><strong>macOS and Windows</strong>: install <a href="https://docs.docker.com/desktop/">Docker Desktop</a>. It’s free for personal use, education and small businesses; larger companies need a paid subscription. Colima (macOS) and Rancher Desktop are free alternatives.</li>
</ul>

<p>Check that the client can talk to the daemon:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker version     <span class="c"># prints both Client and Server sections if all is well</span>
docker run hello-world
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">docker</code> is only a client: it sends requests to the <strong>Docker daemon</strong> (<code class="language-plaintext highlighter-rouge">dockerd</code>), which does the actual work. If <code class="language-plaintext highlighter-rouge">docker version</code> prints the client but errors on the server, the daemon isn’t running: <code class="language-plaintext highlighter-rouge">sudo systemctl start docker</code> on Linux, or start Docker Desktop.</p>

<p>On Linux you can skip typing <code class="language-plaintext highlighter-rouge">sudo</code> by adding yourself to the <code class="language-plaintext highlighter-rouge">docker</code> group (<code class="language-plaintext highlighter-rouge">sudo usermod -aG docker $USER</code>, then log out and back in). Be aware that this group is effectively root on the host, since anyone in it can start a container that mounts <code class="language-plaintext highlighter-rouge">/</code>. Only do it on machines you control.</p>

<h2 id="images-and-containers">Images and containers</h2>

<p>These two words carry the whole model:</p>

<ul>
  <li>An <strong>image</strong> is a read-only template: a filesystem plus metadata (which command to run, which port it listens on). It’s built in <strong>layers</strong>, one per build step, and layers are shared between images.</li>
  <li>A <strong>container</strong> is a running (or stopped) instance of an image, with a thin writable layer on top. You can start many containers from one image.</li>
</ul>

<p>The relationship between them, and the commands that move between them:</p>

<pre><code class="language-mermaid">flowchart TD
  df[Dockerfile] -- "docker build" --&gt; img[(Image)]
  img -- "docker run" --&gt; c1[Container]
  img -- "docker run" --&gt; c2[Container]
  img -- "docker push" --&gt; reg[(Registry&lt;br/&gt;Docker Hub, GHCR…)]
  reg -- "docker pull" --&gt; img
  c1 -- "docker stop / start" --&gt; c1
  c1 -- "docker rm" --&gt; gone([deleted])
</code></pre>

<p>Try it with an image someone else built:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker run <span class="nt">-it</span> <span class="nt">--rm</span> ubuntu bash
</code></pre></div></div>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">run</code></strong>: create a container from an image and start it, pulling the image first if it isn’t on your machine.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">-it</code></strong>: <code class="language-plaintext highlighter-rouge">-i</code> keeps standard input open and <code class="language-plaintext highlighter-rouge">-t</code> gives it a terminal, so you get an interactive shell.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">--rm</code></strong>: delete the container when it exits, so it doesn’t pile up.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">ubuntu</code></strong>: the image (<code class="language-plaintext highlighter-rouge">ubuntu:latest</code> from Docker Hub).</li>
  <li><strong><code class="language-plaintext highlighter-rouge">bash</code></strong>: the command to run inside it, instead of the image’s default.</li>
</ul>

<p>Inside, look around: <code class="language-plaintext highlighter-rouge">ps aux</code> shows only your shell (PID 1), <code class="language-plaintext highlighter-rouge">hostname</code> prints a random ID, and <code class="language-plaintext highlighter-rouge">cat /etc/os-release</code> says Ubuntu even if your host runs Fedora. Type <code class="language-plaintext highlighter-rouge">exit</code> and the container is gone. That’s the isolation from the diagram above.</p>

<h2 id="building-your-own-image">Building your own image</h2>

<p>Let’s package a small web service. Create an empty directory with three files.</p>

<p><strong><code class="language-plaintext highlighter-rouge">server.js</code></strong>: a web server that reports which container answered:</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">const</span> <span class="nx">express</span> <span class="o">=</span> <span class="nf">require</span><span class="p">(</span><span class="dl">"</span><span class="s2">express</span><span class="dl">"</span><span class="p">);</span>
<span class="kd">const</span> <span class="nx">os</span> <span class="o">=</span> <span class="nf">require</span><span class="p">(</span><span class="dl">"</span><span class="s2">os</span><span class="dl">"</span><span class="p">);</span>

<span class="kd">const</span> <span class="nx">app</span> <span class="o">=</span> <span class="nf">express</span><span class="p">();</span>
<span class="kd">const</span> <span class="nx">port</span> <span class="o">=</span> <span class="nx">process</span><span class="p">.</span><span class="nx">env</span><span class="p">.</span><span class="nx">PORT</span> <span class="o">||</span> <span class="mi">3000</span><span class="p">;</span>

<span class="nx">app</span><span class="p">.</span><span class="nf">get</span><span class="p">(</span><span class="dl">"</span><span class="s2">/</span><span class="dl">"</span><span class="p">,</span> <span class="p">(</span><span class="nx">req</span><span class="p">,</span> <span class="nx">res</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
  <span class="nx">res</span><span class="p">.</span><span class="nf">send</span><span class="p">(</span><span class="s2">`Hello from </span><span class="p">${</span><span class="nx">os</span><span class="p">.</span><span class="nf">hostname</span><span class="p">()}</span><span class="s2">\n`</span><span class="p">);</span>
<span class="p">});</span>

<span class="nx">app</span><span class="p">.</span><span class="nf">listen</span><span class="p">(</span><span class="nx">port</span><span class="p">,</span> <span class="p">()</span> <span class="o">=&gt;</span> <span class="nx">console</span><span class="p">.</span><span class="nf">log</span><span class="p">(</span><span class="s2">`listening on port </span><span class="p">${</span><span class="nx">port</span><span class="p">}</span><span class="s2">`</span><span class="p">));</span>
</code></pre></div></div>

<p><strong><code class="language-plaintext highlighter-rouge">package.json</code></strong>:</p>

<div class="language-json highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span><span class="w">
  </span><span class="nl">"name"</span><span class="p">:</span><span class="w"> </span><span class="s2">"hello-docker"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"version"</span><span class="p">:</span><span class="w"> </span><span class="s2">"1.0.0"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"main"</span><span class="p">:</span><span class="w"> </span><span class="s2">"server.js"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"dependencies"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
    </span><span class="nl">"express"</span><span class="p">:</span><span class="w"> </span><span class="s2">"^5.1.0"</span><span class="w">
  </span><span class="p">}</span><span class="w">
</span><span class="p">}</span><span class="w">
</span></code></pre></div></div>

<p><strong><code class="language-plaintext highlighter-rouge">Dockerfile</code></strong>: the recipe for the image:</p>

<div class="language-dockerfile highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">FROM</span><span class="s"> node:22-alpine</span>

<span class="k">WORKDIR</span><span class="s"> /app</span>

<span class="k">COPY</span><span class="s"> package*.json ./</span>
<span class="k">RUN </span>npm <span class="nb">install</span> <span class="nt">--omit</span><span class="o">=</span>dev

<span class="k">COPY</span><span class="s"> . .</span>

<span class="k">ENV</span><span class="s"> PORT=3000</span>
<span class="k">EXPOSE</span><span class="s"> 3000</span>

<span class="k">USER</span><span class="s"> node</span>
<span class="k">CMD</span><span class="s"> ["node", "server.js"]</span>
</code></pre></div></div>

<h3 id="the-dockerfile-line-by-line">The Dockerfile, line by line</h3>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">FROM node:22-alpine</code></strong>: start from the official Node.js 22 image built on Alpine Linux, a very small distribution. Every image starts from another image (or from the empty <code class="language-plaintext highlighter-rouge">scratch</code>).</li>
  <li><strong><code class="language-plaintext highlighter-rouge">WORKDIR /app</code></strong>: create <code class="language-plaintext highlighter-rouge">/app</code> and make it the current directory for every instruction that follows, and for the running container.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">COPY package*.json ./</code></strong>: copy <em>only</em> the dependency manifest first…</li>
  <li><strong><code class="language-plaintext highlighter-rouge">RUN npm install --omit=dev</code></strong>: …then install dependencies. <code class="language-plaintext highlighter-rouge">RUN</code> executes at <strong>build time</strong>, and its result is saved as a layer. <code class="language-plaintext highlighter-rouge">--omit=dev</code> skips development-only packages.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">COPY . .</code></strong>: now copy the rest of the source code.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">ENV PORT=3000</code></strong>: an environment variable baked into the image; <code class="language-plaintext highlighter-rouge">server.js</code> reads it.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">EXPOSE 3000</code></strong>: documents the port the app listens on. It doesn’t publish anything by itself.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">USER node</code></strong>: run as the unprivileged <code class="language-plaintext highlighter-rouge">node</code> user the base image provides, instead of root.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">CMD ["node", "server.js"]</code></strong>: the default command when a container starts. Unlike <code class="language-plaintext highlighter-rouge">RUN</code>, it executes at <strong>run time</strong>.</li>
</ul>

<p><strong>Why copy <code class="language-plaintext highlighter-rouge">package.json</code> separately?</strong> Docker caches each layer and reuses it until something it depends on changes. Because dependencies are installed before the source is copied, editing <code class="language-plaintext highlighter-rouge">server.js</code> only invalidates the last <code class="language-plaintext highlighter-rouge">COPY</code>; the slow <code class="language-plaintext highlighter-rouge">npm install</code> layer is reused and rebuilds take a second or two. Copy everything first and every one-line change reinstalls every dependency.</p>

<p><strong>Why <code class="language-plaintext highlighter-rouge">CMD ["node", "server.js"]</code> and not <code class="language-plaintext highlighter-rouge">CMD node server.js</code>?</strong> The JSON-array (“exec”) form runs <code class="language-plaintext highlighter-rouge">node</code> directly as the container’s main process. The plain-string form wraps it in <code class="language-plaintext highlighter-rouge">/bin/sh -c</code>, and the shell doesn’t forward signals, so <code class="language-plaintext highlighter-rouge">docker stop</code> can’t shut your app down gracefully and falls back to killing it after ten seconds.</p>

<p>Also add a <strong><code class="language-plaintext highlighter-rouge">.dockerignore</code></strong>, which works like <code class="language-plaintext highlighter-rouge">.gitignore</code> for the build:</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>node_modules
npm-debug.log
.git
</code></pre></div></div>

<p>Without it, <code class="language-plaintext highlighter-rouge">COPY . .</code> would copy your local <code class="language-plaintext highlighter-rouge">node_modules</code> (built for your OS, not Alpine) into the image over the ones <code class="language-plaintext highlighter-rouge">npm install</code> just built, along with your whole Git history.</p>

<h3 id="build-it">Build it</h3>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker build <span class="nt">-t</span> hello-docker:1.0 <span class="nb">.</span>
</code></pre></div></div>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">-t hello-docker:1.0</code></strong>: name (<code class="language-plaintext highlighter-rouge">hello-docker</code>) and tag (<code class="language-plaintext highlighter-rouge">1.0</code>) the image. Without a tag, Docker uses <code class="language-plaintext highlighter-rouge">latest</code>.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">.</code></strong>: the <strong>build context</strong>, the directory whose files the Dockerfile’s <code class="language-plaintext highlighter-rouge">COPY</code> can see (here, the current one).</li>
</ul>

<p><code class="language-plaintext highlighter-rouge">docker image ls</code> now lists it. Change a line in <code class="language-plaintext highlighter-rouge">server.js</code> and build again: watch the output report <code class="language-plaintext highlighter-rouge">CACHED</code> for every step up to the final <code class="language-plaintext highlighter-rouge">COPY</code>.</p>

<h2 id="running-it">Running it</h2>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker run <span class="nt">-d</span> <span class="nt">--name</span> web <span class="nt">-p</span> 8080:3000 hello-docker:1.0
curl http://localhost:8080
<span class="c"># Hello from 3f9c1b2a7d44</span>
</code></pre></div></div>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">-d</code></strong>: detached, so it runs in the background and prints the container ID.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">--name web</code></strong>: a name to use instead of that ID.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">-p 8080:3000</code></strong>: publish the port, <code class="language-plaintext highlighter-rouge">host:container</code>. Requests to port 8080 on your machine are forwarded to port 3000 inside the container. Without <code class="language-plaintext highlighter-rouge">-p</code> the service is only reachable from other containers.</li>
</ul>

<p>The hostname in the response is the container’s ID: the process really does have its own view of the system. Start a second one on another host port and you’ll get a different hostname:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker run <span class="nt">-d</span> <span class="nt">--name</span> web2 <span class="nt">-p</span> 8081:3000 hello-docker:1.0
curl http://localhost:8081
</code></pre></div></div>

<h2 id="looking-inside-and-cleaning-up">Looking inside and cleaning up</h2>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker ps                      <span class="c"># running containers (add -a to include stopped ones)</span>
docker logs <span class="nt">-f</span> web             <span class="c"># the app's stdout/stderr; -f follows like tail -f</span>
docker <span class="nb">exec</span> <span class="nt">-it</span> web sh         <span class="c"># open a shell in the running container</span>
docker stop web web2           <span class="c"># graceful: SIGTERM, then SIGKILL after 10s</span>
docker start web               <span class="c"># start a stopped container again, same state</span>
docker <span class="nb">rm</span> <span class="nt">-f</span> web web2          <span class="c"># remove (-f stops them first)</span>
</code></pre></div></div>

<p>A few things worth knowing:</p>

<ul>
  <li><strong>Stopped containers still exist</strong> and keep their writable layer until you <code class="language-plaintext highlighter-rouge">docker rm</code> them. <code class="language-plaintext highlighter-rouge">docker ps -a</code> shows them all; <code class="language-plaintext highlighter-rouge">--rm</code> on <code class="language-plaintext highlighter-rouge">docker run</code> removes the container automatically when it exits.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">docker exec</code></strong> runs an <em>additional</em> process in an already-running container. It’s how you debug. Alpine images have <code class="language-plaintext highlighter-rouge">sh</code>, not <code class="language-plaintext highlighter-rouge">bash</code>.</li>
  <li><strong>Anything written inside a container is lost when it’s removed.</strong> Data that must survive, such as databases and uploads, goes in <strong>volumes</strong>, which later chapters use heavily.</li>
  <li><code class="language-plaintext highlighter-rouge">docker system df</code> shows how much disk images, containers and volumes use; <code class="language-plaintext highlighter-rouge">docker system prune</code> removes stopped containers, unused networks and dangling images. Read the prompt before confirming.</li>
</ul>

<h2 id="sharing-it">Sharing it</h2>

<p>Images are shared through a <strong>registry</strong>. Docker Hub is the default; GitHub Container Registry, GitLab and every cloud provider run their own.</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker login                                         <span class="c"># Docker Hub; pass a hostname for others</span>
docker tag hello-docker:1.0 yourname/hello-docker:1.0
docker push yourname/hello-docker:1.0
</code></pre></div></div>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">docker tag</code></strong> adds a second name to the same image. Registry images are named <code class="language-plaintext highlighter-rouge">registry/namespace/repository:tag</code>; for Docker Hub the registry part is implied, so <code class="language-plaintext highlighter-rouge">yourname/hello-docker</code> is enough.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">docker push</code></strong> uploads only the layers the registry doesn’t already have. Push a new version and only your code layer goes up; the Node base layers are already there.</li>
</ul>

<p>Anyone can now run your service with a single <code class="language-plaintext highlighter-rouge">docker run yourname/hello-docker:1.0</code>, with no Node.js installed and no <code class="language-plaintext highlighter-rouge">npm install</code>, on any machine with Docker.</p>

<h2 id="what-to-remember">What to remember</h2>

<ul>
  <li>An <strong>image</strong> is the packaged environment; a <strong>container</strong> is a process running from it.</li>
  <li>Containers are isolated processes sharing the host kernel, not virtual machines.</li>
  <li><code class="language-plaintext highlighter-rouge">RUN</code> happens when you <strong>build</strong>, <code class="language-plaintext highlighter-rouge">CMD</code> when you <strong>run</strong>.</li>
  <li>Order Dockerfile steps from least to most frequently changing, so the cache does its job.</li>
  <li>Containers are disposable. Anything worth keeping lives in a volume, or in the image.</li>
</ul>

<p><a href="/portfolio-site/blog/2025/07/11/chapter-1-2-docker-advanced/">Chapter 1.2</a> goes deeper into day-to-day container management: the container lifecycle, inspecting and debugging running containers, and running your own private registry.</p>]]></content><author><name>Echo Yin</name></author><category term="devops" /><category term="Platform Engineering" /><category term="DevOps" /><category term="Chapter One" /><category term="Docker" /><summary type="html"><![CDATA[What a container actually is, how it differs from a virtual machine, and the handful of Docker commands you need to build, run, inspect and share one. We package a small Node.js service from scratch and go through the Dockerfile line by line.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://e-choness.github.io/portfolio-site/assets/images/blogs/docker-basics.webp" /><media:content medium="image" url="https://e-choness.github.io/portfolio-site/assets/images/blogs/docker-basics.webp" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Chapter 0.1 - Back to the Root: The Linux Command Line You’ll Actually Use</title><link href="https://e-choness.github.io/portfolio-site/blog/2025/07/09/chapter-0-1-linux-commands/" rel="alternate" type="text/html" title="Chapter 0.1 - Back to the Root: The Linux Command Line You’ll Actually Use" /><published>2025-07-09T00:00:00+00:00</published><updated>2025-07-09T00:00:00+00:00</updated><id>https://e-choness.github.io/portfolio-site/blog/2025/07/09/chapter-0-1-linux-commands</id><content type="html" xml:base="https://e-choness.github.io/portfolio-site/blog/2025/07/09/chapter-0-1-linux-commands/"><![CDATA[<p>Everything later in this series runs on Linux. A Docker container is a Linux process with some fences around it. A CI runner is a Linux machine executing your shell commands. When a Kubernetes pod misbehaves, the fix usually starts with <code class="language-plaintext highlighter-rouge">kubectl exec</code> into a shell. So before any of that, this chapter covers the command line itself.</p>

<p>I’ve organized it by <strong>the job you’re trying to do</strong> rather than alphabetically, because that’s how you actually look things up: “how do I find which process is holding port 8080?”, not “what does <code class="language-plaintext highlighter-rouge">ss</code> do?”. Each section shows the commands, then breaks down the flags that matter. There’s a cheat sheet at the end.</p>

<p>Everything here works in Bash on any mainstream distribution (Ubuntu, Debian, Fedora, Arch), in WSL on Windows, and mostly in macOS’s zsh (where GNU and BSD tools differ, I say so).</p>

<h2 id="the-shape-of-a-command">The shape of a command</h2>

<p>Almost every command follows the same pattern:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">ls</span> <span class="nt">-la</span> <span class="nt">--color</span><span class="o">=</span>auto /var/log
</code></pre></div></div>

<table>
  <thead>
    <tr>
      <th>Part</th>
      <th>Example</th>
      <th>Meaning</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Command</td>
      <td><code class="language-plaintext highlighter-rouge">ls</code></td>
      <td>The program to run</td>
    </tr>
    <tr>
      <td>Short flags</td>
      <td><code class="language-plaintext highlighter-rouge">-la</code></td>
      <td>Single-letter options; <code class="language-plaintext highlighter-rouge">-la</code> is <code class="language-plaintext highlighter-rouge">-l</code> and <code class="language-plaintext highlighter-rouge">-a</code> combined</td>
    </tr>
    <tr>
      <td>Long flag</td>
      <td><code class="language-plaintext highlighter-rouge">--color=auto</code></td>
      <td>A spelled-out option, often with a value</td>
    </tr>
    <tr>
      <td>Argument</td>
      <td><code class="language-plaintext highlighter-rouge">/var/log</code></td>
      <td>What the command acts on, usually a path</td>
    </tr>
  </tbody>
</table>

<p>Two habits save a lot of time:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">ls</span> <span class="nt">--help</span>        <span class="c"># quick usage summary, printed by the command itself</span>
man <span class="nb">ls</span>           <span class="c"># the full manual; press / to search, q to quit</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">--help</code> is the near-universal convention. Don’t rely on <code class="language-plaintext highlighter-rouge">-h</code>: for many tools (<code class="language-plaintext highlighter-rouge">ls</code>, <code class="language-plaintext highlighter-rouge">df</code>, <code class="language-plaintext highlighter-rouge">du</code>, <code class="language-plaintext highlighter-rouge">sort</code>) it means “human-readable sizes”, not help. If you want worked examples instead of reference text, the community <code class="language-plaintext highlighter-rouge">tldr</code> pages (<code class="language-plaintext highlighter-rouge">tldr tar</code>) are excellent.</p>

<h2 id="finding-your-way-around">Finding your way around</h2>

<h3 id="where-am-i-and-whats-here">Where am I, and what’s here?</h3>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">pwd</span>              <span class="c"># print working directory</span>
<span class="nb">ls</span>               <span class="c"># list the current directory</span>
<span class="nb">ls</span> <span class="nt">-lah</span>          <span class="c"># long format, include hidden files, human-readable sizes</span>
<span class="nb">ls</span> <span class="nt">-lt</span>           <span class="c"># newest first</span>
<span class="nb">ls</span> <span class="nt">-R</span> src/       <span class="c"># recurse into subdirectories</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">ls -l</code> is worth reading carefully, because it answers most “why can’t I…” questions:</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>-rw-r--r--  1 echo staff  4.2K Jul  9 10:14 notes.md
drwxr-xr-x  5 echo staff  160B Jul  9 09:02 src
</code></pre></div></div>

<ul>
  <li><strong>First character</strong>: the type. <code class="language-plaintext highlighter-rouge">-</code> is a regular file, <code class="language-plaintext highlighter-rouge">d</code> a directory, <code class="language-plaintext highlighter-rouge">l</code> a symbolic link.</li>
  <li><strong>Next nine characters</strong>: permissions for the owner, the group and everyone else (covered below).</li>
  <li><strong><code class="language-plaintext highlighter-rouge">echo staff</code></strong>: the owning user and group.</li>
  <li><strong>Size, date, name</strong>: what you’d expect. <code class="language-plaintext highlighter-rouge">-h</code> turns <code class="language-plaintext highlighter-rouge">4213</code> into <code class="language-plaintext highlighter-rouge">4.2K</code>.</li>
</ul>

<p>Files starting with a dot (<code class="language-plaintext highlighter-rouge">.bashrc</code>, <code class="language-plaintext highlighter-rouge">.git</code>) are hidden by convention; <code class="language-plaintext highlighter-rouge">-a</code> shows them.</p>

<h3 id="moving">Moving</h3>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">cd</span> /var/log      <span class="c"># absolute path: starts at the root</span>
<span class="nb">cd </span>projects/api  <span class="c"># relative path: starts where you are</span>
<span class="nb">cd</span> ..            <span class="c"># up one level</span>
<span class="nb">cd</span> -             <span class="c"># back to the previous directory</span>
<span class="nb">cd</span>               <span class="c"># home (same as cd ~)</span>
</code></pre></div></div>

<h3 id="where-things-live">Where things live</h3>

<p>The Linux filesystem is one tree starting at <code class="language-plaintext highlighter-rouge">/</code>. You’ll keep coming back to the same few branches:</p>

<pre><code class="language-mermaid">flowchart LR
  root["/"] --&gt; etc["/etc · system configuration"]
  root --&gt; var["/var · changing data"]
  var --&gt; log["/var/log · log files"]
  var --&gt; lib["/var/lib · service data (docker, mysql)"]
  root --&gt; home["/home/you · your files, ~"]
  root --&gt; usr["/usr/bin, /usr/local/bin · installed programs"]
  root --&gt; opt["/opt · self-contained third-party software"]
  root --&gt; tmp["/tmp · scratch, wiped on reboot"]
  root --&gt; proc["/proc, /sys · live kernel and process info"]
</code></pre>

<p>When a service misbehaves, its config is almost always under <code class="language-plaintext highlighter-rouge">/etc</code>, its logs under <code class="language-plaintext highlighter-rouge">/var/log</code> (or in the journal, below), and its data under <code class="language-plaintext highlighter-rouge">/var/lib</code>.</p>

<h2 id="working-with-files-and-directories">Working with files and directories</h2>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">touch </span>notes.md                 <span class="c"># create an empty file (or update its timestamp)</span>
<span class="nb">mkdir</span> <span class="nt">-p</span> projects/api/src      <span class="c"># create a directory and any missing parents</span>
<span class="nb">cp </span>config.yml config.yml.bak   <span class="c"># copy a file</span>
<span class="nb">cp</span> <span class="nt">-r</span> src/ backup/             <span class="c"># copy a directory recursively</span>
<span class="nb">mv </span>draft.md posts/final.md     <span class="c"># move and rename in one step</span>
<span class="nb">rm </span>old.log                     <span class="c"># delete a file</span>
<span class="nb">rm</span> <span class="nt">-r</span> build/                   <span class="c"># delete a directory and its contents</span>
<span class="nb">rm</span> <span class="nt">-i</span> <span class="k">*</span>.tmp                    <span class="c"># ask before each deletion</span>
<span class="nb">ln</span> <span class="nt">-s</span> /opt/tool/bin/tool ~/bin/tool   <span class="c"># symbolic link (a shortcut)</span>
</code></pre></div></div>

<p>A few details that bite people:</p>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">rm</code> has no recycle bin.</strong> Deleted is deleted. <code class="language-plaintext highlighter-rouge">rm -rf</code> (recursive, force, no prompts) combined with a variable that turned out empty has wiped real systems; if you script it, guard the variable: <code class="language-plaintext highlighter-rouge">rm -rf -- "${BUILD_DIR:?}"/*</code> refuses to run when <code class="language-plaintext highlighter-rouge">BUILD_DIR</code> is unset.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">cp</code> and <code class="language-plaintext highlighter-rouge">mv</code> overwrite silently.</strong> Add <code class="language-plaintext highlighter-rouge">-i</code> to be asked first, or <code class="language-plaintext highlighter-rouge">-n</code> to never overwrite.</li>
  <li><strong>Wildcards are expanded by the shell, not the command.</strong> <code class="language-plaintext highlighter-rouge">*.log</code> matches every <code class="language-plaintext highlighter-rouge">.log</code> file in the current directory; <code class="language-plaintext highlighter-rouge">?</code> matches one character; <code class="language-plaintext highlighter-rouge">{a,b}</code> expands to both (<code class="language-plaintext highlighter-rouge">cp app.{yml,yml.bak}</code> copies <code class="language-plaintext highlighter-rouge">app.yml</code> to <code class="language-plaintext highlighter-rouge">app.yml.bak</code>).</li>
</ul>

<h2 id="reading-files">Reading files</h2>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">cat </span>short.txt          <span class="c"># print a whole (short) file</span>
less long.log          <span class="c"># page through a file: / to search, n for next, q to quit</span>
<span class="nb">head</span> <span class="nt">-n</span> 20 data.csv    <span class="c"># first 20 lines</span>
<span class="nb">tail</span> <span class="nt">-n</span> 50 app.log     <span class="c"># last 50 lines</span>
<span class="nb">tail</span> <span class="nt">-f</span> app.log        <span class="c"># keep printing new lines as they're written</span>
<span class="nb">wc</span> <span class="nt">-l</span> data.csv         <span class="c"># count lines (-w words, -c bytes)</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">tail -f</code> is the single most useful debugging command on a server: start it in one terminal, reproduce the problem in another, and watch the log as it happens. <code class="language-plaintext highlighter-rouge">less +F</code> does the same inside <code class="language-plaintext highlighter-rouge">less</code>, and Ctrl+C drops you back into normal scrolling.</p>

<h2 id="finding-things">Finding things</h2>

<h3 id="files-by-name-size-or-age-find">Files, by name, size or age: <code class="language-plaintext highlighter-rouge">find</code></h3>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>find <span class="nb">.</span> <span class="nt">-name</span> <span class="s2">"*.yml"</span>                          <span class="c"># by name, from the current directory down</span>
find /var/log <span class="nt">-name</span> <span class="s2">"*.gz"</span> <span class="nt">-mtime</span> +30         <span class="c"># .gz files older than 30 days</span>
find <span class="nb">.</span> <span class="nt">-type</span> f <span class="nt">-size</span> +100M                    <span class="c"># regular files larger than 100 MB</span>
find <span class="nb">.</span> <span class="nt">-name</span> <span class="s2">"node_modules"</span> <span class="nt">-type</span> d <span class="nt">-prune</span>    <span class="c"># directories only, don't descend into them</span>
find /tmp <span class="nt">-type</span> f <span class="nt">-mtime</span> +7 <span class="nt">-delete</span>           <span class="c"># delete week-old files in /tmp</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">find</code> reads as a sentence: <strong>where to look</strong>, then <strong>tests</strong> that must all match, then an optional <strong>action</strong>.</p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">-name "*.yml"</code>: quote the pattern, so the shell passes it to <code class="language-plaintext highlighter-rouge">find</code> instead of expanding it.</li>
  <li><code class="language-plaintext highlighter-rouge">-type f</code> / <code class="language-plaintext highlighter-rouge">-type d</code>: files or directories.</li>
  <li><code class="language-plaintext highlighter-rouge">-mtime +30</code>: modified more than 30 days ago (<code class="language-plaintext highlighter-rouge">-30</code> means less than).</li>
  <li><code class="language-plaintext highlighter-rouge">-size +100M</code>: larger than 100 MB (<code class="language-plaintext highlighter-rouge">k</code>, <code class="language-plaintext highlighter-rouge">M</code>, <code class="language-plaintext highlighter-rouge">G</code> suffixes).</li>
  <li><code class="language-plaintext highlighter-rouge">-delete</code>: acts on every match, so run the command without it first and check the list.</li>
</ul>

<h3 id="text-inside-files-grep">Text inside files: <code class="language-plaintext highlighter-rouge">grep</code></h3>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">grep</span> <span class="s2">"timeout"</span> app.log               <span class="c"># lines containing "timeout"</span>
<span class="nb">grep</span> <span class="nt">-i</span> <span class="s2">"error"</span> app.log              <span class="c"># case-insensitive</span>
<span class="nb">grep</span> <span class="nt">-n</span> <span class="s2">"TODO"</span> <span class="k">*</span>.py                  <span class="c"># show line numbers</span>
<span class="nb">grep</span> <span class="nt">-r</span> <span class="s2">"DATABASE_URL"</span> <span class="nb">.</span>             <span class="c"># search a whole directory tree</span>
<span class="nb">grep</span> <span class="nt">-v</span> <span class="s2">"healthcheck"</span> access.log     <span class="c"># lines that do NOT match</span>
<span class="nb">grep</span> <span class="nt">-E</span> <span class="s2">"5[0-9]{2} "</span> access.log      <span class="c"># extended regex: any 5xx status</span>
<span class="nb">grep</span> <span class="nt">-c</span> <span class="s2">"WARN"</span> app.log               <span class="c"># just count matching lines</span>
</code></pre></div></div>

<p>For big codebases, <code class="language-plaintext highlighter-rouge">ripgrep</code> (<code class="language-plaintext highlighter-rouge">rg</code>) is a faster <code class="language-plaintext highlighter-rouge">grep -r</code> that respects <code class="language-plaintext highlighter-rouge">.gitignore</code>, and it’s worth installing.</p>

<h3 id="programs-which-and-type">Programs: <code class="language-plaintext highlighter-rouge">which</code> and <code class="language-plaintext highlighter-rouge">type</code></h3>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>which python3        <span class="c"># the file that runs when you type python3</span>
<span class="nb">type </span>ll              <span class="c"># also reveals aliases and shell built-ins</span>
</code></pre></div></div>

<p>When “it works in my terminal but not in cron”, <code class="language-plaintext highlighter-rouge">which</code> usually shows a different binary or a missing <code class="language-plaintext highlighter-rouge">PATH</code> entry.</p>

<h2 id="pipes-and-redirection-making-small-tools-work-together">Pipes and redirection: making small tools work together</h2>

<p>This is where the command line stops being a list of commands and becomes a language. Every process starts with three streams: <strong>standard input</strong> (0), <strong>standard output</strong> (1) and <strong>standard error</strong> (2). By default all three are your terminal; the operators below re-point them.</p>

<pre><code class="language-mermaid">flowchart TD
  kb([keyboard]) -- "stdin (0)" --&gt; cmd[command]
  in[(file)] -- "&lt; file" --&gt; cmd
  cmd -- "stdout (1)&lt;br/&gt;stderr (2)" --&gt; term([terminal])
  cmd -- "&gt; file overwrite&lt;br/&gt;&gt;&gt; file append" --&gt; out[(file)]
  cmd -- "2&gt; errors.log" --&gt; err[(file)]
  cmd -- "| stdout → stdin" --&gt; next[next command]
  next -- "tee copy.txt" --&gt; both([terminal + file])
</code></pre>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">ls</span> <span class="nt">-l</span> /etc <span class="o">&gt;</span> listing.txt          <span class="c"># stdout to a file (overwrites)</span>
<span class="nb">echo</span> <span class="s2">"done"</span> <span class="o">&gt;&gt;</span> build.log          <span class="c"># append instead</span>
<span class="nb">sort</span> &lt; names.txt                  <span class="c"># a file as stdin</span>
make 2&gt; errors.log                <span class="c"># only errors to the file</span>
make <span class="o">&gt;</span> build.log 2&gt;&amp;1             <span class="c"># both streams to the same file</span>
<span class="nb">ls</span> <span class="nt">-l</span> /etc | less                 <span class="c"># pipe: output of one becomes input of the next</span>
./deploy.sh | <span class="nb">tee </span>deploy.log      <span class="c"># see the output AND keep a copy</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">2&gt;&amp;1</code> reads “send stream 2 wherever stream 1 is going”. Order matters: <code class="language-plaintext highlighter-rouge">&gt; build.log 2&gt;&amp;1</code> captures both, while <code class="language-plaintext highlighter-rouge">2&gt;&amp;1 &gt; build.log</code> sends errors to the terminal, because stream 2 copied stream 1 before stream 1 was redirected.</p>

<h3 id="a-worked-pipeline">A worked pipeline</h3>

<p>Here’s the kind of one-liner that answers a real question: <em>which client IPs are hitting this server hardest?</em></p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">awk</span> <span class="s1">'{print $1}'</span> /var/log/nginx/access.log | <span class="nb">sort</span> | <span class="nb">uniq</span> <span class="nt">-c</span> | <span class="nb">sort</span> <span class="nt">-rn</span> | <span class="nb">head</span> <span class="nt">-n</span> 10
</code></pre></div></div>

<p>Read it left to right. Each stage does one small thing:</p>

<ol>
  <li><strong><code class="language-plaintext highlighter-rouge">awk '{print $1}' access.log</code></strong>: print the first whitespace-separated field of every line, which in the default Nginx log format is the client IP.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">sort</code></strong>: put identical IPs next to each other (<code class="language-plaintext highlighter-rouge">uniq</code> only collapses <em>adjacent</em> duplicates).</li>
  <li><strong><code class="language-plaintext highlighter-rouge">uniq -c</code></strong>: collapse each run into one line, prefixed with its count.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">sort -rn</code></strong>: sort by that count, numerically (<code class="language-plaintext highlighter-rouge">-n</code>), largest first (<code class="language-plaintext highlighter-rouge">-r</code>).</li>
  <li><strong><code class="language-plaintext highlighter-rouge">head -n 10</code></strong>: keep the top ten.</li>
</ol>

<p>No script, no temporary files, and every stage can be tested on its own by cutting the pipeline short.</p>

<h3 id="the-text-processing-toolkit">The text-processing toolkit</h3>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">cut</span> <span class="nt">-d</span><span class="s1">','</span> <span class="nt">-f2</span> data.csv            <span class="c"># 2nd comma-separated column</span>
<span class="nb">sort</span> <span class="nt">-t</span><span class="s1">','</span> <span class="nt">-k3</span> <span class="nt">-n</span> data.csv        <span class="c"># sort by 3rd column, numerically</span>
<span class="nb">sort</span> <span class="nt">-u</span> names.txt                 <span class="c"># sort and drop duplicates</span>
<span class="nb">tr</span> <span class="s1">'a-z'</span> <span class="s1">'A-Z'</span> &lt; file.txt         <span class="c"># translate characters (here: uppercase)</span>
<span class="nb">sed</span> <span class="s1">'s/http:/https:/g'</span> links.txt  <span class="c"># replace text in every line (printed, file untouched)</span>
<span class="nb">sed</span> <span class="nt">-i</span> <span class="s1">'s/DEBUG=true/DEBUG=false/'</span> .env   <span class="c"># edit the file in place (GNU sed; macOS needs -i '')</span>
<span class="nb">awk</span> <span class="nt">-F</span><span class="s1">','</span> <span class="s1">'$3 &gt; 100 {print $1, $3}'</span> sales.csv   <span class="c"># rows where column 3 &gt; 100</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">xargs</code> connects commands that print filenames to commands that take filenames:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>find <span class="nb">.</span> <span class="nt">-name</span> <span class="s2">"*.log"</span> <span class="nt">-mtime</span> +30 <span class="nt">-print0</span> | xargs <span class="nt">-0</span> <span class="nb">gzip</span>
</code></pre></div></div>

<ul>
  <li><code class="language-plaintext highlighter-rouge">-print0</code> / <code class="language-plaintext highlighter-rouge">-0</code>: separate names with a null byte instead of newlines, so filenames containing spaces don’t split into two arguments.</li>
  <li><code class="language-plaintext highlighter-rouge">gzip</code> receives the whole batch of files as arguments and compresses each one.</li>
</ul>

<h2 id="permissions-and-ownership">Permissions and ownership</h2>

<p>Every file has an owner, a group, and three sets of permissions:</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>-rwxr-x---  1 deploy www-data  1.2K  deploy.sh
 └┬┘└┬┘└┬┘
  │  │  └── others: ---  no access
  │  └───── group (www-data): r-x  read and execute
  └──────── owner (deploy):   rwx  read, write, execute
</code></pre></div></div>

<p>For a directory, <code class="language-plaintext highlighter-rouge">r</code> means list its contents, <code class="language-plaintext highlighter-rouge">w</code> means create or delete files in it, and <code class="language-plaintext highlighter-rouge">x</code> means enter it (<code class="language-plaintext highlighter-rouge">cd</code>) and reach files inside.</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">chmod</span> +x deploy.sh           <span class="c"># make it executable</span>
<span class="nb">chmod </span>u+x,go-w deploy.sh     <span class="c"># symbolic: add x for the user; remove w from group and others</span>
<span class="nb">chmod </span>640 secrets.env        <span class="c"># numeric: owner rw-, group r--, others ---</span>
<span class="nb">chown </span>deploy:www-data site/  <span class="c"># change owner and group</span>
<span class="nb">chown</span> <span class="nt">-R</span> deploy site/        <span class="c"># recursively</span>
<span class="nb">sudo </span>systemctl restart nginx <span class="c"># run one command as root</span>
</code></pre></div></div>

<p>The numeric form adds up per digit: <strong>read = 4, write = 2, execute = 1</strong>.</p>

<table>
  <thead>
    <tr>
      <th>Number</th>
      <th>Permissions</th>
      <th>Typical use</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">755</code></td>
      <td><code class="language-plaintext highlighter-rouge">rwxr-xr-x</code></td>
      <td>programs, directories others may enter</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">644</code></td>
      <td><code class="language-plaintext highlighter-rouge">rw-r--r--</code></td>
      <td>ordinary files</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">600</code></td>
      <td><code class="language-plaintext highlighter-rouge">rw-------</code></td>
      <td>private keys, <code class="language-plaintext highlighter-rouge">.env</code> files</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">700</code></td>
      <td><code class="language-plaintext highlighter-rouge">rwx------</code></td>
      <td><code class="language-plaintext highlighter-rouge">~/.ssh</code>, private scripts</td>
    </tr>
  </tbody>
</table>

<p>If <code class="language-plaintext highlighter-rouge">ssh</code> refuses a key with “unprotected private key file”, this is why: it wants <code class="language-plaintext highlighter-rouge">600</code> on the key and <code class="language-plaintext highlighter-rouge">700</code> on <code class="language-plaintext highlighter-rouge">~/.ssh</code>.</p>

<p><strong><code class="language-plaintext highlighter-rouge">sudo</code></strong> runs a single command with root privileges and logs it. Use it per command rather than living in a root shell; the friction is the point.</p>

<h2 id="processes">Processes</h2>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>ps aux                       <span class="c"># every process, with user, CPU and memory</span>
ps aux | <span class="nb">grep </span>node           <span class="c"># find a specific one</span>
pgrep <span class="nt">-a</span> node                <span class="c"># the same, without matching grep itself</span>
top                          <span class="c"># live view (htop is friendlier if installed)</span>
<span class="nb">kill </span>4312                    <span class="c"># ask process 4312 to stop (SIGTERM)</span>
<span class="nb">kill</span> <span class="nt">-9</span> 4312                 <span class="c"># force it (SIGKILL), only when TERM didn't work</span>
pkill <span class="nt">-f</span> <span class="s2">"python worker.py"</span>  <span class="c"># signal by command line instead of PID</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">kill</code> sends a <strong>signal</strong>. <code class="language-plaintext highlighter-rouge">SIGTERM</code> (the default) politely asks the process to shut down, so it can finish writes and close connections. <code class="language-plaintext highlighter-rouge">SIGKILL</code> (<code class="language-plaintext highlighter-rouge">-9</code>) removes it immediately with no cleanup, which can leave lock files or half-written data behind. Always try TERM first. The same distinction comes back as <code class="language-plaintext highlighter-rouge">docker stop</code> versus <code class="language-plaintext highlighter-rouge">docker kill</code>.</p>

<h3 id="running-things-in-the-background">Running things in the background</h3>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>./long-task.sh &amp;             <span class="c"># start in the background</span>
<span class="nb">jobs</span>                         <span class="c"># list background jobs of this shell</span>
<span class="nb">fg</span> %1                        <span class="c"># bring job 1 back to the foreground</span>
<span class="c"># Ctrl+Z pauses the foreground job; bg resumes it in the background</span>
<span class="nb">nohup</span> ./long-task.sh <span class="o">&gt;</span> task.log 2&gt;&amp;1 &amp;   <span class="c"># keep running after you log out</span>
</code></pre></div></div>

<p>For anything that should survive reboots, don’t use <code class="language-plaintext highlighter-rouge">nohup</code>: make it a service.</p>

<h2 id="services-and-logs-systemd">Services and logs (systemd)</h2>

<p>Most distributions manage long-running services with systemd:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>systemctl status nginx            <span class="c"># running? since when? last log lines</span>
<span class="nb">sudo </span>systemctl restart nginx      <span class="c"># stop + start</span>
<span class="nb">sudo </span>systemctl reload nginx       <span class="c"># re-read config without dropping connections (if supported)</span>
<span class="nb">sudo </span>systemctl <span class="nb">enable</span> <span class="nt">--now</span> docker  <span class="c"># start now AND on every boot</span>
journalctl <span class="nt">-u</span> nginx <span class="nt">--since</span> <span class="s2">"1 hour ago"</span>   <span class="c"># a service's logs</span>
journalctl <span class="nt">-u</span> nginx <span class="nt">-f</span>            <span class="c"># follow, like tail -f</span>
journalctl <span class="nt">-p</span> err <span class="nt">-b</span>              <span class="c"># only errors, since the last boot</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">systemctl status</code> is always my first command when something is down: it shows whether the service is running, its exit code if not, and the last few log lines, which usually name the problem.</p>

<h2 id="disks-and-memory">Disks and memory</h2>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">df</span> <span class="nt">-h</span>                    <span class="c"># free space per mounted filesystem</span>
<span class="nb">du</span> <span class="nt">-sh</span> <span class="k">*</span>                 <span class="c"># size of each item in the current directory</span>
<span class="nb">du</span> <span class="nt">-sh</span> /var/lib/docker   <span class="c"># how much Docker is using</span>
free <span class="nt">-h</span>                  <span class="c"># memory and swap</span>
lsblk                    <span class="c"># disks and partitions as a tree</span>
</code></pre></div></div>

<p>When a disk fills up, <code class="language-plaintext highlighter-rouge">df -h</code> tells you <em>which</em> filesystem; then <code class="language-plaintext highlighter-rouge">du -sh /* 2&gt;/dev/null | sort -h</code> walks down the tree to find the culprit. (Sending errors to <code class="language-plaintext highlighter-rouge">/dev/null</code> hides the “permission denied” noise.)</p>

<h2 id="networking">Networking</h2>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>ip a                          <span class="c"># interfaces and IP addresses</span>
ip r                          <span class="c"># routing table (the "default via" line is your gateway)</span>
ping <span class="nt">-c</span> 4 example.com         <span class="c"># is it reachable? (-c: stop after 4)</span>
curl <span class="nt">-I</span> https://example.com   <span class="c"># just the response headers</span>
curl <span class="nt">-fsSL</span> https://example.com/install.sh <span class="nt">-o</span> install.sh   <span class="c"># download quietly, fail on HTTP errors</span>
dig example.com +short        <span class="c"># DNS lookup</span>
ss <span class="nt">-tulpn</span>                     <span class="c"># which ports are listening, and which process owns each</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">ss -tulpn</code> answers “what’s already on port 8080?”: <strong>t</strong>cp, <strong>u</strong>dp, <strong>l</strong>istening sockets, <strong>p</strong>rocess names (needs <code class="language-plaintext highlighter-rouge">sudo</code> for other users’ processes), <strong>n</strong>umeric ports.</p>

<h3 id="remote-machines">Remote machines</h3>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>ssh-keygen <span class="nt">-t</span> ed25519 <span class="nt">-C</span> <span class="s2">"echo@laptop"</span>      <span class="c"># create a key pair once</span>
ssh-copy-id deploy@203.0.113.10             <span class="c"># install the public key on a server</span>
ssh deploy@203.0.113.10                     <span class="c"># log in</span>
scp app.tar.gz deploy@203.0.113.10:/tmp/    <span class="c"># copy a file up</span>
rsync <span class="nt">-avz</span> <span class="nt">--delete</span> site/ deploy@203.0.113.10:/var/www/site/   <span class="c"># sync a directory</span>
</code></pre></div></div>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">ed25519</code></strong> keys are short, fast and the modern default; only fall back to <code class="language-plaintext highlighter-rouge">-t rsa -b 4096</code> for very old servers.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">rsync</code></strong> copies only what changed. <code class="language-plaintext highlighter-rouge">-a</code> preserves permissions and timestamps, <code class="language-plaintext highlighter-rouge">-v</code> lists files, <code class="language-plaintext highlighter-rouge">-z</code> compresses in transit, <code class="language-plaintext highlighter-rouge">--delete</code> removes files at the destination that no longer exist locally. The trailing slash on <code class="language-plaintext highlighter-rouge">site/</code> means “the contents of site”, not the directory itself.</li>
</ul>

<h2 id="archives">Archives</h2>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">tar</span> <span class="nt">-czf</span> backup.tar.gz project/      <span class="c"># create a gzip-compressed archive</span>
<span class="nb">tar</span> <span class="nt">-tzf</span> backup.tar.gz               <span class="c"># list its contents without extracting</span>
<span class="nb">tar</span> <span class="nt">-xzf</span> backup.tar.gz <span class="nt">-C</span> /restore   <span class="c"># extract into /restore</span>
zip <span class="nt">-r</span> site.zip site/                <span class="c"># zip, for people on Windows</span>
unzip site.zip <span class="nt">-d</span> site/
</code></pre></div></div>

<p>The <code class="language-plaintext highlighter-rouge">tar</code> letters stand for <strong>c</strong>reate / e<strong>x</strong>tract / lis<strong>t</strong>, <strong>z</strong> for gzip, <strong>f</strong> for “the archive file is the next argument”. So <code class="language-plaintext highlighter-rouge">-czf</code> is “create, gzip, to this file”. Use <code class="language-plaintext highlighter-rouge">-J</code> instead of <code class="language-plaintext highlighter-rouge">-z</code> for <code class="language-plaintext highlighter-rouge">.tar.xz</code>.</p>

<h2 id="installing-software">Installing software</h2>

<table>
  <thead>
    <tr>
      <th>Distribution</th>
      <th>Install</th>
      <th>Update everything</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Debian, Ubuntu</td>
      <td><code class="language-plaintext highlighter-rouge">sudo apt install nginx</code></td>
      <td><code class="language-plaintext highlighter-rouge">sudo apt update &amp;&amp; sudo apt upgrade</code></td>
    </tr>
    <tr>
      <td>Fedora, RHEL, Rocky</td>
      <td><code class="language-plaintext highlighter-rouge">sudo dnf install nginx</code></td>
      <td><code class="language-plaintext highlighter-rouge">sudo dnf upgrade</code></td>
    </tr>
    <tr>
      <td>Arch</td>
      <td><code class="language-plaintext highlighter-rouge">sudo pacman -S nginx</code></td>
      <td><code class="language-plaintext highlighter-rouge">sudo pacman -Syu</code></td>
    </tr>
    <tr>
      <td>macOS</td>
      <td><code class="language-plaintext highlighter-rouge">brew install nginx</code></td>
      <td><code class="language-plaintext highlighter-rouge">brew upgrade</code></td>
    </tr>
  </tbody>
</table>

<p>On Debian-based systems, <code class="language-plaintext highlighter-rouge">apt update</code> refreshes the package list and <code class="language-plaintext highlighter-rouge">apt upgrade</code> installs the newer versions; you need both.</p>

<h2 id="making-the-shell-work-for-you">Making the shell work for you</h2>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">history</span> | <span class="nb">grep </span>docker    <span class="c"># find a command you ran last week</span>
<span class="o">!!</span>                       <span class="c"># repeat the last command (sudo !! when you forgot sudo)</span>
<span class="nb">alias </span><span class="nv">ll</span><span class="o">=</span><span class="s1">'ls -lah'</span>       <span class="c"># a shortcut; put it in ~/.bashrc to keep it</span>
<span class="nb">export </span><span class="nv">EDITOR</span><span class="o">=</span>vim        <span class="c"># set an environment variable for this shell and its children</span>
<span class="nb">echo</span> <span class="nv">$PATH</span>               <span class="c"># where the shell looks for programs</span>
<span class="nb">source</span> ~/.bashrc         <span class="c"># reload your config without opening a new terminal</span>
</code></pre></div></div>

<p>And the keystrokes that pay for themselves within a day:</p>

<ul>
  <li><strong>Tab</strong>: complete commands, paths and (with completion installed) flags.</li>
  <li><strong>Ctrl+R</strong>: search your history as you type; press it again for older matches.</li>
  <li><strong>Ctrl+A / Ctrl+E</strong>: jump to the start / end of the line.</li>
  <li><strong>Ctrl+C</strong>: stop the running command. <strong>Ctrl+D</strong>: end input, or log out of an empty shell.</li>
</ul>

<h2 id="a-few-rules-i-follow">A few rules I follow</h2>

<ol>
  <li><strong>Look before you delete.</strong> Run a <code class="language-plaintext highlighter-rouge">find</code> or a glob with <code class="language-plaintext highlighter-rouge">ls</code> first, then add <code class="language-plaintext highlighter-rouge">-delete</code> or swap in <code class="language-plaintext highlighter-rouge">rm</code>.</li>
  <li><strong>Quote your variables.</strong> <code class="language-plaintext highlighter-rouge">"$file"</code>, not <code class="language-plaintext highlighter-rouge">$file</code>, or filenames with spaces will split.</li>
  <li><strong>Prefer pipes to temporary files.</strong> Each stage can be tested on its own.</li>
  <li><strong>Don’t live as root.</strong> Use <code class="language-plaintext highlighter-rouge">sudo</code> per command.</li>
  <li><strong>Write down anything you had to look up twice</strong> as an alias or a small script.</li>
  <li><strong>Practice somewhere disposable.</strong> A VM, a cloud instance you can delete, or <code class="language-plaintext highlighter-rouge">docker run -it --rm ubuntu bash</code>, which is exactly where the next chapter starts.</li>
</ol>

<h2 id="cheat-sheet">Cheat sheet</h2>

<table>
  <thead>
    <tr>
      <th>Task</th>
      <th>Command</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Where am I / what’s here</td>
      <td><code class="language-plaintext highlighter-rouge">pwd</code>, <code class="language-plaintext highlighter-rouge">ls -lah</code></td>
    </tr>
    <tr>
      <td>Move around</td>
      <td><code class="language-plaintext highlighter-rouge">cd dir</code>, <code class="language-plaintext highlighter-rouge">cd ..</code>, <code class="language-plaintext highlighter-rouge">cd -</code></td>
    </tr>
    <tr>
      <td>Create</td>
      <td><code class="language-plaintext highlighter-rouge">touch file</code>, <code class="language-plaintext highlighter-rouge">mkdir -p a/b/c</code></td>
    </tr>
    <tr>
      <td>Copy / move / delete</td>
      <td><code class="language-plaintext highlighter-rouge">cp -r</code>, <code class="language-plaintext highlighter-rouge">mv</code>, <code class="language-plaintext highlighter-rouge">rm -r</code> (no undo)</td>
    </tr>
    <tr>
      <td>Read</td>
      <td><code class="language-plaintext highlighter-rouge">cat</code>, <code class="language-plaintext highlighter-rouge">less</code>, <code class="language-plaintext highlighter-rouge">head -n</code>, <code class="language-plaintext highlighter-rouge">tail -f</code></td>
    </tr>
    <tr>
      <td>Find files</td>
      <td><code class="language-plaintext highlighter-rouge">find . -name "*.log" -mtime +7</code></td>
    </tr>
    <tr>
      <td>Find text</td>
      <td><code class="language-plaintext highlighter-rouge">grep -rn "pattern" .</code></td>
    </tr>
    <tr>
      <td>Count</td>
      <td><code class="language-plaintext highlighter-rouge">wc -l</code></td>
    </tr>
    <tr>
      <td>Sort / dedupe / count</td>
      <td><code class="language-plaintext highlighter-rouge">sort</code>, <code class="language-plaintext highlighter-rouge">uniq -c</code>, <code class="language-plaintext highlighter-rouge">sort -rn</code></td>
    </tr>
    <tr>
      <td>Columns and fields</td>
      <td><code class="language-plaintext highlighter-rouge">cut -d, -f2</code>, <code class="language-plaintext highlighter-rouge">awk '{print $1}'</code></td>
    </tr>
    <tr>
      <td>Replace text</td>
      <td><code class="language-plaintext highlighter-rouge">sed 's/old/new/g'</code></td>
    </tr>
    <tr>
      <td>Redirect</td>
      <td><code class="language-plaintext highlighter-rouge">&gt;</code>, <code class="language-plaintext highlighter-rouge">&gt;&gt;</code>, <code class="language-plaintext highlighter-rouge">2&gt;</code>, <code class="language-plaintext highlighter-rouge">2&gt;&amp;1</code>, <code class="language-plaintext highlighter-rouge">tee</code></td>
    </tr>
    <tr>
      <td>Pipe</td>
      <td><code class="language-plaintext highlighter-rouge">cmd1 \| cmd2</code></td>
    </tr>
    <tr>
      <td>Permissions</td>
      <td><code class="language-plaintext highlighter-rouge">chmod 644</code>, <code class="language-plaintext highlighter-rouge">chmod +x</code>, <code class="language-plaintext highlighter-rouge">chown user:group</code></td>
    </tr>
    <tr>
      <td>Processes</td>
      <td><code class="language-plaintext highlighter-rouge">ps aux</code>, <code class="language-plaintext highlighter-rouge">pgrep -a</code>, <code class="language-plaintext highlighter-rouge">top</code>, <code class="language-plaintext highlighter-rouge">kill</code> (TERM), <code class="language-plaintext highlighter-rouge">kill -9</code></td>
    </tr>
    <tr>
      <td>Services</td>
      <td><code class="language-plaintext highlighter-rouge">systemctl status/restart/enable</code>, <code class="language-plaintext highlighter-rouge">journalctl -u name -f</code></td>
    </tr>
    <tr>
      <td>Disk / memory</td>
      <td><code class="language-plaintext highlighter-rouge">df -h</code>, <code class="language-plaintext highlighter-rouge">du -sh *</code>, <code class="language-plaintext highlighter-rouge">free -h</code></td>
    </tr>
    <tr>
      <td>Network</td>
      <td><code class="language-plaintext highlighter-rouge">ip a</code>, <code class="language-plaintext highlighter-rouge">ss -tulpn</code>, <code class="language-plaintext highlighter-rouge">curl -I</code>, <code class="language-plaintext highlighter-rouge">dig +short</code></td>
    </tr>
    <tr>
      <td>Remote</td>
      <td><code class="language-plaintext highlighter-rouge">ssh</code>, <code class="language-plaintext highlighter-rouge">scp</code>, <code class="language-plaintext highlighter-rouge">rsync -avz</code></td>
    </tr>
    <tr>
      <td>Archives</td>
      <td><code class="language-plaintext highlighter-rouge">tar -czf</code> / <code class="language-plaintext highlighter-rouge">-xzf</code> / <code class="language-plaintext highlighter-rouge">-tzf</code></td>
    </tr>
    <tr>
      <td>Help</td>
      <td><code class="language-plaintext highlighter-rouge">command --help</code>, <code class="language-plaintext highlighter-rouge">man command</code>, <code class="language-plaintext highlighter-rouge">tldr command</code></td>
    </tr>
  </tbody>
</table>

<p>Next up, <a href="/portfolio-site/blog/2025/07/10/chapter-1-1-docker-basics/">Chapter 1.1</a> takes these fundamentals into containers: what Docker actually isolates, and how to build and run your first image.</p>]]></content><author><name>Echo Yin</name></author><category term="devops" /><category term="Platform Engineering" /><category term="DevOps" /><category term="Chapter Zero" /><category term="Linux" /><summary type="html"><![CDATA[Before containers, pipelines or clusters, there's a shell on a Linux box. This chapter covers the commands I reach for every day, grouped by the job you're trying to do: moving around, reading and finding things, chaining tools with pipes, permissions, processes, services, disks, networks and archives, with every non-obvious flag explained.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://e-choness.github.io/portfolio-site/assets/images/blogs/linux-commands.webp" /><media:content medium="image" url="https://e-choness.github.io/portfolio-site/assets/images/blogs/linux-commands.webp" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Chapter 3.1 - Building Your Internal Developer Portal with Backstage - A Comprehensive Guide</title><link href="https://e-choness.github.io/portfolio-site/blog/2025/05/13/chapter-3-1-backstage-guide-1/" rel="alternate" type="text/html" title="Chapter 3.1 - Building Your Internal Developer Portal with Backstage - A Comprehensive Guide" /><published>2025-05-13T00:00:00+00:00</published><updated>2025-05-13T00:00:00+00:00</updated><id>https://e-choness.github.io/portfolio-site/blog/2025/05/13/chapter-3-1-backstage-guide-1</id><content type="html" xml:base="https://e-choness.github.io/portfolio-site/blog/2025/05/13/chapter-3-1-backstage-guide-1/"><![CDATA[<h2 id="what-we-talk-about-when-we-talk-about-developer-portals">What We Talk About When We Talk About Developer Portals</h2>

<p>At its core, platform engineering is about self-service. This makes an internal <strong>developer portal</strong> critical in this new paradigm, as it’s where all self-service functionalities and integrations are implemented.</p>

<p>Given the importance of a developer portal, before building one, we need to clarify our expectations. Typically, to maximize the benefits of platform engineering, a developer portal will include several key features:</p>

<ul>
  <li>
    <p><strong>Service Catalog:</strong> This allows developers to view all projects, services, deployment statuses, documentation, ownership, and even on-call schedules and incidents.</p>
  </li>
  <li>
    <p><strong>Repository Scaffolding/Project Generation Tool:</strong> Tools like Cookie cutter can enable developers to spin up new services directly from the portal.</p>
  </li>
  <li>
    <p><strong>Customization:</strong> You’ll likely want to integrate your existing toolchain into your developer portal, making it a truly unified, one-stop experience. Possible integrations include Kubernetes, CI/CD status, on-call schedules, incident management systems, secret managers, and more.</p>
  </li>
</ul>

<hr />

<h2 id="choosing-a-tool-backstage">Choosing a Tool: Backstage</h2>

<p>Now that we understand what we truly want in a developer portal, let’s start building it.</p>

<p>A developer portal will have diverse functionalities, and the design/coding part itself is a massive project that not all teams can afford. This means we need a tool to quickly build the portal. Fortunately, such a tool already exists: <strong>Backstage</strong>.</p>

<p>Backstage is an open platform for building developer portals. It’s not a developer portal itself, but rather a tool for building one. Backstage includes:</p>

<ul>
  <li>
    <p><strong>Software Catalog:</strong> For managing all your software, such as microservices, libraries, data pipelines, websites, and ML models.</p>
  </li>
  <li>
    <p><strong>Software Templates:</strong> For quickly spinning up new projects and standardizing your tooling with enterprise best practices.</p>
  </li>
  <li>
    <p><strong>Documentation:</strong> Adopting a “docs-as-code” approach to easily create, maintain, find, and consume technical documentation.</p>
  </li>
  <li>
    <p><strong>Evolving Open-Source Plugin Ecosystem:</strong> To further extend Backstage’s customizability and functionality.</p>
  </li>
</ul>

<p>Backstage’s architecture is highly flexible: it has a frontend written in React/TypeScript and a backend written in Node.js. Its capabilities can be extended by adding plugins.</p>

<p>Additionally, Backstage (created by Spotify) is now hosted by the Cloud Native Computing Foundation (CNCF) as an incubating project. This means users get all the community support they need. There are also office hours you can join interactively every Thursday to learn exactly how the open-source platform can improve developer efficiency and experience.</p>

<p>Today, we’ll build a developer portal from scratch. After this tutorial, you’ll be able to use a template with a secure CI workflow to start a new service, check its CI status, and view its documentation, all in one place.</p>

<hr />

<h2 id="building-the-portal">Building the Portal</h2>

<h3 id="prerequisites">Prerequisites</h3>

<p>These are likely already familiar to most DevOps engineers:</p>

<ul>
  <li>
    <p><strong>Unix-based operating system:</strong> This can run on macOS, Linux, or Windows Subsystem for Linux (WSL).</p>
  </li>
  <li>
    <p><code class="language-plaintext highlighter-rouge">curl</code>, <code class="language-plaintext highlighter-rouge">git</code>, <code class="language-plaintext highlighter-rouge">Docker</code></p>
  </li>
  <li>
    <p><code class="language-plaintext highlighter-rouge">Node.js</code>, <code class="language-plaintext highlighter-rouge">yarn</code></p>
  </li>
</ul>

<hr />

<h3 id="creating-the-portal">Creating the Portal</h3>

<p>Run the following command:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>npx @backstage/create-app@latest
</code></pre></div></div>

<p>The command will ask for a name for your application. Enter a descriptive name, like “my-portal”, press Enter, and wait for the application to finish setting up.</p>

<p>Once the setup is complete, navigate into your newly created directory and run:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>yarn dev
</code></pre></div></div>

<p>That’s it! Your Backstage developer portal is now up and running.</p>

<p>Take some time to explore the interface and get familiar with the basic layout of the software catalog, templates, and documentation sections.</p>

<hr />

<h2 id="github-authentication-and-integration">GitHub Authentication and Integration</h2>

<p>Since the developer portal will be responsible for bootstrapping new code repositories, it requires operational permissions with GitHub. This is why we need to set up GitHub authentication and integration.</p>

<h3 id="personal-access-token-for-integration">Personal Access Token for Integration</h3>

<p>While using a GitHub App is often the best way to set up integrations due to its granular permission settings, for this tutorial, we’ll use a <strong>Personal Access Token (PAT)</strong> for a quicker start.</p>

<ol>
  <li>
    <p>Open the <a href="https://github.com/settings/tokens/new">GitHub token creation page</a> to create your personal access token.</p>
  </li>
  <li>
    <p>Provide a descriptive name in the “Note” field to identify this token, and choose an expiration date.</p>

    <ul>
      <li>
        <p>If you’re unsure about the expiration, we suggest selecting 7 days. (We’re only testing locally, not running in production.)</p>
      </li>
      <li>
        <p>For this tutorial, we will set the scope to the maximum to avoid issues with GitHub permissions. <strong>However, never do this in a production environment!</strong></p>
      </li>
    </ul>
  </li>
  <li>
    <p>Then, export the token as an environment variable:</p>

    <div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">export </span><span class="nv">GITHUB_TOKEN</span><span class="o">=</span><span class="s2">"your_personal_access_token_here"</span>
</code></pre></div>    </div>
  </li>
  <li>
    <p>In your <code class="language-plaintext highlighter-rouge">app-config.yaml</code> file, change the <code class="language-plaintext highlighter-rouge">integrations</code> section to the following:</p>

    <div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">integrations</span><span class="pi">:</span>
  <span class="na">github</span><span class="pi">:</span>
    <span class="pi">-</span> <span class="na">host</span><span class="pi">:</span> <span class="s">github.com</span>
      <span class="na">token</span><span class="pi">:</span> <span class="s">${GITHUB_TOKEN}</span>
</code></pre></div>    </div>
  </li>
</ol>

<h3 id="creating-a-github-oauth-application">Creating a GitHub OAuth Application</h3>

<ol>
  <li>
    <p>Visit <a href="https://github.com/settings/applications/new">https://github.com/settings/applications/new</a> to create your OAuth application.</p>
  </li>
  <li>
    <p>The <strong>Homepage URL</strong> should point to the Backstage frontend. For this tutorial, it will be <code class="language-plaintext highlighter-rouge">http://localhost:3000</code>.</p>
  </li>
  <li>
    <p>The <strong>Authorization callback URL</strong> will point to the Auth backend, most likely <code class="language-plaintext highlighter-rouge">http://localhost:7007/api/auth/github/handler/frame</code>.</p>
  </li>
  <li>
    <p>Then, open your <code class="language-plaintext highlighter-rouge">app-config.yaml</code> file again and update the <code class="language-plaintext highlighter-rouge">auth</code> section to configure authentication:</p>

    <div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">auth</span><span class="pi">:</span>
  <span class="na">environment</span><span class="pi">:</span> <span class="s">development</span>
  <span class="na">providers</span><span class="pi">:</span>
    <span class="na">github</span><span class="pi">:</span>
      <span class="na">development</span><span class="pi">:</span>
        <span class="na">clientId</span><span class="pi">:</span> <span class="s">your_github_oauth_app_client_id</span>
        <span class="na">clientSecret</span><span class="pi">:</span> <span class="s">your_github_oauth_app_client_secret</span>
</code></pre></div>    </div>

    <p><strong>Important Security Best Practice:</strong> Storing client secrets as hardcoded values in configuration files violates security best practices and should only be used for local development. For production use, you should adhere to the <a href="https://12factor.net/config">12-factor app</a> principles and read these values from environment variables.</p>
  </li>
</ol>

<p>After these configuration changes, restart your Backstage development server by running <code class="language-plaintext highlighter-rouge">yarn dev</code>.</p>

<hr />

<h2 id="creating-a-template">Creating a Template</h2>

<p>Next, let’s prepare a software template that can be used to instantly spin up new services. A template should include:</p>

<ul>
  <li>
    <p>Basic source code/directory structure common to your services</p>
  </li>
  <li>
    <p>Documentation</p>
  </li>
  <li>
    <p>CI workflows for testing/building/deploying services</p>
  </li>
</ul>

<p>For this tutorial, we will use this template: <a href="https://github.com/IronCore864/backstage-test-template">https://github.com/IronCore864/backstage-test-template</a></p>

<p>The directory structure is relatively simple, with only two parts:</p>

<ul>
  <li>
    <p>A <code class="language-plaintext highlighter-rouge">skeleton</code> folder</p>
  </li>
  <li>
    <p>A <code class="language-plaintext highlighter-rouge">template.yaml</code> file</p>
  </li>
</ul>

<h3 id="skeleton-folder"><code class="language-plaintext highlighter-rouge">skeleton</code> Folder</h3>

<p>The <code class="language-plaintext highlighter-rouge">skeleton</code> folder contains all the templated files that will be generated when a new service is created using this template. Variables are formatted as <code class="language-plaintext highlighter-rouge">${{ values.varName }}</code>. If you’re familiar with Helm, YAML, or Go templates (or any templating tool), you’ll find this easy to read and understand.</p>

<p>It’s worth highlighting the <code class="language-plaintext highlighter-rouge">catalog-info.yaml</code> file, which is used by Backstage. This file <strong>must</strong> exist; otherwise, the created service cannot be registered as a component in the portal. In our template, we’ve built in some GitHub Actions workflows. One will test pull requests and pushes to the main branch, and another will scan the repository for hardcoded secrets using <code class="language-plaintext highlighter-rouge">ggshield</code>.</p>

<p>This approach allows us to embed all CI/CD best practices directly into the template. When others roll out new services, they’ll have everything they need for security features enabled by default.</p>

<h3 id="templateyaml-file"><code class="language-plaintext highlighter-rouge">template.yaml</code> File</h3>

<p>The <code class="language-plaintext highlighter-rouge">template.yaml</code> file defines how the template appears in the portal’s user interface and what actions it performs. This file can be long and seem overwhelming at first glance, but a closer look reveals it’s quite intuitive:</p>

<ul>
  <li>
    <p>The syntax is similar to Kubernetes custom resources.</p>
  </li>
  <li>
    <p>It has two main sections: <code class="language-plaintext highlighter-rouge">parameters</code> and <code class="language-plaintext highlighter-rouge">steps</code>.</p>
  </li>
  <li>
    <p><code class="language-plaintext highlighter-rouge">parameters</code> define the required inputs and their types when using the template.</p>
  </li>
  <li>
    <p><code class="language-plaintext highlighter-rouge">steps</code> define what actually happens when the template is executed, much like a GitHub Actions workflow.</p>
  </li>
</ul>

<p><strong>Example Parameters:</strong></p>

<p>Each entry under <code class="language-plaintext highlighter-rouge">parameters</code> is one page of the form, written as JSON Schema; <code class="language-plaintext highlighter-rouge">ui:field</code> swaps in Backstage’s pickers.</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">parameters</span><span class="pi">:</span>
  <span class="pi">-</span> <span class="na">title</span><span class="pi">:</span> <span class="s">Service details</span>
    <span class="na">required</span><span class="pi">:</span> <span class="pi">[</span><span class="nv">service_name</span><span class="pi">,</span> <span class="nv">owner</span><span class="pi">]</span>
    <span class="na">properties</span><span class="pi">:</span>
      <span class="na">service_name</span><span class="pi">:</span>
        <span class="na">title</span><span class="pi">:</span> <span class="s">Service Name</span>
        <span class="na">type</span><span class="pi">:</span> <span class="s">string</span>
        <span class="na">description</span><span class="pi">:</span> <span class="s">Unique name of the service</span>
        <span class="na">ui:autofocus</span><span class="pi">:</span> <span class="kc">true</span>
      <span class="na">owner</span><span class="pi">:</span>
        <span class="na">title</span><span class="pi">:</span> <span class="s">Owner</span>
        <span class="na">type</span><span class="pi">:</span> <span class="s">string</span>
        <span class="na">description</span><span class="pi">:</span> <span class="s">Owner of the service</span>
        <span class="na">ui:field</span><span class="pi">:</span> <span class="s">OwnerPicker</span>
        <span class="na">ui:options</span><span class="pi">:</span>
          <span class="na">catalogFilter</span><span class="pi">:</span>
            <span class="na">kind</span><span class="pi">:</span> <span class="s">Group</span>
  <span class="pi">-</span> <span class="na">title</span><span class="pi">:</span> <span class="s">Repository</span>
    <span class="na">required</span><span class="pi">:</span> <span class="pi">[</span><span class="nv">repoUrl</span><span class="pi">,</span> <span class="nv">gitguardian_api_key</span><span class="pi">]</span>
    <span class="na">properties</span><span class="pi">:</span>
      <span class="na">repoUrl</span><span class="pi">:</span>
        <span class="na">title</span><span class="pi">:</span> <span class="s">Repository Location</span>
        <span class="na">type</span><span class="pi">:</span> <span class="s">string</span>
        <span class="na">ui:field</span><span class="pi">:</span> <span class="s">RepoUrlPicker</span>
        <span class="na">ui:options</span><span class="pi">:</span>
          <span class="na">allowedHosts</span><span class="pi">:</span> <span class="pi">[</span><span class="nv">github.com</span><span class="pi">]</span>
      <span class="na">gitguardian_api_key</span><span class="pi">:</span>
        <span class="na">title</span><span class="pi">:</span> <span class="s">GitGuardian API key</span>
        <span class="na">type</span><span class="pi">:</span> <span class="s">string</span>
        <span class="na">ui:field</span><span class="pi">:</span> <span class="s">Secret</span> <span class="c1"># masked in the form, never logged</span>
</code></pre></div></div>

<p><strong>Example Steps:</strong></p>

<p>Steps read the form through <code class="language-plaintext highlighter-rouge">parameters.*</code> (inside the skeleton files the same values are <code class="language-plaintext highlighter-rouge">values.*</code>), and sensitive fields through <code class="language-plaintext highlighter-rouge">secrets.*</code>:</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">steps</span><span class="pi">:</span>
  <span class="pi">-</span> <span class="na">id</span><span class="pi">:</span> <span class="s">fetch-base</span>
    <span class="na">name</span><span class="pi">:</span> <span class="s">Fetch Base</span>
    <span class="na">action</span><span class="pi">:</span> <span class="s">fetch:template</span>
    <span class="na">input</span><span class="pi">:</span>
      <span class="na">url</span><span class="pi">:</span> <span class="s">./skeleton</span>
      <span class="na">values</span><span class="pi">:</span>
        <span class="na">service_name</span><span class="pi">:</span> <span class="s">${{ parameters.service_name }}</span>
        <span class="na">owner</span><span class="pi">:</span> <span class="s">${{ parameters.owner }}</span>

  <span class="pi">-</span> <span class="na">id</span><span class="pi">:</span> <span class="s">publish</span>
    <span class="na">name</span><span class="pi">:</span> <span class="s">Publish</span>
    <span class="na">action</span><span class="pi">:</span> <span class="s">publish:github</span>
    <span class="na">input</span><span class="pi">:</span>
      <span class="na">repoUrl</span><span class="pi">:</span> <span class="s">${{ parameters.repoUrl }}</span>
      <span class="c1"># Stored as a GitHub Actions secret on the new repo, never written to a file</span>
      <span class="na">secrets</span><span class="pi">:</span>
        <span class="na">GITGUARDIAN_API_KEY</span><span class="pi">:</span> <span class="s">${{ secrets.gitguardian_api_key }}</span>

  <span class="pi">-</span> <span class="na">id</span><span class="pi">:</span> <span class="s">register</span>
    <span class="na">name</span><span class="pi">:</span> <span class="s">Register</span>
    <span class="na">action</span><span class="pi">:</span> <span class="s">catalog:register</span>
    <span class="na">input</span><span class="pi">:</span>
      <span class="na">repoContentsUrl</span><span class="pi">:</span> <span class="s">${{ steps['publish'].output.repoContentsUrl }}</span>
      <span class="na">catalogInfoPath</span><span class="pi">:</span> <span class="s">/catalog-info.yaml</span>
</code></pre></div></div>

<p>Keep tokens out of <code class="language-plaintext highlighter-rouge">fetch:template</code> values: anything passed there can be rendered into the skeleton’s files and committed to the new repository. Backstage publishes with the integration token from <code class="language-plaintext highlighter-rouge">app-config.yaml</code>, and the GitGuardian key goes to the repository as an Actions secret.</p>

<p>From the file above, we can infer its specific definition:</p>

<ol>
  <li>
    <p>First, it asks for the service details: <code class="language-plaintext highlighter-rouge">service_name</code> and <code class="language-plaintext highlighter-rouge">owner</code>.</p>
  </li>
  <li>
    <p>Then, it asks for a repository location and the GitGuardian API key the CI pipeline needs.</p>
  </li>
  <li>
    <p>Next, it fetches the template, renders it, publishes it to GitHub (setting the key as a repository secret), and registers it in our portal.</p>
  </li>
</ol>

<h3 id="registering-the-template">Registering the Template</h3>

<p>Finally, add your template to the portal’s catalog so others can use it.</p>

<p>The simplest catalog configuration is to declaratively add locations pointing to YAML files with static locations. These locations will be added under <code class="language-plaintext highlighter-rouge">catalog.locations</code> in your <code class="language-plaintext highlighter-rouge">app-config.yaml</code> file.</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">catalog</span><span class="pi">:</span>
  <span class="na">locations</span><span class="pi">:</span>
    <span class="pi">-</span> <span class="na">type</span><span class="pi">:</span> <span class="s">url</span>
      <span class="na">target</span><span class="pi">:</span> <span class="s">https://github.com/IronCore864/backstage-test-template/blob/main/template.yaml</span>
</code></pre></div></div>

<p>The rule above allows us to add templates from the specified URL.</p>

<p>Remember to restart your <code class="language-plaintext highlighter-rouge">yarn dev</code> server after these changes.</p>

<hr />

<h2 id="bringing-everything-together">Bringing Everything Together</h2>

<p>Now that everything is set up, it’s time to see it in action.</p>

<p>Visit <code class="language-plaintext highlighter-rouge">http://localhost:3000</code>, then click the “Create” button and select our template.</p>

<p>Enter the necessary information. You’ll need to create a GitGuardian API key here: <a href="https://dashboard.gitguardian.com/api/personal-access-tokens">https://dashboard.gitguardian.com/api/personal-access-tokens</a>.</p>

<p>Once everything is set up, click “Next.” Here is what happens behind that button:</p>

<pre><code class="language-mermaid">sequenceDiagram
  actor Dev as Developer
  participant UI as Frontend :3000
  participant BE as Backend :7007
  participant GH as GitHub
  participant CAT as Catalog
  Dev-&gt;&gt;UI: Create: pick template,&lt;br/&gt;fill in the form
  UI-&gt;&gt;BE: run template&lt;br/&gt;(parameters + secrets)
  BE-&gt;&gt;BE: fetch:template&lt;br/&gt;renders ./skeleton
  BE-&gt;&gt;GH: publish:github: create repo,&lt;br/&gt;push files, set secret
  GH--&gt;&gt;BE: repoContentsUrl
  BE-&gt;&gt;CAT: catalog:register&lt;br/&gt;reads catalog-info.yaml
  GH-&gt;&gt;GH: push runs Actions:&lt;br/&gt;tests + ggshield
  Dev-&gt;&gt;UI: open the new component
  UI-&gt;&gt;CAT: owner, docs, links
  UI-&gt;&gt;GH: CI status
</code></pre>

<p>The new service appears in the catalog with its owner and the rendered files, and its page shows the CI runs.</p>

<p>It appears the pipelines have completed successfully. You can click on them to view more details, including detailed steps and logs. If you prefer to view them in your CI software (GitHub Actions, in this case), you can click the corresponding link to jump directly there. For your reference, this repository was created using the template above.</p>

<p>This means that regardless of the toolchain a team uses, team members don’t have to remember 10 different URLs for 10 different tools, nor do they need to keep 10 tabs open constantly. When they need any information, they only need to visit the developer portal, and that’s precisely the advantage of an internal developer portal.</p>

<hr />

<h2 id="summary">Summary</h2>

<p>In this article, we reviewed the characteristics of a developer portal, learned how to create our own using the open-source Backstage tool, configured our portal with GitHub, created a software template, and bootstrapped a service from it.</p>

<p>In real-world scenarios, a developer portal can be much more as integrations grow. Imagine if you deploy services in Kubernetes, use Argo CD for GitOps deployments, HashiCorp Vault for secret management, and all these integrations are within your portal. When you need to check deployment status, for example, to view actual resources in K8s, you don’t have to visit Vault, Argo CD, or the K8s Dashboard. You don’t even have to remember their URLs; just click directly on the developer portal.</p>

<p>It’s important to note that this tutorial is only for a quick local start. For production use, further considerations and adjustments are necessary based on your specific situation. For instance, we currently use static configuration, which means catalog information would be lost if the development server were restarted. To address this, you would need to configure Postgres for the portal. Another example is using <code class="language-plaintext highlighter-rouge">yarn dev</code> to start both the frontend and backend; in production, you might want to separate them, deploy them as containers in K8s, and create Ingress for them.</p>

<p>Backstage plugins, which extend the portal much further than templates, are the natural next step from here.</p>]]></content><author><name>Echo Yin</name></author><category term="devops" /><category term="Platform Engineering" /><category term="Backstage" /><category term="Chapter Three" /><summary type="html"><![CDATA[This guide explores the essentials of internal developer portals, their key features, and provides a hands-on tutorial for building one using Backstage, covering setup, GitHub integration, and template creation for efficient service bootstrapping.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://e-choness.github.io/portfolio-site/assets/images/blogs/backstage.webp" /><media:content medium="image" url="https://e-choness.github.io/portfolio-site/assets/images/blogs/backstage.webp" xmlns:media="http://search.yahoo.com/mrss/" /></entry></feed>