<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ifeoluwa O. Olaiya on Medium]]></title>
        <description><![CDATA[Stories by Ifeoluwa O. Olaiya on Medium]]></description>
        <link>https://medium.com/@ifeoluwa1201?source=rss-3486717239fe------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*s8UGLxDSEFNuFqf_N3IB_w.jpeg</url>
            <title>Stories by Ifeoluwa O. Olaiya on Medium</title>
            <link>https://medium.com/@ifeoluwa1201?source=rss-3486717239fe------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 15:24:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ifeoluwa1201/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[A Practical Guide to GitHub Actions]]></title>
            <link>https://medium.com/@ifeoluwa1201/a-practical-guide-to-github-actions-f4dcf1a3c74c?source=rss-3486717239fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4dcf1a3c74c</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <dc:creator><![CDATA[Ifeoluwa O. Olaiya]]></dc:creator>
            <pubDate>Wed, 14 Jan 2026 08:02:51 GMT</pubDate>
            <atom:updated>2026-01-14T08:02:51.501Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fg9t_Ufwt_D_rBtwNIqYEA.png" /></figure><h4><strong>Core concepts and patterns for real-world automation</strong></h4><p>GitHub Actions automates the work that slows development down, including testing, building, checking code quality, and deploying applications. Instead of running commands manually after every change, you define workflows once and let GitHub run them for you.</p><p>This guide breaks down 15 essential GitHub Actions concepts, learned through hands-on use. It starts with the basics, moves through triggers and configuration, and finishes with advanced patterns, each explained with practical examples.</p><p>If you are getting started with GitHub Actions or want to truly understand how it works under the hood, this guide is for you.</p><p>Let’s dive in.</p><h3>1. Workflows</h3><p>A workflow is an automated process defined in a YAML file stored in .github/workflows/. Workflows contain one or more jobs and are triggered by events like pushes, pull requests, or manual dispatch. Each workflow runs independently and can be configured to run on different conditions.</p><p>Workflows are the top-level organizational unit in GitHub Actions. They define what should happen, when it should happen, and where it should run. When I first started, it clicked once I realized they’re just YAML files that orchestrate everything else.</p><pre>name: CI Pipeline<br><br>on:<br>  push:<br>    branches: [main]<br>  pull_request:<br><br>jobs:<br>  test:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v4<br>      - name: Run tests<br>        run: npm test</pre><p><strong>Example breakdown</strong>: This workflow triggers on pushes to main or any pull request. It has one job (test) that checks out code and runs tests.</p><h3>2. Jobs</h3><p>Jobs are groups of steps that execute on the same runner. Multiple jobs in a workflow run in parallel by default, but you can configure sequential execution using job dependencies. Each job runs in its own fresh virtual environment. Files created in one job aren’t available in another unless shared through artifacts.</p><p>Jobs run in parallel by default. If you need sequential execution, use the needs keyword to create dependencies between job</p><pre>jobs:<br>  build:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: Build application<br>        run: npm run build<br><br>  test:<br>    runs-on: ubuntu-latest<br>    needs: build  # Wait for build to complete<br>    steps:<br>      - name: Run tests<br>        run: npm test<br><br>  deploy:<br>    runs-on: ubuntu-latest<br>    needs: [build, test]  # Wait for both build and test<br>    steps:<br>      - name: Deploy<br>        run: echo &quot;Deploying...&quot;</pre><p><strong>Example breakdown</strong>: The test job waits for build to finish. The deploy job waits for both build and test.</p><h3>3. Steps</h3><p>Steps are individual tasks that run commands or actions within a job. They execute sequentially in the order defined. There are two types: run steps that execute shell commands, and uses steps that run pre-built actions.</p><p>Steps share the same runner environment within a job, so environment variables and files created in one step are available to subsequent steps.</p><pre>steps:<br>  # Using an action<br>  - name: Checkout code<br>    uses: actions/checkout@v4<br><br>  # Running a command<br>  - name: Install dependencies<br>    run: npm install<br><br>  # Multi-line command<br>  - name: Run multiple commands<br>    run: |<br>      echo &quot;Building application&quot;<br>      npm run build<br>      echo &quot;Build complete&quot;<br><br>  # Conditional step<br>  - name: Deploy to production<br>    if: github.ref == &#39;refs/heads/main&#39;<br>    run: ./deploy.sh</pre><p><strong>Example breakdown</strong>: The first step uses a pre-built action to checkout code. The last step only runs if we’re on the main branch (thanks to the if condition).</p><h3>4. Workflow Events</h3><p>Workflow events are triggers that cause a workflow to run. Common events include push, pull_request, workflow_dispatch (manual trigger), and schedule (cron-based). You can configure multiple events for a single workflow.</p><p>The workflow_dispatch event is particularly useful for testing. It adds a manual <strong>&quot;Run workflow&quot;</strong> button in the GitHub UI, letting you trigger workflows without having to push code.</p><pre>on:<br>  # Run on push to main or develop<br>  push:<br>    branches: [main, develop]<br><br>  # Run on pull requests targeting main<br>  pull_request:<br>    branches: [main]<br><br>  # Add manual trigger button<br>  workflow_dispatch:<br><br>  # Run daily at 2 AM UTC<br>  schedule:<br>    - cron: &#39;0 2 * * *&#39;<br><br>  # Run when releases are created<br>  release:<br>    types: [created]</pre><p><strong>Example breakdown</strong>: This workflow triggers in five different scenarios: pushes to main/develop, PRs to main, manual runs via UI, daily at 2 AM, and when releases are created.</p><h3>5. Workflow Runners</h3><p>Runners are servers that execute your workflow jobs. GitHub provides hosted runners with pre-installed software for Ubuntu, Windows, and macOS. You can also use self-hosted runners on your own infrastructure.</p><p>GitHub-hosted runners are convenient and require zero setup. For most projects, ubuntu-latest is all you need.</p><pre>jobs:<br>  ubuntu-job:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - run: echo &quot;Running on Ubuntu&quot;<br><br>  windows-job:<br>    runs-on: windows-latest<br>    steps:<br>      - run: echo &quot;Running on Windows&quot;<br><br>  macos-job:<br>    runs-on: macos-latest<br>    steps:<br>      - run: echo &quot;Running on macOS&quot;<br><br>  self-hosted-job:<br>    runs-on: self-hosted<br>    steps:<br>      - run: echo &quot;Running on self-hosted runner&quot;</pre><p><strong>Example breakdown</strong>: Each job runs on a different operating system. The last one uses a self-hosted runner you’d set up yourself.</p><h3>6. Event Filters</h3><p>Event filters control when workflows run based on branches, paths, or tags. Without filters, a push event triggers on every push to any branch. With filters, you can target specific branches or only run when certain files change, saving compute resources.</p><p>Common filters include branches (which branches trigger the workflow) and paths (which file changes trigger the workflow). Both support glob patterns for matching multiple items.</p><pre>on:<br>  push:<br>    branches:<br>      - main<br>      - develop<br>    paths:<br>      - &#39;src/**&#39;<br>      - &#39;package.json&#39;<br><br>jobs:<br>  test:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: Checkout code<br>        uses: actions/checkout@v4<br><br>      - name: Run tests<br>        run: npm test</pre><p><strong>Example breakdown</strong>: This workflow only runs when you push to the main or develop branches AND when files in the src/ directory or package.json change.</p><h3>7. Activity Types</h3><p>Activity types let you specify exactly which actions trigger your workflow. For example, the pull_request event has different activity types: opened (new PR created), synchronize (new commits pushed to existing PR), reopened (closed PR reopened), and closed (PR closed or merged).</p><p>Without specifying activity types, pull request workflows automatically run on opened, synchronize, and reopened. By specifying activity types, you control exactly when workflows run.</p><pre>on:<br>  pull_request:<br>    types: [opened, synchronize]<br><br>jobs:<br>  test:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: Checkout code<br>        uses: actions/checkout@v4<br><br>      - name: Run tests<br>        run: npm test</pre><p><strong>Example breakdown</strong>: This workflow only runs when a PR is first opened or when new commits are pushed to it. It will NOT run when a PR is reopened or closed. This prevents unnecessary test runs when closing PRs.</p><h3>8. Workflow Contexts</h3><p>Contexts provide access to information about workflow runs, jobs, steps, and the environment. The most commonly used are github (event data, repository info), env (environment variables), secrets (sensitive data), jobs (job outputs), and steps (step outputs).</p><p>The ${{ }} syntax may seem confusing at first, but contexts are what give GitHub Actions its flexibility and power.</p><pre>name: Context Examples<br><br>on: push<br><br>env:<br>  GLOBAL_VAR: &#39;global value&#39;<br><br>jobs:<br>  example:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: Show context information<br>        run: |<br>          echo &quot;Event name: ${{ github.event_name }}&quot;<br>          echo &quot;Repository: ${{ github.repository }}&quot;<br>          echo &quot;Branch: ${{ github.ref }}&quot;<br>          echo &quot;Commit SHA: ${{ github.sha }}&quot;<br>          echo &quot;Environment: ${{ env.GLOBAL_VAR }}&quot;</pre><p><strong>Example breakdown</strong>: The github context provides repo/commit info. The env context accesses environment variables.</p><h3>9. Expressions and Variables</h3><p>Expressions use the ${{ }} syntax to create dynamic workflows. They can access context information (like github.ref), evaluate conditions, perform string operations, and reference variables. This makes workflows flexible and reusable.</p><p><strong>Environment Variables</strong>: Defined with env in your workflow file at three levels: workflow (available everywhere), job (available in that job), or step (available in that step only). Inner scopes override outer ones.</p><p><strong>Configuration Variables</strong>: Defined in your repository or organization settings (not in workflow files). Accessed via ${{ vars.VARIABLE_NAME }}. These are useful for values shared across multiple workflows or repositories.</p><p><strong>Expressions</strong>: Beyond just accessing values, expressions can use operators (==, !=, &amp;&amp;, ||) for conditional logic and comparisons.</p><pre>env:<br>  NODE_VERSION: &#39;20&#39;<br>  ENVIRONMENT: &#39;production&#39;<br><br>jobs:<br>  build:<br>    runs-on: ubuntu-latest<br>    env:<br>      ENVIRONMENT: &#39;staging&#39;  # Job-level overrides workflow-level<br>    steps:<br>      - name: Checkout code<br>        uses: actions/checkout@v4<br><br>      - name: Setup Node<br>        uses: actions/setup-node@v4<br>        with:<br>          node-version: ${{ env.NODE_VERSION }}<br><br>      - name: Display job-level variables<br>        run: |<br>          echo &quot;Node version: ${{ env.NODE_VERSION }}&quot;<br>          echo &quot;Environment: ${{ env.ENVIRONMENT }}&quot;<br><br>      - name: Display step-level override<br>        env:<br>          ENVIRONMENT: &#39;development&#39;  # Step-level overrides job-level<br>        run: echo &quot;Environment in this step: ${{ env.ENVIRONMENT }}&quot;<br><br>      - name: Deploy using expression<br>        if: github.ref == &#39;refs/heads/main&#39;<br>        run: echo &quot;Deploying to ${{ env.ENVIRONMENT }}&quot;</pre><p><strong>Example breakdown</strong>: NODE_VERSION is defined at workflow level (accessible everywhere). ENVIRONMENT is defined at three levels: workflow (production), job (staging), and step (development). The job-level value overrides the workflow-level, so most steps see staging. The third step has step-level override, so it sees development. The deploy step uses an expression with if to only run on main branch.</p><h3>10. Functions</h3><p>GitHub Actions provides built-in functions for common operations. Key functions include contains() and startsWith() for string matching, hashFiles() for cache keys, success() and failure() for conditional steps based on job status, and toJSON() for debugging contexts.</p><p>These functions enable powerful conditional logic and dynamic behaviour in your workflows.</p><pre>jobs:<br>  build-and-notify:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: Run tests<br>        id: tests<br>        run: npm test<br><br>      - name: Notify on success<br>        if: success()<br>        run: echo &quot;Tests passed!&quot;<br><br>      - name: Notify on failure<br>        if: failure()<br>        run: echo &quot;Tests failed!&quot;</pre><p><strong>Example breakdown</strong>: After running tests, success() evaluates to true if all previous steps succeeded (triggers success notification). failure() evaluates to true if any previous step failed (triggers failure notification). These status functions let you conditionally execute steps based on workflow outcomes.</p><h3>11. Inputs and Outputs</h3><p>Inputs allow passing data into workflows (for workflow_dispatch and reusable workflows). Outputs enable passing data from steps to jobs and from jobs to other jobs or workflows.</p><p>The output flow has three levels: steps write to $GITHUB_OUTPUT, jobs reference step outputs, and workflows reference job outputs. Each level must explicitly declare what it exposes.</p><pre>name: Inputs and Outputs<br><br>on:<br>  workflow_dispatch:<br>    inputs:<br>      name:<br>        description: &#39;Your name&#39;<br>        required: true<br>        type: string<br><br>jobs:<br>  greet:<br>    runs-on: ubuntu-latest<br>    outputs:<br>      message: ${{ steps.greeting.outputs.message }}<br>    steps:<br>      - name: Create greeting<br>        id: greeting<br>        run: |<br>          echo &quot;message=Hello, ${{ inputs.name }}!&quot; &gt;&gt; $GITHUB_OUTPUT<br><br>  display:<br>    needs: greet<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: Display greeting<br>        run: echo &quot;${{ needs.greet.outputs.message }}&quot;</pre><p><strong>Example breakdown</strong>: The workflow accepts a name input via manual trigger. The greet job creates a greeting message and writes it to $GITHUB_OUTPUT. The job exposes it as an output. The display job accesses it via needs.greet.outputs.message and prints it.</p><h3>12. Caching and Artifacts</h3><p>Caching and artifacts both store files but serve different purposes. Cache stores dependencies across workflow runs (like node_modules), expiring after 7 days of no access. Artifacts store build outputs within a workflow run to share between jobs, persisting for 90 days.</p><p>Use caching to avoid reinstalling unchanged dependencies. Use artifacts to pass files between jobs in the same run.</p><pre>jobs:<br>  build:<br>    runs-on: ubuntu-latest<br>    steps:<br>      # CACHE: Speed up dependency installation<br>      - name: Cache dependencies<br>        uses: actions/cache@v3<br>        id: cache<br>        with:<br>          path: node_modules<br>          key: deps-${{ hashFiles(&#39;package-lock.json&#39;) }}<br><br>      - name: Install dependencies<br>        if: steps.cache.outputs.cache-hit != &#39;true&#39;<br>        run: npm ci<br><br>      - name: Build<br>        run: npm run build<br><br>      # ARTIFACT: Share build output with deploy job<br>      - name: Upload build artifact<br>        uses: actions/upload-artifact@v4<br>        with:<br>          name: build-files<br>          path: build/<br><br>  deploy:<br>    needs: build<br>    runs-on: ubuntu-latest<br>    steps:<br>      # ARTIFACT: Download build from previous job<br>      - name: Download build artifact<br>        uses: actions/download-artifact@v4<br>        with:<br>          name: build-files<br>          path: build/<br><br>      - name: Deploy<br>        run: echo &quot;Deploying files from build/&quot;</pre><p><strong>Example breakdown</strong>:</p><p><strong>Build job:</strong></p><ul><li><strong>Cache step</strong>: Checks if node_modules from a previous run exists with the same package-lock.json hash. If found (cache hit), it restores them. If not (cache miss), continues to next step.</li><li><strong>Install step</strong>: Only runs if cache missed (the if condition checks cache-hit != &#39;true&#39;). Installs dependencies with npm ci.</li><li><strong>Build step</strong>: Builds the application (using cached or freshly installed dependencies).</li><li><strong>Upload artifact step</strong>: Saves the build/ folder as an artifact named build-files so the deploy job can access it.</li></ul><p><strong>Deploy job:</strong></p><ul><li>Runs in a fresh environment (doesn’t have files from build job)</li><li><strong>Download artifact step</strong>: Retrieves the build-files artifact uploaded by the build job and extracts it to build/ folder.</li><li><strong>Deploy step</strong>: Uses the downloaded build files to deploy.</li></ul><p><strong>Key difference</strong>: Cache persists across workflow runs for speed (survives multiple commits). Artifacts only exist within a workflow run to share files between jobs (each job has its own clean environment).</p><h3>13. Matrices</h3><p>Matrices run a job multiple times with different configurations. Define variables in a matrix and GitHub Actions creates a job for each combination. This is ideal for testing across multiple OS versions or language versions.</p><p>Advanced features like include and exclude give you fine-grained control.</p><pre>jobs:<br>  test:<br>    runs-on: ${{ matrix.os }}<br>    strategy:<br>      matrix:<br>        node: [18, 20, 21]<br>        os: [ubuntu-latest, windows-latest]<br><br>    steps:<br>      - name: Checkout code<br>        uses: actions/checkout@v4<br><br>      - name: Setup Node<br>        uses: actions/setup-node@v4<br>        with:<br>          node-version: ${{ matrix.node }}</pre><p><strong>Example breakdown</strong>: The matrix defines two variables: node with 3 values and os with 2 values. GitHub Actions creates 6 jobs (3 × 2 = 6): ubuntu-18, ubuntu-20, ubuntu-21, windows-18, windows-20, windows-21. Each job uses ${{ matrix.node }} and ${{ matrix.os }} to access its specific values. This lets you test across multiple configurations without writing 6 separate jobs.</p><h3>14. Reusable Workflows</h3><p>Reusable workflows eliminate duplication by defining a template that other workflows can call. The reusable workflow uses workflow_call as its trigger (not workflow_dispatch) and can accept inputs, secrets, and return outputs.</p><p>I spent 30 minutes debugging when I used workflow_dispatch instead of workflow_call—they&#39;re different!</p><p><strong>Reusable workflow </strong>(.github/workflows/greet-reusable.yaml):</p><pre>name: Reusable Greeting<br><br>on:<br>  workflow_call:<br>    inputs:<br>      username:<br>        required: true<br>        type: string<br><br>jobs:<br>  greet:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: Say hello<br>        run: echo &quot;Hello, ${{ inputs.username }}! Welcome to the workflow.&quot;</pre><p><strong>Calling workflow</strong> (.github/workflows/main.yaml):</p><pre>name: Main Workflow<br><br>on:<br>  push:<br>    branches: [main]<br><br>jobs:<br>  call-greeting:<br>    uses: ./.github/workflows/greet-reusable.yaml<br>    with:<br>      username: &#39;DevOps Engineer&#39;</pre><p><strong>Example breakdown</strong>: The reusable workflow accepts a username input. The calling workflow references it with ./ (same repository) and passes the input using with:. When you push to main, it calls the reusable workflow and displays the greeting.</p><h4><strong>Cross-repository usage</strong>:</h4><p>You can also call reusable workflows from different repositories using owner/repo/.github/workflows/file.yaml@main syntax. This is useful for sharing workflows across multiple projects or creating organization-wide workflow standards.</p><h3>15. Managing Concurrency</h3><p>Concurrency prevents multiple workflow runs or jobs from executing at the same time when they might conflict. You set it at the workflow level (entire workflow) or job level (specific jobs only).</p><p><strong>Two important settings:</strong></p><ul><li>group: Name that identifies which runs/jobs are mutually exclusive</li><li>cancel-in-progress: true = cancel old run, false = queue and wait</li></ul><h4><strong>Workflow-level concurrency:</strong></h4><pre>name: Deploy to Production<br><br>on:<br>  push:<br>    branches: [main]<br><br>concurrency:<br>  group: production-deploy<br>  cancel-in-progress: true<br><br>jobs:<br>  deploy:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: Deploy<br>        run: echo &quot;Deploying to production&quot;</pre><p><strong>Example breakdown</strong>: If you push twice quickly, the first deployment gets cancelled and the second runs. This prevents old code from deploying after new code.</p><h4>Job-Level Concurrency</h4><pre>jobs:<br>  test:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: Run tests<br>        run: npm test<br><br>  deploy:<br>    runs-on: ubuntu-latest<br>    concurrency:<br>      group: deploy-production<br>      cancel-in-progress: false<br>    steps:<br>      - name: Deploy<br>        run: echo &quot;Deploying&quot;</pre><p><strong>Example breakdown</strong>: The test job has no concurrency control, so multiple test runs can happen simultaneously. The deploy job has concurrency with cancel-in-progress: false, so deployments queue up instead of cancelling each other (ensuring every commit gets deployed in order).</p><h3>Final Thoughts</h3><p>Looking back at these concepts, from basic workflow structure to advanced patterns like matrices and concurrency, what stands out most is how hands-on practice made everything click. Reading the official <a href="https://docs.github.com/en/actions">documentation</a> helped, but actually building workflows, watching them fail, and debugging issues taught me far more than any tutorial could. Every error message became a lesson, and every successful run confirmed a new understanding.</p><p>This is not something you master quickly, and that is completely fine. I spent days working through these ideas by building real workflows. Some days everything made sense. Other days I spent an hour debugging why a secret was not accessible. That is part of the learning process. Each workflow you build reinforces what you already know and exposes what you need to learn next.</p><p>If you are starting your GitHub Actions journey, begin with something small. Automate one task for a simple project, such as running tests or building your code. Then iterate. Add caching when builds feel slow. Use matrices when you need cross-platform testing. Introduce concurrency when workflows start colliding. You do not need every feature, only the ones that solve real problems you are facing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4dcf1a3c74c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Docker Compose to Kubernetes: A Complete Practical Guide]]></title>
            <link>https://medium.com/@ifeoluwa1201/from-docker-compose-to-kubernetes-a-complete-practical-guide-dd52b463aac0?source=rss-3486717239fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd52b463aac0</guid>
            <category><![CDATA[scripting]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[dcoker]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Ifeoluwa O. Olaiya]]></dc:creator>
            <pubDate>Mon, 05 Jan 2026 09:36:35 GMT</pubDate>
            <atom:updated>2026-01-05T09:40:12.654Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ovHaNkd0SFL05PB3TU6k7g.png" /></figure><h4>A hands-on journey from docker-compose up to production-ready Kubernetes deployments.</h4><h3>Why This Guide Exists (And Why You Need It)</h3><p>Picture this: You’ve just finished building your application. It’s beautiful. It works perfectly on your laptop/local, you run docker-compose up everything&#39;s running. Database connected, API responding, life is good.</p><p>Then someone asks: “How do we deploy this to production?”</p><p>Suddenly, you’re staring at a wall of Kubernetes documentation, trying to figure out what a Pod is and why your perfectly good Docker Compose file won’t just… work.</p><p><strong>This is that gap, the chasm between “it works on Docker Compose” and “it runs reliably in Kubernetes.”</strong> This guide is your bridge across it.</p><p>We’re building a real-world Go API with MongoDB, JWT authentication, and all the trimmings you’d expect in production. No toy examples, no shortcuts that fall apart at scale. Just practical, battle-tested patterns you can use tomorrow.</p><h3>What You’ll Build</h3><p>By the end of this guide, you’ll have:</p><ul><li><strong>A fully containerised Go application</strong> using multi-stage Docker builds</li><li><strong>Docker Compose setup</strong> for local development that actually feels good to use</li><li><strong>Complete Kubernetes deployment</strong> with persistent storage, secrets management, and health checks</li><li><strong>NGINX Ingress</strong> for routing (because LoadBalancer costs money in the cloud)</li><li><strong>Automation scripts</strong> so you’re not typing kubectl multiple times per deploy</li><li><strong>Real debugging skills</strong> from the mistakes I made so you don’t have to</li></ul><h3>The Stack</h3><ul><li><strong>Backend</strong>: Go (Gin framework)</li><li><strong>Database</strong>: MongoDB 8.0</li><li><strong>Containerisation</strong>: Docker</li><li><strong>Orchestration</strong>: Kubernetes (KIND for local, but patterns work everywhere)</li><li><strong>Ingress</strong>: NGINX Ingress Controller</li><li><strong>Authentication</strong>: JWT tokens</li></ul><h3>Prerequisites</h3><ul><li><strong>Docker and Docker Compose</strong>: For containerization and local development</li><li><strong>Kubernetes cluster</strong>: KIND recommended for local testing (we’ll set this up in Part 3)</li><li><strong>kubectl CLI tool</strong>: For interacting with Kubernetes</li><li><strong>Go 1.25+</strong>: Only needed if you want to modify the backend code locally</li></ul><h3>Understanding Go (Golang)</h3><p>Quick context on the language powering this API: <strong>Go is a compiled language</strong>. When you run go build, you get a single, standalone executable binary. No interpreter, no runtime, no node_modules folder.</p><p>This is why our multi-stage Dockerfile works so well. The build stage needs the full Go compiler (~400MB), but the runtime stage? Just the compiled binary on Alpine Linux (~20MB total). Everything the app needs is already baked into that one executable.</p><p>Compare this to Python or Node.js: you’d need the interpreter/runtime plus all packages in your container, hundreds of megabytes and potential version conflicts. With Go, you copy one binary and you’re done.</p><p>Bonus: Go’s built-in concurrency (goroutines) means our tiny 128Mi Kubernetes pod can handle hundreds of simultaneous requests without breaking a sweat. Go containers are production-ready due to their fast startup, small footprint, and predictable behaviour<em>.</em></p><h3>Part 1: Understanding Your Starting Point</h3><h4>The Application</h4><p>We’re working with <strong>MuchToDo, </strong>a task management API that handles:</p><ul><li>User registration and JWT-based authentication</li><li>Full CRUD operations for todos</li><li>MongoDB for persistence</li><li>Optional Redis caching</li><li>Health check endpoints</li><li>Swagger documentation</li></ul><p>The codebase uses <strong>Viper</strong> for configuration, which becomes important later (spoiler: it reads .env files, not just environment variables).</p><h4>The Challenge</h4><p>Getting this to work in Docker Compose is straightforward. Getting it to work in Kubernetes? That’s where things get interesting.</p><p>The main hurdles we’ll tackle:</p><ol><li><strong>Configuration management</strong>: How do you get your .env file into a pod?</li><li><strong>Database initialization</strong>: MongoDB needs proper setup with authentication</li><li><strong>Persistent storage</strong>: Your data needs to survive pod restarts</li><li><strong>Service discovery</strong>: Containers need to find each other</li><li><strong>External access</strong>: Users need to actually reach your API</li><li><strong>Secrets management</strong>: Passwords don’t belong in Git</li></ol><p>Let’s solve them one by one.</p><h3>Part 2: Docker Compose Foundation</h3><h4>The Dockerfile (Multi-Stage Build)</h4><p>First, we need a solid Docker image. Multi-stage builds are crucial as they separate the build environment from the runtime environment, drastically reducing image size and attack surface.</p><p>Here’s our production-ready Dockerfile:</p><pre># Build Stage - Compile the Go application<br>FROM golang:1.25.5-alpine AS builder<br><br>WORKDIR /build<br><br># Copy and download dependencies first (for Docker caching)<br>COPY MuchToDo/go.mod MuchToDo/go.sum ./<br>RUN go mod download<br><br># Copy source code<br>COPY MuchToDo/ ./<br><br># Build the binary<br>RUN go build -o main ./cmd/api/main.go<br><br><br># Runtime Stage - Run the application<br>FROM alpine:latest AS runtime<br><br># Install curl for health checks<br>RUN apk --no-cache add ca-certificates curl<br><br># Create non-root user<br>RUN adduser -D -u 1000 appuser<br><br>WORKDIR /app<br><br># Copy binary from build stage<br>COPY --from=builder /build/main .<br>COPY --from=builder /build/docs ./docs<br><br># Use non-root user<br>USER appuser<br><br># Expose port<br>EXPOSE 8080<br><br># Health check with curl<br>HEALTHCHECK --interval=30s --timeout=3s \<br>  CMD curl -f http://localhost:8080/health || exit 1<br><br># Run the app<br>CMD [&quot;./main&quot;]</pre><p><strong>Why this approach?</strong></p><ul><li><strong>Dependency caching</strong>: We copy go.mod and go.sum first, then run go mod download. Docker caches this layer, so rebuilds are faster when code changes but dependencies don&#39;t.</li><li><strong>Multi-stage build</strong>: The builder stage is ~400MB with the Go compiler and tools. The runtime stage? Just ~20MB with only the compiled binary and Alpine Linux essentials.</li><li><strong>Security basics:<br></strong>– Runs as a regular user (appuser), not as root—safer if the container gets compromised<br>– Alpine Linux is tiny and has fewer packages installed — less stuff means fewer vulnerabilities<br>– No source code in the final image, just the compiled binary</li><li><strong>Built-in health checks</strong>: Docker’s HEALTHCHECK directive lets Docker Compose (and later Kubernetes) verify the container is actually working, not just running.</li><li><strong>Documentation support</strong>: We copy the docs/ folder so Swagger API documentation works in the deployed container(s).</li></ul><h4>Docker Compose Setup</h4><p>Docker Compose makes local development a breeze. It orchestrates multiple containers (our Go app and MongoDB) with proper networking, health checks, and dependencies: all defined in one file.</p><p>Here’s the complete docker-compose.yaml:</p><pre>services:<br>  app:<br>    image: ifeolaitan/muchtodo:v1<br>    container_name: muchtodo-app<br>    restart: unless-stopped<br>    ports:<br>      - &quot;8080:8080&quot;<br>    volumes:<br>      - ./.env:/app/.env:ro<br>    depends_on:<br>      mongodb:<br>        condition: service_healthy<br>    networks:<br>      - backend<br><br>  mongodb:<br>    image: mongo:8.0<br>    container_name: mongodb<br>    restart: unless-stopped<br>    ports:<br>      - &quot;27017:27017&quot;<br>    env_file:<br>      - .env<br>    environment:<br>      MONGO_INITDB_ROOT_USERNAME: ${MONGO_USERNAME}<br>      MONGO_INITDB_ROOT_PASSWORD: ${MONGO_PASSWORD}<br>      MONGO_INITDB_DATABASE: ${DB_NAME}<br>    volumes:<br>      - mongo_data:/data/db<br>      - mongo_config:/data/configdb<br>    healthcheck:<br>      test: mongosh --port 27017 -u ${MONGO_USERNAME} -p ${MONGO_PASSWORD} --authenticationDatabase admin --eval &quot;db.adminCommand(&#39;ping&#39;)&quot; --quiet<br>      interval: 10s<br>      timeout: 10s<br>      retries: 5<br>      start_period: 40s<br>    networks:<br>        - backend<br><br>volumes:<br>  mongo_data:<br>  mongo_config:<br><br>networks:<br>  backend:<br>    driver: bridge</pre><p><strong>Let’s break down the key parts:</strong></p><p><strong>The Backend Service (app)</strong></p><ul><li><strong>image</strong>: We&#39;re using a pre-built image. You&#39;d build this yourself using the Dockerfile we covered earlier.</li><li><strong>volumes: - ./.env:/app/.env:ro</strong>: This is crucial. We mount the .env file from your host machine directly into the container at /app/.env in read-only mode (:ro). This lets Viper read the configuration file without baking it into the image.</li><li><strong>depends_on.condition: service_healthy</strong>: This is smarter than basic depends_on. Docker Compose won&#39;t start the app container until MongoDB is not just <em>running</em>, but actually <em>healthy</em> (passing its health check). This prevents connection errors during startup.</li><li><strong>restart: unless-stopped</strong>: If the container crashes, Docker automatically restarts it. Manual stops are respected.</li></ul><p><strong>The MongoDB Service</strong></p><ul><li><strong>environment</strong>: These MONGO_INITDB_* variables are special. MongoDB&#39;s official Docker image runs initialization scripts that create the root user and database using these values. This only happens on first run when /data/db is empty.</li><li><strong>volumes</strong>: We persist two directories:<br>–mongo_data:/data/db: Your actual database files<br>– mongo_config:/data/configdb: MongoDB configuration and metadata<br>Named volumes like these survive docker-compose down, so your data persists between restarts.</li><li><strong>healthcheck</strong>: This is the secret sauce. We use mongosh (MongoDB shell) to ping the database with authentication. The health check:<br>– Runs every 10 seconds (interval)<br>– Times out after 10 seconds if no response (timeout)<br>– Waits 40 seconds after container start before first check (start_period), gives MongoDB time to initialise<br>– Fails after 5 consecutive failures (retries)</li></ul><p><strong>Networking</strong></p><ul><li>networks.backend: Both services connect to a custom bridge network. This gives them:<br>– DNS resolution: The app can connect to mongodb:27017 (service name becomes hostname)<br>– Isolation: Containers on this network can’t talk to containers on other networks<br>– Custom subnet: Better control than Docker’s default bridge</li></ul><h4>The .env File</h4><p>Create .env with your configuration. Docker Compose reads this file to populate ${MONGO_USERNAME} style variables, and our app reads it for configuration:</p><pre>PORT=8080<br><br># --- Connect Database ---<br># For Docker containers (app running inside Docker)<br>MONGO_URI=mongodb://root:example@mongodb:27017/<br><br># --- Database Root User Creds ---<br>MONGO_USERNAME=root<br>MONGO_PASSWORD=example<br>DB_NAME=much_todo_db<br><br># --- Authentication ---<br>JWT_SECRET_KEY=your-secret-key-change-this-in-production<br>JWT_EXPIRATION_HOURS=72<br><br># --- Logging ---<br># Log level: DEBUG, INFO, WARN, ERROR<br>LOG_LEVEL=DEBUG<br># Log format: &quot;json&quot; or &quot;text&quot;<br>LOG_FORMAT=json<br><br># --- Testing ---<br>INTEGRATION=true<br><br># --- Optional: Redis Configuration (set ENABLE_CACHE=true to enable) ---<br>ENABLE_CACHE=false<br>REDIS_ADDR=redis:6379<br>REDIS_PASSWORD=<br>REDIS_DB=0</pre><p><strong>Notice the </strong>MONGO_URI: The hostname is mongodb, not localhost. In Docker networks, services reference each other by service name.</p><h4>Running It</h4><pre># Start everything<br>docker-compose up -d<br><br># Check health<br>curl http://localhost:8080/health</pre><p><strong>Expected response:</strong> {&quot;database&quot;:&quot;ok&quot;,&quot;cache&quot;:&quot;disabled&quot;}</p><p>If you see this, congratulations! You have a working multi-container application. Now let’s make it production-ready with Kubernetes.</p><h3>Part 3: Kubernetes Fundamentals</h3><h4>Why Kubernetes?</h4><p>Docker Compose is great for development, but production needs:</p><ul><li><strong>High availability</strong>: Automatic restarts, health checks, rolling updates</li><li><strong>Scaling</strong>: Horizontal pod autoscaling</li><li><strong>Resource management</strong>: CPU/memory limits and requests</li><li><strong>Service discovery</strong>: Automatic DNS for services</li><li><strong>Secrets management</strong>: Encrypted storage for credentials</li></ul><h4>The Architecture</h4><p>Here’s what we’re building:</p><pre>Internet<br>    ↓<br>NGINX Ingress Controller (muchtodo.local)<br>    ↓<br>Backend Service (ClusterIP:8080) → Backend Pods (2 replicas)<br>    ↓                                       ↓<br>MongoDB Service (ClusterIP:27017) → MongoDB Pod<br>    ↓<br>PersistentVolume (5Gi)</pre><h4>Kubernetes Directory Structure</h4><pre>kubernetes/<br>├── namespace.yaml<br>├── backend/<br>│   ├── backend-secret.yaml<br>│   ├── backend-configmap.yaml<br>│   ├── backend-deployment.yaml<br>│   └── backend-service.yaml<br>├── mongodb/<br>│   ├── mongodb-secret.yaml<br>│   ├── mongodb-configmap.yaml<br>│   ├── mongodb-pvc.yaml<br>│   ├── mongodb-deployment.yaml<br>│   └── mongodb-service.yaml<br>├── ingress.yaml<br>└── kind-config.yaml</pre><h4>Understanding Kubernetes Resources</h4><p>Before we dive into creating resources, let’s understand the building blocks we’ll be using:</p><p><strong>Namespace:</strong> Think of Namespaces as folders that organize resources in your cluster. They provide isolation and access control, making it easy to separate different environments (dev, staging, prod) or teams. All our resources will live in the muchtodo namespace.</p><p><strong>Secret:</strong> Secrets store sensitive data like passwords, API keys, and tokens. Kubernetes keeps them separate from your configuration and base64-encodes them. Note that base64 is encoding, not encryption. For production use, rely on external secret managers such as HashiCorp Vault or AWS Secrets Manager.</p><p><strong>ConfigMap:</strong> ConfigMaps store non-sensitive configuration data such as database names, feature flags, or environment settings. They follow the same pattern as Secrets, but are intended for values that do not require confidentiality.</p><p><strong>PersistentVolumeClaim (PVC):</strong> PVCs request storage from Kubernetes. When you create a PVC asking for “5GB of disk space,” Kubernetes provisions a volume from available storage. Data on PVCs survives pod restarts and crashes, it’s persistent.</p><p><strong>Deployment:</strong> Deployments tell Kubernetes how to run your containers: which image, how many replicas, resource limits, health checks, environment variables. If a pod crashes, the Deployment automatically creates a replacement. Deployments handle rolling updates and rollbacks.</p><p><strong>Service:</strong> Services provide stable networking for pods. Pods get random IPs that change when they restart, but a Service gives them a consistent DNS name (like mongodb or backend-service) that other pods use to connect. Services also load-balance traffic across multiple pod replicas.</p><p><strong>Ingress:</strong> Ingress routes external HTTP/HTTPS traffic to Services inside the cluster. It’s like a reverse proxy or load balancer at the edge of your cluster, mapping hostnames and paths to backend Services.</p><p>Now let’s put these pieces together.</p><h3>Part 3.5: Setting Up Your Cluster and Namespace</h3><p>Before deploying any resources, you need a Kubernetes cluster and a namespace to organize your application.</p><h4>KIND Configuration (For Local Testing)</h4><p><strong>If you’re using KIND for local testing</strong>, you need to create your cluster with this configuration <strong>BEFORE</strong> deploying any resources. <strong>KIND (Kubernetes IN Docker)</strong> runs a Kubernetes cluster inside Docker containers on your local machine. It’s perfect for testing Kubernetes manifests without needing a cloud provider. However, since the cluster runs inside Docker, we need to expose ports from the cluster to your host machine so you can access the Ingress controller.</p><p>If you’re deploying to a cloud provider (EKS, GKE, AKS) or Minikube, you can skip the KIND cluster creation and just create the namespace.</p><p>kubernetes/kind-config.yaml:</p><pre>apiVersion: kind.x-k8s.io/v1alpha4<br>kind: Cluster<br>nodes:<br>  - role: control-plane<br>    kubeadmConfigPatches:<br>      - |<br>        kind: InitConfiguration<br>        nodeRegistration:<br>          kubeletExtraArgs:<br>            node-labels: &quot;ingress-ready=true&quot;<br>    extraPortMappings:<br>      - containerPort: 80<br>        hostPort: 80<br>        protocol: TCP<br>      - containerPort: 443<br>        hostPort: 443<br>        protocol: TCP</pre><p><strong>What this config does:</strong></p><ul><li>node-labels: &quot;ingress-ready=true&quot;: Labels the control-plane node so the NGINX Ingress controller knows where to run</li><li>extraPortMappings: Maps ports 80 and 443 from inside the KIND cluster to your host machine, allowing you to access http://muchtodo.local from your browser</li></ul><h4>Creating the Namespace</h4><p>We’re creating a muchtodo namespace to keep all our application resources (MongoDB, backend, Ingress) grouped together and separate from other applications.</p><p>kubernetes/namespace.yaml:</p><pre>apiVersion: v1<br>kind: Namespace<br>metadata:<br>  name: muchtodo<br>  labels:<br>    app: muchtodo</pre><p><strong>Create the cluster and namespace:</strong></p><pre># If using KIND (local testing)<br>kind create cluster --name muchtodo-app --config kubernetes/kind-config.yaml<br><br># Create the namespace<br>kubectl apply -f kubernetes/namespace.yaml</pre><p>Now your cluster and namespace are ready for deploying resources.</p><h3>Part 4: MongoDB in Kubernetes (The Hard Part)</h3><h4>Why MongoDB can be Tricky</h4><p>MongoDB in Kubernetes is harder than most databases because:</p><ol><li>It needs persistent storage (StatefulSet or PVC)</li><li>Authentication must be set up correctly</li><li>The official image has specific initialization expectations</li><li>Replica sets add massive complexity (we’re skipping them for now)</li></ol><h4>The MongoDB Secret</h4><p>kubernetes/mongodb/mongodb-secret.yaml:</p><pre>apiVersion: v1<br>kind: Secret<br>metadata:<br>  namespace: muchtodo<br>  name: mongodb-secret<br>  labels:<br>    app: mongodb<br>type: Opaque<br>data:<br>  MONGO_INITDB_ROOT_USERNAME: cm9vdA==    # root<br>  MONGO_INITDB_ROOT_PASSWORD: ZXhhbXBsZQ==  # example</pre><p><strong>How this works: </strong>These credentials will be injected as environment variables into the MongoDB container. The MongoDB Docker image looks for MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD on first startup to create the root user. Values must be base64-encoded when using the data field (or use stringData for plain text that Kubernetes will encode automatically).</p><p>Create base64 values with:</p><pre>echo -n &quot;root&quot; | base64<br>echo -n &quot;example&quot; | base64</pre><p><strong>Note: </strong>This isn’t encryption, just encoding (use external secret managers for production).</p><h4>The MongoDB ConfigMap</h4><p>kubernetes/mongodb/mongodb-configmap.yaml:</p><pre>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  namespace: muchtodo<br>  name: mongodb-config<br>  labels:<br>    app: mongodb<br>data:<br>  MONGO_INITDB_DATABASE: &quot;much_todo_db&quot;</pre><p><strong>How this works: </strong>This ConfigMap holds the non-sensitive database name. When the MongoDB Deployment references this ConfigMap with envFrom, the MONGO_INITDB_DATABASE value becomes an environment variable in the MongoDB container. Combined with the credentials from the Secret, MongoDB&#39;s initialization scripts will create the much_todo_db database on first startup.</p><h4>The MongoDB Persistent Volume Claim</h4><p>kubernetes/mongodb/mongodb-pvc.yaml:</p><pre>apiVersion: v1<br>kind: PersistentVolumeClaim<br>metadata:<br>  name: mongodb-pvc<br>  namespace: muchtodo<br>  labels:<br>    app: mongodb<br>spec:<br>  accessModes: [&quot;ReadWriteOnce&quot;]<br>  resources:<br>    requests:<br>      storage: 5Gi<br>  storageClassName: standard</pre><p><strong>How this works: </strong>When you apply this PVC, Kubernetes provisions a 5GB volume from available storage. ReadWriteOnce means the volume can be mounted by a single node for reading and writing. The MongoDB Deployment will mount this PVC at /data/db (where MongoDB stores its data files). Even if the MongoDB pod crashes or gets rescheduled to a different node, the data persists because it&#39;s stored on the volume, not in the pod.</p><h4>The MongoDB Deployment</h4><p>kubernetes/mongodb/mongodb-deployment.yaml:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  namespace: muchtodo<br>  name: mongodb-deployment<br>  labels:<br>    app: mongodb<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: mongodb<br>  template:<br>    metadata:<br>      labels:<br>        app: mongodb<br>    spec:<br>      containers:<br>        - name: mongodb<br>          image: mongo:8.0<br>          resources:<br>            requests:<br>              memory: &quot;256Mi&quot;<br>              cpu: &quot;250m&quot;<br>            limits:<br>              memory: &quot;512Mi&quot;<br>              cpu: &quot;500m&quot;<br>          envFrom:<br>            - secretRef:<br>                name: mongodb-secret<br>            - configMapRef:<br>                name: mongodb-config<br>          ports:<br>            - containerPort: 27017<br>          livenessProbe:<br>            exec:<br>              command:<br>                - mongosh<br>                - --eval<br>                - &quot;db.adminCommand(&#39;ping&#39;)&quot;<br>            initialDelaySeconds: 40<br>            periodSeconds: 10<br>            timeoutSeconds: 10<br>            failureThreshold: 3<br>          readinessProbe:<br>            exec:<br>              command:<br>                - mongosh<br>                - --eval<br>                - &quot;db.adminCommand(&#39;ping&#39;)&quot;<br>            initialDelaySeconds: 10<br>            periodSeconds: 10<br>            timeoutSeconds: 5<br>            failureThreshold: 3<br>          volumeMounts:<br>            - name: mongodb-configdb<br>              mountPath: /data/configdb<br>            - name: mongodb-data<br>              mountPath: /data/db<br>      volumes:<br>        - name: mongodb-data<br>          persistentVolumeClaim:<br>            claimName: mongodb-pvc<br>        - name: mongodb-configdb<br>          emptyDir: {}</pre><p><strong>How this Deployment works:</strong></p><p>This Deployment tells Kubernetes how to run and manage your MongoDB container. Here’s what each part does:</p><ul><li>namespace: muchtodo: Places this MongoDB deployment in the muchtodo namespace we created earlier. All our app resources live in this namespace.</li><li>replicas: 1: Runs exactly 1 MongoDB pod. Kubernetes constantly monitors this, if the pod crashes or gets deleted, Kubernetes immediately creates a new one to maintain the count.</li><li>image: mongo:8.0: The official MongoDB 8.0 Docker image from Docker Hub. Kubernetes pulls this image and runs it in a container.</li><li>resources: Sets CPU and memory limits. requests (256Mi RAM, 250m CPU) is the guaranteed minimum Kubernetes reserves for this pod. limits (512Mi RAM, 500m CPU) is the maximum the pod can use. If MongoDB tries to use more memory than the limit, Kubernetes kills and restarts the pod.</li><li>containerPort: 27017: MongoDB listens on port 27017 inside the pod. This doesn&#39;t expose it externally, that&#39;s what the Service does.</li><li>envFrom: Automatically injects all key-value pairs from the Secret (credentials) and ConfigMap (database name) as environment variables. MongoDB&#39;s Docker image reads MONGO_INITDB_ROOT_USERNAME, MONGO_INITDB_ROOT_PASSWORD, and MONGO_INITDB_DATABASE on first startup to initialize authentication and create the database.</li><li>volumeMounts: Connects storage to the container at specific paths:<br>–/data/db is where MongoDB stores database files. This is mounted from the PVC we created, so data persists even if the pod is deleted.<br>–/data/configdb stores MongoDB config metadata. This uses emptyDir, temporary storage that&#39;s lost when the pod restarts (that&#39;s fine, MongoDB recreates it).</li><li>livenessProbe: Kubernetes runs this check every 10 seconds to see if MongoDB is still alive. It executes mongosh inside the container to ping the database. If this fails 3 times in a row, Kubernetes assumes the container is frozen or broken and restarts it. The initialDelaySeconds: 40 gives MongoDB 40 seconds to start up before the first check.</li><li>readinessProbe: Similar to liveness, but this determines if MongoDB is ready to accept traffic. Kubernetes won&#39;t send requests to this pod until the readiness probe passes. If it starts failing, Kubernetes stops routing traffic to the pod but doesn&#39;t restart it (maybe it&#39;s just temporarily overloaded).</li><li>volumes: Defines storage volumes that containers can mount. The mongodb-data volume references our PVC (mongodb-pvc), which provides persistent 5GB storage that survives pod restarts.</li></ul><p>This Deployment ensures MongoDB stays running 24/7. If the pod crashes, Kubernetes recreates it. If the pod is accidentally deleted, Kubernetes creates a replacement. If the pod becomes unhealthy, Kubernetes restarts it. And because we’re using a PVC for /data/db, all your database data survives these restarts.</p><h4>The MongoDB Service</h4><p>kubernetes/mongodb/mongodb-service.yaml:</p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  namespace: muchtodo<br>  name: mongodb<br>  labels:<br>    app: mongodb<br>spec:<br>  type: ClusterIP<br>  selector:<br>    app: mongodb<br>  ports:<br>    - port: 27017<br>      targetPort: 27017</pre><p><strong>How this Service works: </strong>This Service finds the MongoDB pod using selector: app=mongodb and gives it a stable DNS name. Backend pods can connect to mongodb:27017 even if the pod restarts and gets a new IP. The ClusterIP type keeps it internal only, so external traffic can&#39;t reach the database directly.</p><h4><strong>What we’ve built so far:</strong></h4><p>At this point, you have a fully functional MongoDB instance running in Kubernetes:</p><ul><li><strong>Secrets</strong> storing database credentials (username and password)</li><li><strong>ConfigMap</strong> holding database configuration (database name)</li><li><strong>PersistentVolumeClaim</strong> requesting 5GB of storage that survives pod restarts</li><li><strong>Deployment</strong> running the MongoDB container with health checks, environment variables, and persistent storage mounted</li><li><strong>Service</strong> providing a stable DNS name (mongodb) that other pods can use to connect</li></ul><p>MongoDB is now running, storing data persistently, and ready to accept connections from other pods in the cluster. The health probes ensure it’s actually working before Kubernetes marks it as ready.</p><p>But here’s the thing: <strong>you still don’t have an application using this database</strong>. MongoDB is sitting there waiting for connections, but the backend API hasn’t been deployed yet. That’s what we’ll tackle next.</p><h3>Part 5: Backend Deployment (The Configuration Challenge)</h3><p>We’ll use the same Kubernetes resources we just covered for MongoDB (Secrets, ConfigMaps, Deployments, Services), but the backend has a unique twist that requires a creative solution.</p><h4>The Problem</h4><p>Our Go app uses <strong>Viper</strong>, which reads configuration from a .env file with viper.ReadInConfig(). But Kubernetes loves environment variables, not files.</p><p><strong>Bad solution:</strong> Manually copy every env var into the deployment.</p><p><strong>Good solution:</strong> Mount the entire .env file as a Secret.</p><h4>The Backend Secret (with .env file)</h4><p>This is different from MongoDB’s Secret. Instead of storing individual key-value pairs (like MONGO_USERNAME: root), we&#39;re storing an entire .env file as a single entry in the Secret. The key is literally .env and the value is the whole file content. Later, we&#39;ll mount this Secret as a file in the container so Viper can read it just like it does in Docker Compose.</p><p>kubernetes/backend/backend-secret.yaml:</p><pre>apiVersion: v1<br>kind: Secret<br>metadata:<br>  namespace: muchtodo<br>  name: backend-secret<br>  labels:<br>    app: backend<br>type: Opaque<br>stringData:<br>  .env: |<br>    PORT=8080<br>    LOG_LEVEL=DEBUG<br>    LOG_FORMAT=json<br>    JWT_EXPIRATION_HOURS=72<br>    DB_NAME=much_todo_db<br>    MONGO_URI=mongodb://root:example@mongodb:27017/<br>    JWT_SECRET_KEY=0d50ZsFhdwq93BdakyDn137udKAgnlIdzY3t40BxHni</pre><p><strong>How this works: </strong>Instead of individual environment variables, this Secret stores the entire .env file as one block using stringData. When the Deployment mounts it with subPath: .env, it creates the file at /app/.env where Viper can read it. This keeps your sensitive config (JWT secrets, database credentials) out of Git while working with the app&#39;s existing code without modifications.</p><h4>The Backend ConfigMap</h4><p>kubernetes/backend/backend-configmap.yaml:</p><pre>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  namespace: muchtodo<br>  name: backend-config<br>  labels:<br>    app: backend<br>data:<br>  PORT: &quot;8080&quot;<br>  LOG_LEVEL: &quot;DEBUG&quot;<br>  LOG_FORMAT: &quot;json&quot;<br>  JWT_EXPIRATION_HOURS: &quot;72&quot;<br>  DB_NAME: &quot;much_todo_db&quot;</pre><p><strong>How this works: </strong>This ConfigMap stores non-sensitive configuration values. In this setup, these values are already included in the backend Secret’s .env file, so the ConfigMap isn&#39;t currently being injected into the pods. However, it exists as an alternative approach where you could separate non-sensitive config (like port and log settings) from sensitive data (like JWT secrets). You could inject it using envFrom if you wanted to remove these values from the Secret.</p><h4>The Backend Deployment</h4><p>kubernetes/backend/backend-deployment.yaml:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  namespace: muchtodo<br>  name: backend-deployment<br>  labels:<br>    app: backend<br>spec:<br>  replicas: 2<br>  selector:<br>    matchLabels:<br>      app: backend<br>  template:<br>    metadata:<br>      labels:<br>        app: backend<br>    spec:<br>      containers:<br>        - name: backend<br>          image: ifeolaitan/muchtodo:v1<br>          imagePullPolicy: Always<br>          resources:<br>            requests:<br>              memory: &quot;64Mi&quot;<br>              cpu: &quot;250m&quot;<br>            limits:<br>              memory: &quot;128Mi&quot;<br>              cpu: &quot;500m&quot;<br>          volumeMounts:<br>            - name: env-file<br>              mountPath: /app/.env<br>              subPath: .env<br>          ports:<br>            - containerPort: 8080<br>          livenessProbe:<br>            httpGet:<br>              path: /health<br>              port: 8080<br>            initialDelaySeconds: 30<br>            periodSeconds: 30<br>            timeoutSeconds: 5<br>            failureThreshold: 3<br>          readinessProbe:<br>            httpGet:<br>              path: /health<br>              port: 8080<br>            initialDelaySeconds: 10<br>            periodSeconds: 5<br>            timeoutSeconds: 3<br>            failureThreshold: 3<br>      volumes:<br>        - name: env-file<br>          secret:<br>            secretName: backend-secret</pre><p><strong>How this Deployment works:</strong></p><p>This Deployment manages your Go backend API. Here’s the full breakdown:</p><ul><li>namespace: muchtodo: Deploys in the muchtodo namespace alongside MongoDB and other app resources.</li><li>replicas: 2: Runs 2 identical backend pods simultaneously. This provides high availability, if one pod crashes, the other keeps handling requests. The Service automatically load-balances traffic between them. With 2 replicas, you can handle more traffic and have zero downtime during rolling updates.</li><li>image: ifeolaitan/muchtodo:v2: The Docker image containing your compiled Go application. Kubernetes pulls this from Docker Hub and runs it. In production, you&#39;d use your own registry (ECR, GCR, or private registry).</li><li>containerPort: 8080: Your Go app listens on port 8080 inside the pod. This doesn&#39;t make it externally accessible, the Service and Ingress handle that.</li><li>volumeMounts.subPath: .env: This is the clever part. Instead of mounting the entire Secret as a directory (which would create /app/backend-secret/.env), subPath mounts just the .env key from the Secret directly as a file at /app/.env. This makes it look exactly like your local setup, so Viper&#39;s ReadInConfig() works without code changes.</li><li>volumes: Defines the Secret volume named env-file that references backend-secret. The container mounts this volume to get access to the .env file content.</li><li>livenessProbe: Kubernetes checks http://backend:8080/health every 10 seconds. If it fails 3 times (30 seconds of failures), Kubernetes kills and restarts the pod. This catches frozen or deadlocked containers. The initialDelaySeconds: 30 gives the Go app 30 seconds to start up and become ready before the first check.</li><li>readinessProbe: Also checks /health but serves a different purpose. If this fails, Kubernetes removes the pod from the Service&#39;s load balancer rotation, it stops sending traffic to this pod but doesn&#39;t restart it. This is perfect for temporary overload situations. Once the probe succeeds again, Kubernetes adds the pod back to rotation.</li><li>resources.requests: Tells Kubernetes &quot;reserve 64Mi RAM and 250m CPU (0.25 cores) for this pod.&quot; Kubernetes won&#39;t schedule the pod on a node that doesn&#39;t have these resources available. This is your guaranteed minimum.</li><li>resources.limits: The maximum resources this pod can use (128Mi RAM, 500m CPU). If your Go app tries to allocate more than 128Mi of memory, Kubernetes kills the pod and restarts it. CPU limits throttle the pod instead of killing it. Setting limits prevents one misbehaving pod from starving other pods on the same node.</li></ul><p>With 2 replicas, if one pod crashes, the other instantly takes over — users see no downtime. The health probes ensure Kubernetes only routes traffic to healthy pods. Resource limits prevent runaway memory leaks from affecting other applications. The .env file mounting strategy means your Go code works identically in Kubernetes and Docker Compose. It&#39;s a production-ready setup with automatic recovery, load balancing, and fault tolerance built in</p><h4>The Backend Service</h4><p>kubernetes/backend/backend-service.yaml:</p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  namespace: muchtodo<br>  name: backend-service<br>  labels:<br>    app: backend<br>spec:<br>  type: ClusterIP<br>  selector:<br>    app: backend<br>  ports:<br>    - port: 8080<br>      targetPort: 8080</pre><p><strong>How this Service works: </strong>The Service uses selector: app=backend to find all pods with that label (our 2 backend replicas). When traffic comes in on port 8080, Kubernetes automatically load-balances it across both pods. The Ingress will route to this Service, and the Service distributes requests to healthy backend pods. Since it&#39;s ClusterIP, only internal cluster traffic can reach it, external access must go through the Ingress.</p><h4><strong>What we’ve built so far:</strong></h4><p>At this point, you have MongoDB and the backend running inside your Kubernetes cluster. MongoDB is storing data persistently, the backend pods can connect to it using the mongodb Service name, and health checks ensure everything stays healthy.</p><p>But there’s one problem: <strong>you still can’t access your API from outside the cluster</strong>. Both Services are ClusterIP, which means they’re only reachable from inside Kubernetes. Your browser can’t hit http://localhost:8080 like it did with Docker Compose.</p><p>That’s where Ingress comes in.</p><h3>Part 6: Making It Accessible (Ingress)</h3><p>Now that your cluster, namespace, MongoDB, and backend are set up, you need a way for external traffic to reach your API.</p><h4>The Ingress Resource</h4><p>Without Ingress, you’d need to expose every Service with a LoadBalancer (expensive in cloud) or NodePort (messy port management).</p><p>kubernetes/ingress.yaml:</p><pre>apiVersion: networking.k8s.io/v1<br>kind: Ingress<br>metadata:<br>  name: muchtodo-ingress<br>  namespace: muchtodo<br>  labels:<br>    app: muchtodo<br>  annotations:<br>    nginx.ingress.kubernetes.io/rewrite-target: /<br>spec:<br>  ingressClassName: nginx<br>  rules:<br>    - host: muchtodo.local<br>      http:<br>        paths:<br>          - path: /<br>            pathType: Prefix<br>            backend:<br>              service:<br>                name: backend-service<br>                port:<br>                  number: 8080</pre><p><strong>Breaking down this configuration:</strong></p><ul><li>ingressClassName: nginx: Tells Kubernetes to use the NGINX Ingress Controller to handle this Ingress resource</li><li>host: muchtodo.local: Routes requests for muchtodo.local to this backend (you can have multiple hosts in one Ingress)</li><li>path: /: Matches all paths starting from root (/, /api, /health, etc.)</li><li>pathType: Prefix: Matches the path as a prefix (alternative is Exact for exact matches only)</li><li>backend.service.name: backend-service: Routes traffic to the backend-service Service we created in Part 5</li><li>backend.service.port.number: 8080: Connects to port 8080 on the Service</li></ul><h4>Installing NGINX Ingress Controller</h4><p>An Ingress resource by itself does nothing, it’s just a configuration. You need an <strong>Ingress Controller</strong> to actually read that configuration and route traffic. Think of it like having a routing table (Ingress) but needing a router (Ingress Controller) to do the actual work.</p><p>NGINX Ingress Controller is one of the most popular choices. It runs as a set of pods in your cluster, listens for Ingress resources, and automatically configures itself to route traffic accordingly.</p><pre>kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/main/deploy/static/provider/kind/deploy.yaml<br><br># Wait for it to be ready<br>kubectl wait --namespace ingress-nginx \<br>  --for=condition=ready pod \<br>  --selector=app.kubernetes.io/component=controller \<br>  --timeout=120s</pre><p>This installs the NGINX Ingress Controller in the ingress-nginx namespace. Once it&#39;s running, it watches for Ingress resources across all namespaces and automatically configures routing rules.</p><h4>Add to /etc/hosts</h4><p>Your computer doesn’t know what muchtodo.local is, it&#39;s not a real domain on the internet. The /etc/hosts file is like a local DNS override that maps hostnames to IP addresses on your machine.</p><pre>echo &quot;127.0.0.1 muchtodo.local&quot; | sudo tee -a /etc/hosts</pre><p><strong>What this does:</strong></p><ul><li>Maps muchtodo.local to 127.0.0.1 (localhost)</li><li>When you visit http://muchtodo.local in your browser, your computer sends the request to 127.0.0.1</li><li>KIND’s port mappings (from the kind-config) forward port 80 from your host to the cluster</li><li>The NGINX Ingress Controller receives the request and routes it to backend-service based on the Ingress rules</li></ul><p><strong>For cloud deployments:</strong> You’d replace muchtodo.local with a real domain (like api.yourapp.com) and point it to your cluster&#39;s LoadBalancer IP instead.</p><h4><strong>The full picture:</strong></h4><p>At this point, you have a <strong>complete, working Kubernetes deployment</strong>:</p><ul><li>MongoDB running with persistent storage in the muchtodo namespace</li><li>Backend pods (2 replicas) connected to MongoDB</li><li>All resources organized in a dedicated namespace</li><li>NGINX Ingress Controller routing external traffic from http://muchtodo.local to your backend Service</li><li>Complete networking: Internet → Ingress Controller → Backend Service → Backend Pods → MongoDB Service → MongoDB Pod</li></ul><p>You can now access your API from your browser or any HTTP client using http://muchtodo.local/health, http://muchtodo.local/api/users, etc.—just like you did with Docker Compose, but now it&#39;s running in Kubernetes with all the benefits of orchestration, health checks, scaling capabilities, and production-ready patterns.</p><p>The only problem? You just ran a lot of kubectl apply commands manually. Let&#39;s fix that.</p><h3>Part 7: Deployment Automation</h3><p>Typing kubectl commands repeatedly gets old fast. Let’s automate the entire deployment process with shell scripts.</p><p>Create a scripts/ directory with four automation scripts:</p><ol><li>docker-build.sh: Builds your Docker image</li><li>docker-run.sh: Starts Docker Compose with validation</li><li>k8s-deploy.sh: Deploys everything to Kubernetes</li><li>k8s-cleanup.sh: Tears down Kubernetes resources</li></ol><p><strong>Note:</strong> All four scripts are available in the <a href="https://github.com/Ife-Olaitan/container-assessment/tree/main/scripts">project repository</a> at scripts/. We&#39;ll focus on the Kubernetes deployment script here since that&#39;s the core of our automation, but you can find the Docker build, Docker run, and cleanup scripts in the <a href="https://github.com/Ife-Olaitan/container-assessment/tree/main/scripts">repo</a>.</p><h4>The Key Script: k8s-deploy.sh</h4><p>Here’s the main deployment script that orchestrates the entire Kubernetes deployment:</p><pre>#!/bin/bash<br><br># Script to deploy to Kubernetes<br><br>set -e<br><br>echo &quot;Deploying MuchToDo to Kubernetes...&quot;<br><br># Apply namespace<br>echo &quot;Creating namespace...&quot;<br>kubectl apply -f kubernetes/namespace.yaml<br><br># Deploy MongoDB<br>echo &quot;Deploying MongoDB...&quot;<br>kubectl apply -f kubernetes/mongodb/mongodb-secret.yaml<br>kubectl apply -f kubernetes/mongodb/mongodb-configmap.yaml<br>kubectl apply -f kubernetes/mongodb/mongodb-pvc.yaml<br>kubectl apply -f kubernetes/mongodb/mongodb-deployment.yaml<br>kubectl apply -f kubernetes/mongodb/mongodb-service.yaml<br><br># Wait for MongoDB to be ready<br>echo &quot;Waiting for MongoDB to be ready...&quot;<br>kubectl wait --for=condition=ready pod -l app=mongodb -n muchtodo --timeout=120s<br><br># Deploy Backend<br>echo &quot;Deploying Backend...&quot;<br>kubectl apply -f kubernetes/backend/backend-secret.yaml<br>kubectl apply -f kubernetes/backend/backend-configmap.yaml<br>kubectl apply -f kubernetes/backend/backend-deployment.yaml<br>kubectl apply -f kubernetes/backend/backend-service.yaml<br><br># Wait for Backend to be ready<br>echo &quot;Waiting for Backend to be ready...&quot;<br>kubectl wait --for=condition=ready pod -l app=backend -n muchtodo --timeout=120s<br><br># Check if Ingress Controller is installed<br>if kubectl get namespace ingress-nginx &amp;&gt; /dev/null; then<br>    echo &quot;Ingress controller already installed&quot;<br>else<br>    echo &quot;Installing NGINX Ingress Controller...&quot;<br>    kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/main/deploy/static/provider/kind/deploy.yaml<br>    echo &quot;Waiting for Ingress Controller to be ready...&quot;<br>    sleep 30<br>    kubectl wait --namespace ingress-nginx \<br>      --for=condition=ready pod \<br>      --selector=app.kubernetes.io/component=controller \<br>      --timeout=120s<br>fi<br><br># Deploy Ingress<br>echo &quot;Deploying Ingress...&quot;<br>kubectl apply -f kubernetes/ingress.yaml<br><br># Display deployment status<br>echo &quot;&quot;<br>echo &quot;Deployment complete!&quot;<br>echo &quot;&quot;<br>echo &quot;=== Pod Status ===&quot;<br>kubectl get pods -n muchtodo<br><br>echo &quot;&quot;<br>echo &quot;=== Service Status ===&quot;<br>kubectl get svc -n muchtodo<br><br>echo &quot;&quot;<br>echo &quot;=== Ingress Status ===&quot;<br>kubectl get ingress -n muchtodo<br><br>echo &quot;&quot;<br>echo &quot;Access the API:&quot;<br>echo &quot;&quot;<br>echo &quot;Option 1: Via Ingress (if KIND cluster has port mappings)&quot;<br>echo &quot;  1. Add to /etc/hosts: echo &#39;127.0.0.1 muchtodo.local&#39; | sudo tee -a /etc/hosts&quot;<br>echo &quot;  2. Access API: curl http://muchtodo.local&quot;<br>echo &quot;     Health check: curl http://muchtodo.local/health&quot;<br>echo &quot;&quot;<br>echo &quot;Option 2: Via Port-forward to Ingress&quot;<br>echo &quot;  kubectl port-forward -n ingress-nginx svc/ingress-nginx-controller 8080:80&quot;<br>echo &quot;  curl http://localhost:8080 -H &#39;Host: muchtodo.local&#39;&quot;<br>echo &quot;&quot;<br>echo &quot;Option 3: Direct to Backend (bypass Ingress)&quot;<br>echo &quot;  kubectl port-forward -n muchtodo svc/backend-service 8080:8080&quot;<br>echo &quot;  curl http://localhost:8080&quot;</pre><p><strong>What it does:</strong></p><ul><li>Deploys in the correct order (namespace → MongoDB → backend → ingress)</li><li>Waits for MongoDB to be healthy before deploying the backend</li><li>Checks if Ingress controller exists before installing</li><li>Uses kubectl wait to ensure pods are ready (not just running)</li></ul><p><strong>Make Scripts Executable</strong></p><pre>chmod +x scripts/*.sh</pre><p><strong>Usage:</strong></p><pre># Docker Compose<br>./scripts/docker-run.sh<br><br># Kubernetes<br>./scripts/k8s-deploy.sh<br><br># Clean up<br>./scripts/k8s-cleanup.sh</pre><p><strong>What automation gives you:</strong></p><p>You now have repeatable, reliable deployment scripts that handle the entire workflow:</p><ul><li><strong>No more manual kubectl commands</strong> — One script deploys everything in the correct order</li><li><strong>Built-in error handling</strong> — The set -e flag stops execution if any command fails</li><li><strong>Smart waiting</strong> — Scripts use kubectl wait to ensure pods are actually ready, not just created</li><li><strong>Conditional logic</strong> — Checks if resources already exist before creating them (like the Ingress controller)</li><li><strong>Clean teardown</strong> — The cleanup script removes everything systematically</li></ul><p>Instead of running 10+ kubectl commands manually and hoping you didn’t miss anything, you run one script and get consistent, predictable deployments every time. This is the foundation for CI/CD pipelines, automation that works locally works in production too.</p><p>Now let’s see the complete end-to-end workflow in action.</p><h3>Part 8: The Complete Workflow</h3><p>Now that you understand all the pieces, let’s see how they fit together in real development and deployment workflows. This section shows the complete end-to-end process for both Docker Compose (local development) and Kubernetes (deployment).</p><h4>Local Development with Docker Compose</h4><p><strong>When to use this:</strong> Daily development, testing new features, debugging locally, quick iterations.</p><p><strong>Why it’s fast:</strong> Docker Compose starts everything with one command, no cluster setup needed, instant feedback loop.</p><pre># 1. Set up environment<br>cp .env.example .env<br># Edit .env with your values<br><br># 2. Run the stack<br>./scripts/docker-run.sh<br><br># 3. Test it<br>curl http://localhost:8080/health<br><br># 4. Clean up<br>docker-compose down</pre><p><strong>What happens:</strong></p><ol><li>Docker Compose pulls images (if needed)</li><li>Creates the backend network</li><li>Starts MongoDB with health checks</li><li>Waits for MongoDB to be healthy (this is key!)</li><li>Starts the backend container</li><li>Mounts your .env file into the container</li><li>Everything is accessible at localhost:8080</li></ol><p><strong>Expected output from the health check:</strong></p><pre>{&quot;database&quot;:&quot;ok&quot;,&quot;cache&quot;:&quot;disabled&quot;}</pre><p>If you see this, your entire stack is working. MongoDB is connected, the backend is responding, and you’re ready to develop.</p><h4>Kubernetes Deployment</h4><p><strong>When to use this:</strong> Testing production configurations, validating Kubernetes manifests, learning Kubernetes patterns, preparing for cloud deployments.</p><p><strong>Why it’s different:</strong> Kubernetes deployment simulates production, health checks, resource limits, persistent storage, service discovery, and Ingress routing all work exactly like they would in EKS/GKE/AKS.</p><pre># 1. Create KIND cluster<br>kind create cluster --name muchtodo-app --config kubernetes/kind-config.yaml<br><br># 2. Deploy everything<br>./scripts/k8s-deploy.sh<br><br># 3. Add to hosts file<br>echo &quot;127.0.0.1 muchtodo.local&quot; | sudo tee -a /etc/hosts<br><br># 4. Test it<br>curl http://muchtodo.local/health<br><br># 5. Clean up when done<br>./scripts/k8s-cleanup.sh<br>kind delete cluster --name muchtodo-app</pre><p><strong>What happens:</strong></p><ol><li>KIND creates a Kubernetes cluster inside Docker (takes ~30 seconds)</li><li>Port 80 and 443 are mapped from the cluster to your host machine</li><li>The deploy script runs through:<br>– Creates the muchtodo namespace<br>– Deploys MongoDB (Secret, ConfigMap, PVC, Deployment, Service)<br>– Waits for MongoDB to be ready (pod health checks pass)<br>– Deploys Backend (Secret, ConfigMap, Deployment, Service)<br>– Waits for Backend to be ready<br>– Installs NGINX Ingress Controller (if not already present)<br>– Creates the Ingress resource</li><li>Your app is now accessible at <a href="http://muchtodo.local/">http://muchtodo.local</a></li></ol><p><strong>Expected output from the health check:</strong></p><pre>{&quot;database&quot;:&quot;ok&quot;,&quot;cache&quot;:&quot;disabled&quot;}</pre><p>Same response as Docker Compose, but now it’s going through:</p><ul><li>Your browser → muchtodo.local</li><li>/etc/hosts maps this to 127.0.0.1</li><li>KIND’s port mapping forwards to the cluster</li><li>NGINX Ingress Controller routes to backend-service</li><li>backend-service routes to one of 2 backend pods</li><li>Backend pod connects to mongodb Service</li><li>mongodb Service routes to MongoDB pod</li></ul><p><strong>Key differences from Docker Compose:</strong></p><ul><li><strong>Setup time:</strong> KIND cluster creation adds ~30 seconds upfront</li><li><strong>Access URL:</strong> http://muchtodo.local instead of localhost:8080</li><li><strong>Health checks:</strong> Kubernetes probes vs Docker healthchecks (more sophisticated)</li><li><strong>Scaling:</strong> replicas: 2 for the backend (can&#39;t do this in Docker Compose without extra tools)</li><li><strong>Resource limits:</strong> CPU/memory constraints enforced</li><li><strong>Persistent storage:</strong> PVC instead of Docker volumes</li></ul><h3>Part 10: What I Learned (So You Don’t Have To)</h3><h4>Mistake #1: Trying to Use MongoDB Replica Sets</h4><p>Initially, I tried setting up MongoDB with replica sets because “that’s what production uses.” Big mistake for a learning project.</p><p><strong>The problem:</strong> Replica sets require:</p><ul><li>KeyFile authentication between nodes</li><li>Complex initialization scripts</li><li>StatefulSets instead of Deployments</li><li>Headless services</li><li>More storage and resources</li></ul><p><strong>The lesson:</strong> Start simple. Standalone MongoDB is fine for development and learning. Add complexity when you need it, not before.</p><h4>Mistake #2: Assuming Environment Variables Would Just Work</h4><p>The Go app uses Viper’s viper.ReadInConfig() to read .env files. I assumed setting environment variables in Kubernetes would work the same way.</p><p><strong>The problem:</strong> Viper doesn’t automatically read environment variables unless you call AutomaticEnv() or BindEnv() for each variable.</p><p><strong>The solution:</strong> Mount the .env file as a Secret volume. This works with the existing code without modifications.</p><h4>Mistake #3: Using command: Instead of args: for MongoDB</h4><p>MongoDB’s Docker image has an ENTRYPOINT that runs initialization scripts (creating the root user, setting up auth). When I used command: in the Deployment, it bypassed the entrypoint entirely.</p><p><strong>The problem:</strong> No root user was created, auth failed.</p><p><strong>The solution:</strong> Use args: to pass additional arguments to mongod while keeping the entrypoint intact.</p><h4>Mistake #4: Not Using Health Checks</h4><p>Without proper livenessProbe and readinessProbe, Kubernetes routes traffic to pods before they’re ready, causing connection errors.</p><p><strong>The lesson:</strong> Always configure health probes. They’re not optional.</p><h4>Mistake #5: Forgetting Resource Limits</h4><p>Without resource requests/limits, one misbehaving pod can starve others on the same node.</p><p><strong>The lesson:</strong> Always set resources.requests and resources.limits. Start conservative, adjust based on monitoring.</p><h3>Conclusion</h3><p><strong>You started with a Docker Compose file. You ended with a production-ready Kubernetes deployment.</strong></p><p>More importantly, you understand <em>why</em> each piece exists:</p><ul><li>Why we mount the .env file instead of using environment variables</li><li>Why we use ClusterIP for internal services</li><li>Why health probes matter</li><li>Why we separate secrets from configuration</li><li>Why resource limits prevent pod resource starvation</li></ul><p>This isn’t just about knowing the YAML syntax. It’s about understanding the patterns, the trade-offs, and the real-world problems you’ll face when running applications in Kubernetes.</p><p><strong>Your containers don’t just work locally anymore. They’re ready for the real world.</strong></p><p>Now go deploy something amazing.</p><h3>Complete Code Repository</h3><p>All the code from this guide is available in this <a href="https://github.com/Ife-Olaitan/container-assessment">repository</a></p><ul><li>Docker Compose setup</li><li>Complete Kubernetes manifests</li><li>Automation scripts</li><li>Environment templates</li></ul><p>Feel free to use it as a template for your own projects.</p><h3>Questions? Feedback?</h3><p>If this guide helped you, or if you hit a snag I didn’t cover, I’d love to hear about it. Connect with me on <a href="https://www.linkedin.com/in/ifeoluwaolaiya/">LinkedIn</a> or drop a comment.</p><p>Cheers and happy deploying!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd52b463aac0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[EC2 vs S3: Deploying the Same Website Two Ways on AWS]]></title>
            <link>https://medium.com/@ifeoluwa1201/ec2-vs-s3-deploying-the-same-website-two-ways-on-aws-2f3c2ff384e4?source=rss-3486717239fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f3c2ff384e4</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[ansible]]></category>
            <dc:creator><![CDATA[Ifeoluwa O. Olaiya]]></dc:creator>
            <pubDate>Sun, 05 Oct 2025 10:30:14 GMT</pubDate>
            <atom:updated>2025-10-05T10:58:29.940Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bho1f2jBe4w4uQCaMwxZkQ.png" /></figure><p>Deploying websites in the cloud can be approached in more than one way, and each method comes with its own strengths and trade-offs. This project explored two distinct approaches on AWS: using <strong>EC2 instances behind an Application Load Balancer (ALB)</strong> and using <strong>Amazon S3 Static Website Hosting</strong>.</p><p>The key tasks included:</p><ul><li>Launching two EC2 instances inside a custom VPC and subnets</li><li>Configuring the instances with NGINX to serve a custom HTML page</li><li>Automating the process using Ansible</li><li>Placing the EC2s behind an ALB to handle traffic distribution</li><li>Deploying the same HTML file to an S3 bucket with static website hosting</li><li>Comparing both approaches and documenting the outcomes</li></ul><p>By following these steps, the project not only delivered a functional website but also demonstrated how AWS services can be combined with automation tools to achieve <strong>scalable, dynamic hosting</strong> on one hand, and <strong>simple, cost-effective static hosting</strong> on the other.</p><h3>Step 1: Creating the VPC</h3><p>I began by creating a dedicated Virtual Private Cloud (VPC) instead of using the default one. This gave me full control over IP addressing, subnets, and routing. In a production environment, this is a best practice for ensuring isolation and control of resources.</p><figure><img alt="Custom VPC created in AWS Console" src="https://cdn-images-1.medium.com/max/1024/1*csHTgOu7K9Cx5V0_L7GRTA.png" /><figcaption><em>Custom VPC created in AWS Console</em></figcaption></figure><h3>Step 2: Designing Subnets Across Availability Zones</h3><p>Inside the VPC, I created <strong>two subnets</strong>, one in each Availability Zone. At first, these were private by default. I later turned them into <strong>public subnets</strong> by:</p><ul><li>Associating them with a route table that had a default route (0.0.0.0/0) pointing to the Internet Gateway (IGW).</li><li>Launching EC2 instances with <strong>public IPs enabled</strong>, so I could connect from my local machine with SSH and configure them using Ansible.</li></ul><p>This design also provided <strong>high availability and fault tolerance</strong>, since traffic could still flow even if one Availability Zone went down. The public IPs were only needed for Ansible and SSH access. The ALB itself communicates with the instances via their private IPs inside the VPC.</p><figure><img alt="Two subnets created in different Availability Zones" src="https://cdn-images-1.medium.com/max/1024/1*x-vEckUH8FPAK_d1AQuzUg.png" /><figcaption><em>Two subnets created in different Availability Zones</em></figcaption></figure><h3>Step 3: Internet Gateway and Route Tables</h3><p>To connect the subnets to the internet, I created an <strong>Internet Gateway (IGW)</strong> and attached it to my VPC. I then created a <strong>Route Table</strong> with a default route to the IGW and associated it with both subnets.</p><p>This routing setup is what actually made the subnets public. Without the IGW and route table association, even instances with public IPs would not have outbound internet access.</p><figure><img alt="Route Table with default route to Internet Gateway (IGW)" src="https://cdn-images-1.medium.com/max/1024/1*PIAyDYkzHC7pXqE5iNxkQQ.png" /><figcaption><em>Route Table with default route to Internet Gateway (IGW)</em></figcaption></figure><h3>Step 4: Security Groups</h3><p>For security, I designed two separate groups. The first was for the ALB, which allowed inbound HTTP traffic (port 80) from anywhere. The second was for the EC2 instances, which allowed SSH (port 22) only from my IP and HTTP (port 80) only from the ALB security group.</p><p>This separation ensured layered security: only I could log in via SSH, and only the ALB could talk to the EC2 instances. The instances were never directly exposed to the internet for HTTP traffic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J_soKPLMo8yejFJGQ_6r1A.png" /><figcaption><em>Security group rules showing ALB SG</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8jY16gkSxTNA2cvQqELkpw.png" /><figcaption><em>Security group rules showing APP SG</em></figcaption></figure><h3>Step 5: Launching EC2 Instances</h3><p>With networking ready, I launched two Ubuntu 22.04 LTS EC2 instances (t2.micro, Free Tier). Each was placed in a different subnet and Availability Zone, given a public IP for remote access, and secured by the EC2 security group.</p><p>The public IPs allowed me to run Ansible directly from my laptop. In production, a more secure approach would be to avoid public IPs and instead manage instances through a bastion host. Importantly, the ALB itself only routes traffic to the private IPs of these EC2 instances within the VPC.</p><figure><img alt="Two EC2 Ubuntu instances running in separate AZs" src="https://cdn-images-1.medium.com/max/1024/1*26lAYRVwsMwu9n85BPY29w.png" /><figcaption><em>Two EC2 Ubuntu instances running in separate AZs</em></figcaption></figure><h3>Step 6: Preparing Ansible</h3><p>On my local machine, I set up Ansible with an <strong>inventory file</strong> containing the two EC2 IPs, a <strong>configuration file for Ansible</strong> itself, and a <strong>playbook</strong> that would install NGINX and deploy the HTML.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BLLft97_UeWkWZ5oG9u2Jw.png" /><figcaption>Ansible configuration file</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*otM_N6B3LlOzWDzb4aSaVw.png" /><figcaption>Ansible inventory file</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_I_wK3QM6TxY7mZAYL1nVw.png" /><figcaption>Ansible playbook file</figcaption></figure><p>After setting up SSH access, I confirmed Ansible could reach both servers by running a simple ping command. The responses confirmed my configuration was correct.</p><pre>ansible -m ping webservers</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ypSBNkkNpiXY6sWVwjkvhA.png" /><figcaption><em>Ansible ping successful for both EC2 instances</em></figcaption></figure><h3>Step 7: Creating the HTML Page</h3><p>To make the site dynamic, I wrote a Jinja2 template that displayed the hostname of whichever EC2 instance was serving the request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6joFxFbqoKNJ8ypfKRigcA.png" /><figcaption><em>index.html.j2 Jinja2 template file</em></figcaption></figure><p>This simple template made it easy to confirm load balancing later, since refreshing the page would show different hostnames.</p><h3>Step 8: Running the Playbook</h3><p>The Ansible playbook I used contained four main tasks: update the package manager, install NGINX, deploy my Jinja2 HTML page to the NGINX web directory, and ensure the NGINX service was started and enabled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_I_wK3QM6TxY7mZAYL1nVw.png" /><figcaption>Ansible playbook file</figcaption></figure><p>I ran the playbook against my inventory file and within a few minutes, both servers were fully configured and serving the custom HTML page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kgMmaDSfvFSpbG_DMQ7hLw.png" /><figcaption><em>Successful execution of Ansible playbook installing NGINX and deploying HTML</em></figcaption></figure><h3>Step 9: Setting Up the ALB</h3><p>Next, I created an Application Load Balancer. I set up a Target Group on port 80 with health checks on / and registered both EC2 instances. I then deployed the ALB across the two subnets and attached it to the target group. I confirmed that the Target Group showed both instances as healthy. The ALB was then successfully created across two subnets and linked to the Target Group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_qR3X5b9D4CNfdxSTloSgQ.png" /><figcaption><em>Application Load Balancer created across two subnets</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8JzGRw24M2X5fHlbMjtP_A.png" /><figcaption><em>Target Group showing registered EC2 instances and health checks</em></figcaption></figure><p>The ALB distributed traffic evenly between the EC2 instances using their private IPs. This highlighted one of the benefits of VPC networking: even though I used public IPs for Ansible and management, the ALB itself securely and privately communicated with the servers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OqGvYNpcgTypaQdeLoXgIw.png" /><figcaption><em>Browser showing ALB DNS alternating between hostnames on refresh</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X-86EXhNplbUjPWSHtKGKQ.png" /><figcaption><em>Browser showing ALB DNS alternating between hostnames on refresh</em></figcaption></figure><h3>Step 10: Hosting the Same Site on S3</h3><p>For comparison, I hosted the same HTML file on Amazon S3. I created a bucket with a unique name, uploaded the index.html file, enabled static website hosting in the bucket properties, and added a public-read bucket policy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UX5lWmNiRMf68pabZvNa7w.png" /><figcaption><em>S3 bucket created and configured for static website hosting</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WOD_XECUhEyxWNEQgwzC8g.png" /><figcaption><em>S3 bucket policy allowing public read access</em></figcaption></figure><p>Unlike EC2 and ALB, S3 hosting does not require a VPC, subnets, or an internet gateway. The content is served directly from S3’s global infrastructure. The trade-off is that it can only serve static content, with no server logic or dynamic values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I7n6G_odvYyT0jDbm8smQg.png" /><figcaption><em>Browser showing S3 static website endpoint serving HTML file</em></figcaption></figure><h3>Step 11: Comparing EC2 + ALB vs S3</h3><p>Hosting the same website on EC2 behind an ALB and on S3 highlighted the differences between compute-based and storage-based hosting. With EC2 and ALB, I could serve dynamic content. For example, each EC2 instance displayed its own hostname, and the load balancer alternated between them when refreshing the page. This setup is more flexible and can run full web applications, but it also comes with higher cost and more management overhead, since servers must be maintained, patched, and scaled.</p><p>On the other hand, hosting on S3 was much simpler. After uploading the HTML file and enabling static website hosting, the site was immediately accessible from the S3 endpoint. The trade-off is that S3 can only serve static content. It cannot execute code or return dynamic values like EC2 can. However, S3 hosting is extremely cost-effective, scales automatically, and requires almost no ongoing management.</p><p>In short, EC2 with ALB is best suited for web applications or workloads that require dynamic content and server-side logic, while S3 is ideal for static websites, documentation, or blogs where simplicity and low cost are the priority.</p><h3>Step 12: Reflections</h3><p>This project gave me hands-on experience in designing a custom VPC with subnets, routing, and an Internet Gateway. I practiced configuring layered security groups for ALB and EC2, and I automated server setup using Ansible to ensure consistency and repeatability. Most importantly, I was able to compare compute-based hosting, which is flexible but costly, with storage-based hosting, which is simple and cost-effective but limited to static content.</p><p>It also reinforced the importance of documentation. Capturing each step with screenshots and clear explanations not only demonstrated my process but also deepened my understanding of the services and their interactions.</p><p>Thanks for reading! If you are also exploring Cloud and DevOps, I’d love to connect and share the journey.</p><p>Linkedin — Ifeoluwa Olaiya (<a href="https://www.linkedin.com/in/ifeoluwaolaiya?utm_source=share&amp;utm_campaign=share_via&amp;utm_content=profile&amp;utm_medium=ios_app">https://www.linkedin.com/in/ifeoluwaolaiya?utm_source=share&amp;utm_campaign=share_via&amp;utm_content=profile&amp;utm_medium=ios_app</a>)</p><p>Email — olaiyaifeoluwa.o@gmail.com</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f3c2ff384e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>