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.
By the end of this lesson you'll be able to
0 of 4 completeVerified: shop-api's lint and three tests pass with Node 22, and the workflow file parses. The output shown
is real.
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.
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
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:
- Nothing is published unless it passed tests and the scan.
- The image that's deployed is byte for byte the image that was tested. No rebuilds after the scan.
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:
# 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:
$ 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
npm run lint && npm test&&run the next command only if this one worked
(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.
# .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:
# .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:
# /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):
# .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.
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.
A pull request where the Image workflow passes Test, Build and Scan and skips PushReveal one safe solution
$ 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
docker build --target test .dockerbuild and run containersbuildbuild an image from a Dockerfile--target teststop at this build stage.the build context: the files COPY can see
docker build --target runtime -t shop-api:ci .--target runtimestop at this build stage-t shop-api:ciname and tag the image
docker run -d --name registry -p 5000:5000 registry:3runstart a new container-drun in the background--name registryname the container-p 5000:5000publish a port, host:containerregistry:3the image to start
docker tag shop-api:ci localhost:5000/shop-api:test && docker push localhost:5000/shop-api:testtaggive an image another nameshop-api:cithe image, then its new namelocalhost:5000/shop-api:testthe image, then its new name&&run the next command only if this one workedpushupload an image to a registrylocalhost:5000/shop-api:testthe image
docker inspect --format '{{index .RepoDigests 0}}' localhost:5000/shop-api:testinspectshow every detail as JSON--format '{{index .RepoDigests 0}}'print only these fields (Go template)localhost:5000/shop-api:testthe container or image
git switch -c ci/image && git add Dockerfile .github/workflows/image.yml && git commit -m "ci: test, scan and push the image"gitversion controladdstage changescommitsave staged changes
git push -u origin ci/image && gh pr create --fill && gh pr checks --watchpushupload commits
docker rm -f registryrmdelete a container-fstop it first if runningregistrythe container
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 yourself
0 of 5 steps doneRun each task in your own account or terminal, then tick it off.
Quick check
Why run the tests in a Dockerfile stage instead of only on the CI runner?
Official reading for this lesson
Or get every quiz answer right and it completes itself.
Something unclear, wrong or out of date in this lesson? Tell me, and I'll fix it.