Part 2 ยท Chapter 6

CI/CD & GitHub Actions

How code goes from a git push to a running production deployment, automatically.

What you'll learn in this chapter

  • What CI and CD mean and why the distinction matters
  • How GitHub Actions works: workflows, jobs, steps, triggers, and runners
  • A complete, production-ready CI/CD pipeline for a Node.js application
  • How to use secrets, caching, and the Actions Marketplace
  • GitLab CI/CD and how it compares to GitHub Actions
  • Branch protection rules and PR gates โ€” how teams ship code confidently
  • Deployment strategies: rolling, blue/green, and canary releases

The Factory Assembly Line Analogy

Before assembly lines, cars were built by hand โ€” one at a time, by skilled craftspeople who each assembled an entire car from start to finish. It took weeks. The quality varied depending on who built it and on what day. Scaling up meant hiring more craftspeople and hoping each one worked the same way.

Henry Ford's insight was not that workers were lazy. It was that the process was inefficient. Break the work into standardized steps. Have each step performed in sequence by a specialist. Automate what can be automated. The result: cars built identically, reliably, in a fraction of the time.

CI/CD is your software factory assembly line. Every time a developer pushes code, a robot factory takes over. It checks out the code, installs dependencies, runs the linter, runs the tests, builds the Docker image, pushes it to a registry, and deploys it to the server. No human needs to type a single command. No steps get accidentally skipped on a Friday afternoon when everyone wants to go home. The process is identical every single time.

๐Ÿญ The Assembly Line Analogy

CI/CD is your software assembly line. A developer's git push is the raw material entering the factory. The pipeline is the conveyor belt โ€” each station (job) performs one task. The finished product rolling off the end is a verified, tested, deployed application running in production. No human hands touch it between the push and the deploy.

CI vs CD โ€” What's the Difference?

These two terms are often used together, but they mean different things and represent different levels of automation maturity.

Continuous Integration (CI)

Continuous Integration means that every time a developer pushes code โ€” even a small change to a single file โ€” an automated process immediately kicks off: check out the code, install dependencies, run the linter, run the tests, report a pass or fail. The key word is continuous. Not "we run tests before big releases." Not "we run tests when someone remembers." Every. Single. Push.

The benefit: bugs are caught within minutes of being introduced. When you write the breaking code and the test fails five minutes later, you know exactly what you did. Compare that to finding the same bug two weeks later when ten other developers have built on top of your code. CI compresses the feedback loop dramatically.

Continuous Delivery (CD)

Continuous Delivery adds the next step: the application is always in a deployable state. After CI passes, the artifact (a Docker image, a zip file, a binary) is built and packaged, ready to be deployed at any time with a single button click. The deployment itself may still require a human decision โ€” but the preparation is automatic. Teams practicing Continuous Delivery can deploy on demand, multiple times a day if they choose.

Continuous Deployment

Continuous Deployment removes even the human decision: if the tests pass, the code goes straight to production automatically. No button press. This is the most aggressive form of CD, practiced by companies like Netflix, Amazon, and Etsy. When you push 50 small commits a day and trust your test suite completely, this level of automation makes sense. For most teams starting out, Continuous Delivery is the right target.

Continuous Integration:
  git push โ†’ checkout โ†’ install โ†’ lint โ†’ test โ†’ report โœ“/โœ—

Continuous Delivery:
  git push โ†’ checkout โ†’ lint โ†’ test โ†’ build image โ†’ push to registry โ†’ [HUMAN APPROVES] โ†’ deploy

Continuous Deployment:
  git push โ†’ checkout โ†’ lint โ†’ test โ†’ build image โ†’ push to registry โ†’ deploy automatically
๐Ÿ“š Key Term: Pipeline

A CI/CD pipeline is the automated sequence of steps that runs when code is pushed. Each step either passes or fails. If any step fails, the pipeline stops and the team is notified. A pipeline ensures that every piece of code that reaches production has been through the same quality gates, every time.

GitHub Actions โ€” The Concepts

GitHub Actions is the CI/CD platform built directly into GitHub. It is free for public repositories and has a generous free tier for private ones. Because it lives inside GitHub, it has deep integration: it can read your code, use your secrets, report status on pull requests, and deploy using your repository's identity โ€” with no third-party service needed.

Workflows

A workflow is a YAML file that lives in the .github/workflows/ directory of your repository. You can have many workflow files โ€” one for CI, one for scheduled tasks, one for releasing. Each workflow runs independently.

Triggers (on)

Workflows run in response to events โ€” things that happen in your repository. The most common triggers are push (code pushed to a branch), pull_request (a PR is opened, updated, or merged), and schedule (run on a cron schedule). You can also trigger workflows manually with workflow_dispatch.

Jobs

A workflow contains one or more jobs. Each job runs on a fresh virtual machine called a runner. Jobs run in parallel by default. If one job needs the result of another, you use needs: to declare the dependency, and GitHub will run them in sequence.

Steps

Each job contains a list of steps. A step is either a shell command (run:) or a pre-built action (uses:). Steps within a job share the same filesystem and runner environment, so a file created in one step is available in the next.

Actions

An action is a reusable, pre-built step published to the GitHub Marketplace. actions/checkout@v4 checks out your code. actions/setup-node@v4 installs Node.js. docker/build-push-action@v5 builds and pushes a Docker image. There are thousands of community-built actions for almost any task imaginable.

A Production-Ready GitHub Actions Pipeline

Here is a complete, real-world CI/CD workflow for a Node.js application. It has three jobs that run in sequence: test, then build and push the Docker image, then deploy to a server. Study this carefully โ€” it follows patterns you will see in virtually every professional GitHub Actions setup.

# .github/workflows/ci-cd.yml
name: CI/CD Pipeline

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

env:
  NODE_VERSION: '20'
  REGISTRY: ghcr.io
  IMAGE_NAME: ${{ github.repository }}

jobs:
  ##############################################
  # JOB 1 โ€” Test: lint, unit tests, integration
  ##############################################
  test:
    name: Test
    runs-on: ubuntu-latest

    services:
      # Spin up a real PostgreSQL database for integration tests
      postgres:
        image: postgres:16
        env:
          POSTGRES_PASSWORD: testpass
          POSTGRES_DB: testdb
        options: >-
          --health-cmd pg_isready
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: ${{ env.NODE_VERSION }}
          cache: 'npm'         # caches node_modules between runs

      - name: Install dependencies
        run: npm ci

      - name: Run linter
        run: npm run lint

      - name: Run tests
        run: npm test
        env:
          DATABASE_URL: postgresql://postgres:testpass@localhost:5432/testdb

  ##############################################
  # JOB 2 โ€” Build image and push to registry
  # Only runs after test passes, and only on main
  ##############################################
  build-and-push:
    name: Build & Push Docker Image
    needs: test                          # only runs if test passes
    runs-on: ubuntu-latest
    if: github.ref == 'refs/heads/main'   # only on main branch

    permissions:
      contents: read
      packages: write                    # needed to push to GHCR

    steps:
      - uses: actions/checkout@v4

      - name: Log in to GitHub Container Registry
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Extract image metadata
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
          tags: |
            type=sha               # tag with git commit SHA
            type=raw,value=latest

      - name: Build and push Docker image
        uses: docker/build-push-action@v5
        with:
          context: .
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          cache-from: type=gha   # use GitHub Actions layer cache
          cache-to: type=gha,mode=max

  ##############################################
  # JOB 3 โ€” Deploy to production server via SSH
  ##############################################
  deploy:
    name: Deploy to Production
    needs: build-and-push
    runs-on: ubuntu-latest
    if: github.ref == 'refs/heads/main'

    steps:
      - name: Deploy via SSH
        uses: appleboy/ssh-action@v1
        with:
          host: ${{ secrets.SERVER_HOST }}
          username: ${{ secrets.SERVER_USER }}
          key: ${{ secrets.SSH_PRIVATE_KEY }}
          script: |
            docker pull ghcr.io/${{ github.repository }}:latest
            docker stop myapp || true
            docker rm   myapp || true
            docker run -d --name myapp \
              -p 3000:3000 \
              --env-file /etc/myapp.env \
              --restart unless-stopped \
              ghcr.io/${{ github.repository }}:latest

Let's trace what happens when a developer pushes to main. The test job starts immediately on a fresh Ubuntu runner. It spins up a real PostgreSQL service container in the same runner network, installs Node.js, runs the linter, and runs the tests against the real database. If any step fails, the pipeline stops and the developer gets an email and a red indicator on their commit.

If all tests pass, the build-and-push job starts. It logs into GitHub Container Registry using the automatically-provided GITHUB_TOKEN (no manual secret needed), builds the Docker image, and pushes it tagged with both the commit SHA and latest.

Finally, the deploy job SSHes into the production server, pulls the new image, stops and removes the old container, and starts a fresh one. The entire process โ€” from push to live production โ€” takes about four minutes.

Secrets and Environment Variables

Pipelines need sensitive information: SSH keys, database passwords, API tokens. You never put these in your YAML file or in your repository. GitHub Actions has a Secrets system: go to your repository's Settings, find Secrets and Variables under Actions, and add key-value pairs. They are encrypted at rest and masked in logs โ€” even if a step accidentally prints them, GitHub replaces the value with asterisks.

In your workflow, reference them as ${{ secrets.SECRET_NAME }}. The value is injected at runtime and never visible to anyone after it is saved.

โš ๏ธ Never Commit Secrets

It sounds obvious, but it happens constantly. A developer accidentally commits a .env file with real credentials. GitHub scans public repositories for known secret patterns and will alert you โ€” but if the repository was public even for a minute, assume the secret was already harvested by automated scrapers. Rotate it immediately. Use a .gitignore that excludes .env files, and use repository secrets for anything sensitive in pipelines.

Caching Dependencies for Speed

Every job starts on a fresh runner. That means every run starts with no node_modules, no npm cache, nothing. Without caching, every run re-downloads hundreds of megabytes of dependencies. With caching, the second run and every run after it reuses the cached modules. The difference is often three minutes versus fifteen seconds for the install step alone.

The actions/setup-node@v4 action handles caching automatically when you add cache: 'npm'. It caches based on a hash of your package-lock.json. If your dependencies haven't changed, the cached version is restored. If package-lock.json changes (you added or removed a package), it reinstalls fresh and saves a new cache.

Matrix Builds โ€” Test Against Multiple Versions

What if your library needs to work on Node.js 18, 20, and 22? Instead of three separate jobs, use a matrix strategy. GitHub Actions runs the job once for each combination of the matrix values, in parallel.

test:
  strategy:
    matrix:
      node-version: [18, 20, 22]
      os: [ubuntu-latest, windows-latest]

  runs-on: ${{ matrix.os }}

  steps:
    - uses: actions/checkout@v4
    - uses: actions/setup-node@v4
      with:
        node-version: ${{ matrix.node-version }}
    - run: npm ci && npm test

This creates six parallel runs: Node 18+Ubuntu, Node 18+Windows, Node 20+Ubuntu, Node 20+Windows, Node 22+Ubuntu, Node 22+Windows. If any combination fails, you know exactly which environment breaks. GitHub reports all six results in the pull request.

GitLab CI/CD โ€” The Alternative

Not every team uses GitHub. GitLab is widely used in enterprise and self-hosted environments. GitLab CI/CD works similarly but uses a single .gitlab-ci.yml at the root of your repository. The concepts map directly: stages instead of jobs with dependencies, the same idea of runners, the same idea of secrets (called CI/CD variables in GitLab).

# .gitlab-ci.yml
stages:
  - test
  - build
  - deploy

test:
  stage: test
  image: node:20-alpine
  services:
    - postgres:16
  variables:
    POSTGRES_PASSWORD: testpass
    DATABASE_URL: postgresql://postgres:testpass@postgres:5432/postgres
  script:
    - npm ci
    - npm run lint
    - npm test

build:
  stage: build
  image: docker:24
  services:
    - docker:dind           # Docker-in-Docker โ€” lets you run Docker inside CI
  script:
    - docker build -t $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA .
    - docker push $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA
    - docker tag $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA $CI_REGISTRY_IMAGE:latest
    - docker push $CI_REGISTRY_IMAGE:latest
  only:
    - main

deploy:
  stage: deploy
  script:
    - ssh deploy@$SERVER_HOST "docker pull $CI_REGISTRY_IMAGE:latest && docker compose up -d"
  environment:
    name: production
    url: https://myapp.example.com
  only:
    - main

Branch Protection and PR Gates

A CI pipeline is only useful if it can actually block bad code from reaching production. That is where branch protection rules come in. In GitHub, go to your repository's Settings → Branches, and add a branch protection rule for main.

The key settings to enable: "Require a pull request before merging" (no pushing directly to main), "Require status checks to pass before merging" (CI must pass), and "Require branches to be up to date before merging" (prevents merging stale PRs).

With these rules in place, this is the only path to production: open a PR, CI runs, a team member reviews, CI passes, only then can it be merged. This process catches bugs, enforces standards, and creates a paper trail of every change. Elite engineering teams live and breathe this workflow.

๐Ÿ’ก Environments and Approval Gates

GitHub Actions supports "Environments" โ€” named deployment targets like staging and production. You can require manual approval before a job that targets the production environment runs. This gives you automated builds and tests while still keeping a human in the loop for the final deploy to production โ€” the best of both worlds for risk-conscious teams.

Deployment Strategies

How you replace an old version of your application with a new one matters enormously for reliability. There are three main strategies, each with different tradeoffs.

Rolling Deployment

Replace running instances of the old version one by one with the new version. At any point during the rollout, some instances run the new version and some run the old. Traffic is distributed across all of them. This achieves zero-downtime deploys but means briefly running two versions simultaneously โ€” a problem if the new version is not backward-compatible with the old one's database schema.

Blue/Green Deployment

Run two identical production environments: "blue" (current) and "green" (new). Deploy the new version to green. Run tests against green. When you're confident, flip a load balancer switch to send all traffic to green in an instant. Blue is now idle but available. If something goes wrong, flip the switch back โ€” rollback is immediate and zero-risk. The cost: you are running double the infrastructure during the transition.

Canary Deployment

Named after the canary-in-a-coal-mine concept โ€” use a small group to detect danger before the whole group is exposed. Deploy the new version to a small percentage of servers (say, 5%). Route 5% of real user traffic to the new version while 95% stays on the old. Monitor error rates, latency, and user behavior. If the canary looks healthy, gradually increase to 10%, then 25%, then 50%, then 100%. If the canary looks sick, roll back immediately โ€” only 5% of users ever saw the broken version. This is the gold standard for large-scale production deployments.

Blue/Green:
  Load Balancer โ†’ [Blue: v1.0] 100% traffic โ†’ test passes โ†’ switch
  Load Balancer โ†’ [Green: v2.0] 100% traffic โ†’ rollback = flip back

Canary:
  t=0:   [v1.0] 95%  [v2.0] 5%   โ†’ watch metrics
  t=1h:  [v1.0] 75%  [v2.0] 25%  โ†’ still healthy
  t=4h:  [v1.0] 0%   [v2.0] 100% โ†’ full rollout complete

Useful Patterns and Pro Tips

Reusable Workflows

GitHub Actions lets you define a workflow in one repository and call it from others using uses: myorg/shared-workflows/.github/workflows/build.yml@main. This is how large organizations standardize their CI/CD patterns across dozens of repositories without copy-pasting YAML everywhere.

Composite Actions

If you find yourself repeating the same three steps (setup Node, install, build) across multiple workflows, package them into a composite action. A composite action is a local folder with an action.yml file that bundles steps together. Call it with uses: ./.github/actions/build-node-app.

Artifact Uploads

Need to pass files between jobs (like a compiled binary, or test coverage reports)? Use actions/upload-artifact to save them from one job and actions/download-artifact to retrieve them in the next.

Chapter Summary

  • Continuous Integration means every code push automatically triggers testing โ€” catching bugs within minutes of introduction rather than weeks later.
  • Continuous Delivery ensures the application is always in a deployable state. Continuous Deployment goes further and deploys automatically when tests pass.
  • GitHub Actions uses YAML workflows in .github/workflows/. Workflows have triggers, jobs, and steps. Jobs run on fresh runners and can depend on each other.
  • Use repository secrets for sensitive data โ€” never put credentials in YAML files. Reference them as ${{ secrets.MY_SECRET }}.
  • Branch protection rules enforce that CI must pass and code must be reviewed before anything merges to main โ€” the foundation of reliable team workflows.
  • Rolling deployments replace instances one by one. Blue/green runs two environments and switches traffic instantly. Canary gradually rolls out to a small percentage before going to 100%.