Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 44 ยท Projects

Project: Build, Scan and Deploy a Container

Build a pipeline that tests, builds and scans a Docker image, pushes it by commit SHA, deploys to staging, waits for approval and promotes to production.

In this project you will design the pipeline that most teams eventually need: a web service is tested, packaged as a container image, scanned for known vulnerabilities, stored in a registry, deployed to staging, and then promoted to production after a human approves it. Each earlier lesson contributed one piece. Here you will wire the pieces together and make the important decisions: what the image is called, what is allowed to deploy, and what must never be rebuilt.

The workflow files below are read-only, because they need GitHub's servers, a registry and real hosts. The runnable part is a stand-in: a small simulation of the promotion logic (build once, scan, deploy to staging, wait for approval, promote the same image). It is not GitHub Actions, but it shows the rules that make this design safe. If you need a refresher first, read Building and Pushing Docker Images and Environments, Approvals and Deployments.

The plan

The golden rule of container delivery is build once, deploy many times. The image that was tested and scanned is the very same image that reaches production. You do not rebuild it for each environment; you only change configuration, such as environment variables and secrets, when you deploy it.

flowchart LR
  T["test"] --> B["build image"]
  B --> S["scan image"]
  S --> P["push to registry<br/>tag: commit SHA"]
  P --> ST["deploy to staging"]
  ST --> A["approval"]
  A --> PR["deploy to production<br/>same image"]

One image flows left to right; staging and production receive the same digest.

We use three rules throughout:

  1. Every image is tagged with the full commit SHA. A SHA tag never moves, so "what is running in production?" always has an exact answer.
  2. Pull requests build and scan, but they never push or deploy.
  3. Only the main branch can deploy, and production sits behind a protected environment with required reviewers.

Step 1: test and build

Start with a workflow that triggers on pull requests and on pushes to main. The test job comes first and the build job needs it, as you learned in Jobs, Steps and Dependencies.

YAML
name: container-pipeline

on:
  pull_request:
  push:
    branches: [main]

concurrency:
  group: pipeline-${{ github.ref }}
  cancel-in-progress: ${{ github.event_name == 'pull_request' }}

permissions:
  contents: read

env:
  REGISTRY: ghcr.io
  IMAGE: ghcr.io/${{ github.repository }}

jobs:
  test:
    runs-on: ubuntu-latest
    timeout-minutes: 15
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm
      - run: npm ci
      - run: npm test

Notice the concurrency setting. Old pull request runs are cancelled when new commits arrive, but runs on main are never cancelled mid-way, because a half-finished deploy is worse than a slow one. The workflow-level permissions block gives every job read-only access by default; jobs that need more will ask for it explicitly. That is the least-privilege habit from Securing Your Pipeline.

The build job creates the image but only loads it into the runner, so a scanner can look at it before anything is published:

YAML
  build:
    needs: test
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: docker/setup-buildx-action@v3
      - uses: docker/build-push-action@v6
        with:
          context: .
          load: true
          tags: ${{ env.IMAGE }}:${{ github.sha }}
          cache-from: type=gha
          cache-to: type=gha,mode=max

The cache-from and cache-to lines reuse Docker layers between runs, so a change to application code does not reinstall every dependency. Your Dockerfile should copy the dependency manifests and install before copying the rest of the code, so that the layer cache can do its work. See the Docker tutorial for Dockerfile practice.

Step 2: scan before you publish

An image can contain vulnerable operating-system packages even when your own code is clean. A scanner compares the packages inside the image with a vulnerability database and fails the job when it finds serious problems. Trivy is a common open-source scanner; any scanner that returns a non-zero exit code on findings works the same way.

YAML
      - name: Scan image
        uses: aquasecurity/[email protected]
        with:
          image-ref: ${{ env.IMAGE }}:${{ github.sha }}
          severity: CRITICAL,HIGH
          ignore-unfixed: true
          exit-code: "1"

Two settings deserve a comment. ignore-unfixed skips findings that have no available patch, because you cannot act on them, and failing every build over them only teaches the team to ignore red builds. exit-code: "1" is what turns a finding into a failed step. Pin the action to a full commit SHA in a real project (the tag above is for readability), and keep the scanner's vulnerability database fresh, since a scan that ran yesterday can miss today's advisory.

Because the build and scan run in the same job here, the loaded image is still on the runner when the scanner looks for it. If you split them into separate jobs, you would have to export the image as an artifact or push it to a temporary tag first.

Step 3: push by SHA

Publishing happens only after tests and scan have passed, and only on main. This is a separate job with write access to packages:

YAML
  publish:
    needs: build
    if: github.event_name == 'push' && github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write
    outputs:
      image: ${{ env.IMAGE }}@${{ steps.push.outputs.digest }}
    steps:
      - uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}
      - uses: docker/setup-buildx-action@v3
      - id: push
        uses: docker/build-push-action@v6
        with:
          push: true
          tags: ${{ env.IMAGE }}:${{ github.sha }}
          cache-from: type=gha

A caveat is worth knowing. This job rebuilds the image, and the layer cache makes it fast and almost always identical, but a strictly "build once" design would push in the first job and scan the pushed digest. Teams choose between the two: scan-then-push keeps bad images out of the registry, push-then-scan guarantees that the scanned bytes are the published bytes. If you choose the first, deploy by digest (the @sha256:... identity of the image), which is what the image output above carries, so that staging and production are guaranteed to run the same bytes.

Step 4: staging, approval and production

Deployment jobs use GitHub environments. Staging has no reviewers, so it deploys automatically. Production has required reviewers configured in the repository settings, so the job pauses until someone approves.

YAML
  deploy-staging:
    needs: publish
    runs-on: ubuntu-latest
    environment:
      name: staging
      url: https://staging.example.com
    concurrency: deploy-staging
    steps:
      - run: ./scripts/deploy.sh staging "${{ needs.publish.outputs.image }}"
      - run: ./scripts/smoke-test.sh https://staging.example.com

  deploy-production:
    needs: [publish, deploy-staging]
    runs-on: ubuntu-latest
    environment:
      name: production
      url: https://www.example.com
    concurrency: deploy-production
    steps:
      - run: ./scripts/deploy.sh production "${{ needs.publish.outputs.image }}"
      - run: ./scripts/smoke-test.sh https://www.example.com

Both deploy jobs read needs.publish.outputs.image, so each lists publish in its needs. The needs context only contains jobs named in that job's own list, so reading an output from a job you did not list gives an empty string, which is a common bug.

The smoke-test.sh script is the safety net: a quick request to a health URL that proves the new version actually started. If it fails, the job fails and the pipeline stops before the next environment. Pair it with a documented rollback, which in this design is simply re-running the deploy script with the previous SHA, because every old image is still in the registry. Deployment Strategies covers gentler rollouts such as canary releases.

The deploy script itself is yours: it might call ssh, kubectl set image, or a cloud CLI. Authenticate with short-lived OIDC credentials rather than stored keys wherever your cloud supports it.

Stand-in: a promotion pipeline simulation

The simulator below keeps the rules in plain JavaScript: an image identified by SHA, a scan that blocks on critical findings, an environment list in which production requires approval, and a refusal to deploy anything that was not built and scanned. Change the findings or the approval and watch where the pipeline stops. This is a model of the policy, not of GitHub's engine.

JS Promotion pipeline simulation

Press Run (or Ctrl + Enter) to see the console output here.

No output.

With the defaults the scan ignores the HIGH finding because it has no fix, approval is granted, and the same SHA reaches both environments. Set approvals.production to false and the run pauses; add a fixable CRITICAL finding and nothing is ever published.

The second stand-in tracks what is running where, which is how you answer "which commit is in production?" and how a rollback is chosen.

JS Deployment history and rollback

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The rollback target is not computed from a branch; it comes from the record of successful deployments. That is why every pipeline run should record what it deployed.

Hardening checklist

Before you call the project finished, check each of these:

  • The registry login uses GITHUB_TOKEN or OIDC, never a personal access token committed to the repo.
  • Third-party actions are pinned to full commit SHAs and updated by a bot (see Pipeline Metrics and Maintenance).
  • The production environment allows deployments only from main and requires at least one reviewer who is not the author.
  • Branch protection requires the test and build checks before merging.
  • Images older than a set period are cleaned up by a registry retention policy, but the SHAs of the last several production releases are kept for rollback.
  • A failed deploy notifies the team and does not leave staging and production on silently different versions.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why should staging and production run the same image?

    Build once, deploy many times. Rebuilding for production could produce different bytes than the ones you tested. Only configuration changes between environments.
  2. 2. What is the advantage of tagging images with the commit SHA instead of only latest?

    The latest tag is overwritten by every push, so it cannot answer what is running or serve as a rollback target. A SHA identifies one specific build.
  3. 3. A scan finds a HIGH vulnerability with no available patch. With ignore-unfixed enabled, what happens?

    Unfixed findings cannot be acted on, so failing on them trains people to ignore red builds. Keep tracking them separately, but gate on what you can fix.
  4. 4. Which setting makes the production job wait for a person?

    Required reviewers are configured on the environment. A job that targets it pauses until an allowed reviewer approves.
  5. 5. A deploy job reads needs.publish.outputs.image but lists only needs: deploy-staging. What goes wrong?

    The needs context only contains jobs named in the job's own needs list. Add publish to the list to read its outputs.

Summary

  • Build once, tag by commit SHA, and promote the same image (ideally by digest) through environments.
  • Pull requests may test, build and scan; only main may publish and deploy.
  • Scanners turn findings into failed steps; gate on fixable HIGH and CRITICAL issues.
  • Required reviewers on the production environment add the human approval step.
  • Smoke tests and a record of successful deployments make rollback a lookup, not a guess.
  • Read-only YAML is the real design; the simulators only model the policy.

Next: Project: A Jenkins Multibranch Pipeline