# Back to your pipeline: test, scan, push and deploy the image

Back to the shop-api pipeline with what Docker taught you: tests inside the build, a scan before publishing, one image pushed and deployed by digest, and an automatic rollback.

Course: [Docker](https://devops.rajeev.pro/courses/docker), lesson 15. About 35 minutes, intermediate. Source: https://devops.rajeev.pro/courses/docker/15-back-to-your-pipeline

## What you will learn

- Run lint and tests in a Dockerfile stage so the image can't be built from failing code
- Scan the image and stop the pipeline on HIGH or CRITICAL findings before it's published
- Push the exact image that was tested and scanned, and deploy it by digest
- Deploy with Compose so an unhealthy release rolls back on its own

> **Lab status.** **Verified:** shop-api's lint and three tests pass with Node 22, and the workflow file parses. The output shown is real. <br />**Code walkthrough:** the Docker build stages, the Trivy scan, the push and the Compose deploy. Every command is one you ran in earlier lessons of this course (7, 8, 9 and 11), but this exact pipeline hasn't been run on GitHub Actions or against a server yet. <br />**Cloud lab:** none. GitHub Container Registry is free for public images; the deploy target is any server with Docker.

If you took the CI/CD course first, its pipeline used Docker before you'd learned it: a build-and-push step you
had to take on trust. Now you know what a layer, a multi-stage build, a digest and a scan are. This lesson goes
back to that same **shop-api** repository and rebuilds the image part of its pipeline properly, so every step is
one you understand.

## The pipeline you're building

```text
pull request:  checkout → test stage → build runtime image → scan → stop
push to main:  checkout → test stage → build runtime image → scan → push → deploy by digest (approval)
```

Two rules shape all of it:

1. **Nothing is published unless it passed tests and the scan.**
2. **The image that's deployed is byte for byte the image that was tested.** No rebuilds after the scan.

> **Figure.** Build job, on every push and pull request: checkout, then the test stage runs lint and 3 tests inside the image, then the runtime image is built as shop-api:ci with no tests inside, then Trivy fails the job on fixable HIGH or CRITICAL findings. Pull requests stop there. On main, the same scanned image is pushed as shop-api:sha-commit and its sha256 digest is passed to the deploy job as an output. Deploy job, main only: it waits for approval in the production environment, then over SSH runs docker compose up --wait with IMAGE set to the digest and a 60 second timeout. Healthy in 60 seconds: the digest is written to last-good and the job is green. Not healthy: the last-good image is started again and the job fails red. The Dockerfile HEALTHCHECK decides healthy.

## Tests inside the build

The Dockerfile gets a `test` stage. It copies the code and the tests and runs them; the `runtime` stage, the one
you ship, copies only the code:

```dockerfile
# syntax=docker/dockerfile:1

# 1. Everything needed to run the tests
FROM node:22-alpine AS test
WORKDIR /app
COPY package.json ./
COPY src ./src
COPY test ./test
RUN npm run lint && npm test

# 2. The image we ship: runtime and code only, no tests
FROM node:22-alpine AS runtime
WORKDIR /app
ENV NODE_ENV=production PORT=3000
COPY package.json ./
COPY src ./src
ARG APP_VERSION=dev
ENV APP_VERSION=$APP_VERSION
USER node
EXPOSE 3000
HEALTHCHECK --interval=10s --timeout=3s CMD wget -qO- http://localhost:3000/health || exit 1
CMD ["node", "src/server.js"]
```

`docker build --target test .` builds only the first stage, so a failing test fails the build. These are the
same three tests from the CI/CD course, here run with plain Node to show what the stage will print:

```text
$ npm run lint && npm test
> shop-api@1.0.0 lint
> node --check src/app.js && node --check src/server.js

> shop-api@1.0.0 test
> node --test

ok 1 - adds 18% tax and rounds to cents
ok 2 - rejects a negative amount
ok 3 - GET /health answers ok
1..3
# tests 3
# pass 3
# fail 0
```

(TAP details trimmed.) shop-api has no dependencies; a real app adds `COPY package-lock.json` and `RUN npm ci`
to both stages, and BuildKit caches that layer between them (lesson 7). Running the tests in the image means
they use the image's Node version, not whatever is installed on the CI runner.

## Scan before anything is published

Lesson 11 scanned images by hand. In the pipeline, the scan is a gate: HIGH or CRITICAL findings with a fix
available fail the job, and the push step never runs.

```yaml
# .github/workflows/image.yml (the scan step)
- name: Scan
  run: >-
    docker run --rm -v /var/run/docker.sock:/var/run/docker.sock
    aquasec/trivy:0.76.2 image --severity HIGH,CRITICAL --ignore-unfixed --exit-code 1 shop-api:ci
```

Trivy runs from its own pinned image and reads `shop-api:ci` from the runner's Docker. `--ignore-unfixed` skips
findings nobody can fix yet, so the gate fails only on things you can act on (usually by updating the base
image). Pull requests run the scan too, so a vulnerable base image is caught in review, not after merge.

## Push the image you tested

The whole workflow:

```yaml
# .github/workflows/image.yml
name: Image

on:
  push:
    branches: [main]
  pull_request:

permissions:
  contents: read

jobs:
  build:
    runs-on: ubuntu-latest
    timeout-minutes: 20
    permissions:
      contents: read
      packages: write # push to ghcr.io (used only on main)
    outputs:
      digest: ${{ steps.push.outputs.digest }}
    steps:
      - uses: actions/checkout@v7
      - uses: docker/setup-buildx-action@v4

      # 1. Run lint and tests inside the image's test stage
      - name: Test
        uses: docker/build-push-action@v7
        with:
          context: .
          target: test
          cache-from: type=gha
          cache-to: type=gha,mode=max

      # 2. Build the runtime image and load it into the runner's Docker
      - name: Build
        uses: docker/build-push-action@v7
        with:
          context: .
          target: runtime
          load: true
          tags: shop-api:ci
          build-args: APP_VERSION=sha-${{ github.sha }}
          cache-from: type=gha

      # 3. Fail on HIGH or CRITICAL vulnerabilities before anything is published
      - name: Scan
        run: >-
          docker run --rm -v /var/run/docker.sock:/var/run/docker.sock
          aquasec/trivy:0.76.2 image --severity HIGH,CRITICAL --ignore-unfixed --exit-code 1 shop-api:ci

      # 4. Only main publishes. Pull requests stop after the scan.
      - name: Log in to ghcr.io
        if: github.ref == 'refs/heads/main'
        uses: docker/login-action@v4
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}
      - name: Push the scanned image
        id: push
        if: github.ref == 'refs/heads/main'
        run: |
          IMAGE="ghcr.io/${GITHUB_REPOSITORY,,}:sha-${GITHUB_SHA}"   # registry names must be lowercase
          docker tag shop-api:ci "$IMAGE"
          docker push "$IMAGE"
          echo "digest=$(docker inspect --format '{{index .RepoDigests 0}}' "$IMAGE" | cut -d@ -f2)" >> "$GITHUB_OUTPUT"
```

The detail that matters is step 4: it **tags and pushes `shop-api:ci`**, the image that was just scanned. Many
pipelines build again in a push step; with caching that's usually the same, but if the base image changed in
between, you'd ship something nobody tested. After the push, Docker knows the image's **digest** (lesson 8), and
the job passes it to the deploy job as an output.

Tags are for people (`sha-<commit>` tells you which commit); the digest is for machines. A tag can be pushed
again and point somewhere else; `ghcr.io/you/shop-api@sha256:...` can't.

## Deploy the digest and roll back

On the server, a Compose file takes the image from a variable:

```yaml
# /srv/shop-api/compose.yaml on the server
services:
  api:
    image: ${IMAGE:?set IMAGE to the image to run}
    ports:
      - '3000:3000'
    restart: unless-stopped
```

The deploy job connects over SSH and runs it with the digest. It sits behind the `production` environment, so
it waits for an approval and only then gets the SSH secrets (the CI/CD course's lesson 4):

```yaml
# .github/workflows/image.yml (continued)
deploy:
  needs: build
  if: github.ref == 'refs/heads/main'
  runs-on: ubuntu-latest
  timeout-minutes: 10
  environment: production # required reviewers and the SSH secrets live here
  steps:
    - name: Deploy the exact digest that was tested and scanned
      env:
        SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }}
        HOST: ${{ vars.DEPLOY_HOST }}
        IMAGE: ghcr.io/${{ github.repository }}@${{ needs.build.outputs.digest }} # lowercase your repo name if it has capitals
      run: |
        install -m 600 /dev/null ~/.ssh_key && echo "$SSH_KEY" > ~/.ssh_key
        ssh -i ~/.ssh_key -o StrictHostKeyChecking=accept-new deploy@"$HOST" \
          "cd /srv/shop-api && IMAGE='$IMAGE' docker compose up -d --wait --wait-timeout 60 \
           && echo '$IMAGE' > last-good \
           || { IMAGE=\$(cat last-good) docker compose up -d; exit 1; }"
```

`docker compose up --wait` doesn't return until the container is **healthy**, which is what the Dockerfile's
`HEALTHCHECK` decides. If it isn't healthy within 60 seconds, the command fails, the script starts the image in
`last-good` again, and the job fails red so someone looks. If it is healthy, its digest becomes the new
`last-good`. That's lesson 9's health checks and the CI/CD course's rollback lesson, joined up.

`StrictHostKeyChecking=accept-new` trusts the server's key the first time. For production, store the server's
host key in a secret and write it to `known_hosts` instead, so a spoofed server can't receive your deploy. And
the first deploy needs a `last-good` file on the server, or a failure has nothing to roll back to.

## Where this goes next

This is a complete pipeline for one server. The Kubernetes course replaces the SSH step: the same digest goes
into a Deployment or a Helm values file, and a rolling update with readiness probes does the health check and
the rollback for you. The image part of the pipeline stays exactly as it is here.

## Mission: Rebuild the image pipeline for shop-api

In your shop-api repository from the CI/CD course, add the two-stage Dockerfile and the Image workflow. Prove locally that a broken test stops the build and that Trivy passes, push to a local registry to see a digest, then open a pull request and watch the workflow stop after the scan.

- You need: Your shop-api repository and Docker
- You'll have: A pull request where the Image workflow passes Test, Build and Scan and skips Push

```sh
$ docker build --target test .                       # tests run inside the build
$ docker build --target runtime -t shop-api:ci .
$ trivy image --severity HIGH,CRITICAL --ignore-unfixed --exit-code 1 shop-api:ci
$ docker run -d --name registry -p 5000:5000 registry:3
$ docker tag shop-api:ci localhost:5000/shop-api:test && docker push localhost:5000/shop-api:test
$ docker inspect --format '{{index .RepoDigests 0}}' localhost:5000/shop-api:test
$ git switch -c ci/image && git add Dockerfile .github/workflows/image.yml && git commit -m "ci: test, scan and push the image"
$ git push -u origin ci/image && gh pr create --fill && gh pr checks --watch
$ docker rm -f registry
```

Then change an expected value in `test/app.test.js`, push again, and check the workflow fails at **Test** without
ever reaching Push.

## Try it

- Build the test stage with `docker build --target test .` and read the test output.
- Break a test and build again; note which step fails.
- Scan the runtime image with Trivy and read the summary.
- Push to a local registry and find the image's digest with `docker inspect`.
- Do the mini mission and open a pull request with the workflow.

## Quiz

1. Why run the tests in a Dockerfile stage instead of only on the CI runner?
   - It's faster
   - **The tests run against the same base image, Node version and files that ship, and a failing test stops the image from being built** (answer)
   - CI runners can't run tests
   Why: The runner might have a different Node version. The test stage uses the image's own runtime, so "passed in CI" means passed in the shipped environment.

2. Why does the pipeline push the image it scanned instead of building again in a push step?
   - Rebuilding is slower but otherwise identical
   - **A second build can pick up a newer base image or package, so what you pushed is not what you tested and scanned** (answer)
   - Registries reject rebuilt images
   Why: Build once, then promote that exact artifact. A digest proves which image it is.

3. Why deploy by digest (image@sha256:...) rather than by tag?
   - Digests are shorter
   - **A tag can be moved to another image; a digest always means the same bytes** (answer)
   - Compose can't use tags
   Why: Tags like latest, or even sha-abc, can be pushed again. The digest is the content's own fingerprint.

4. What does docker compose up --wait add to a deploy?
   - Nothing
   - **It waits until the containers are running and healthy, and exits with an error if they aren't, so the script can roll back** (answer)
   - It pulls images faster
   Why: Without it, compose returns as soon as containers start, and a crashing release looks like a success.

## Resources

- [Multi-stage builds](https://docs.docker.com/build/building/multi-stage/) (Docker Docs)
- [GitHub Actions with Docker](https://docs.docker.com/build/ci/github-actions/) (Docker Docs)
- [Trivy container image scanning](https://trivy.dev/latest/docs/target/container_image/) (Trivy)
- [docker compose up](https://docs.docker.com/reference/cli/docker/compose/up/) (Docker Docs)
