Skip to main content

Scanning Docker Images with Trivy in CI

Scan Docker images for CVEs with Trivy, fail CI builds on critical findings, and keep base images patched with automated updates.

44 Terms

Overview and What You Will Learn

Docker image scanning compares the operating system packages and language dependencies inside an image against databases of known vulnerabilities (CVEs) and reports which ones you ship, how severe they are, and which version fixes them. Trivy is a free, open-source scanner that covers images, filesystems, Dockerfiles and infrastructure files. The goal is a CI gate: an image with a fixable critical or high vulnerability never reaches the registry.

In this lab you will:

  • Install Trivy and scan an image, a project folder and a Dockerfile
  • Read results and filter them down to findings you can act on
  • Block vulnerable images in GitHub Actions and publish results to the Security tab
  • Use registry scanning, scheduled rescans and automated base image updates to catch new CVEs

Why This Matters in Production

A clean image today can have critical CVEs next month without a single code change, because new vulnerabilities are published against packages you already ship. A payments company such as Razorpay or Stripe runs containers that handle card data, so an exploitable library in a forgotten image is both a security and a compliance problem. Scanning in CI stops new issues at the door, and scheduled rescans catch the ones that appear later.

Core Principles

Vulnerabilities come from three layers of an image: the base OS packages, the language runtime and its packages, and your own application dependencies. Trivy checks all three and reports the CVE ID, severity and the fixed version if one exists.

flowchart TD A[Developer push] --> B[Build image] B --> C{Trivy scan} C -->|critical or high fixable| D[Fail build] C -->|clean| E[(Push to registry)] E --> F[Scheduled rescan] F -->|new CVE| G[Open ticket or PR] classDef ok fill:#10B981,color:#FFFFFF classDef bad fill:#EF4444,color:#FFFFFF classDef step fill:#DBEAFE,color:#1E293B class A,B,C,F step class E ok class D,G bad
Severity Typical policy
CRITICAL Fail the build
HIGH Fail the build for production services
MEDIUM and LOW Report only

Use --ignore-unfixed in the gate. If the vendor has not shipped a patch, failing the build gives the developer nothing to do. Track unfixed findings in a report instead.

Detailed Step-by-Step Practical Lab

Milestone 1: Install Trivy and Run a First Scan

Trivy needs no daemon or account. It downloads its vulnerability database on first use and caches it.

Bash
brew install trivy
# Or run it as a container (pin the current release tag from the Trivy GitHub releases page)
docker run --rm \
-v /var/run/docker.sock:/var/run/docker.sock \
-v trivy-cache:/root/.cache \
aquasec/trivy:<release-tag> image payment-api:local
trivy --version
# Scan a local image
trivy image payment-api:local

The report groups findings by target (OS packages, then each language ecosystem) with columns for library, CVE ID, severity, installed version and fixed version.

Security

Mounting /var/run/docker.sock gives the container control of the Docker daemon. On shared machines prefer the installed binary, or scan an exported image tarball with trivy image --input image.tar.

Milestone 2: Filter Results into Something Actionable

Raw output includes low-severity and unfixable noise. Filter to what a developer can fix today.

Bash
# Only serious findings
trivy image --severity CRITICAL,HIGH payment-api:local
# Only findings that have a patched version available
trivy image --severity CRITICAL,HIGH --ignore-unfixed payment-api:local
# Machine-readable output for tooling
trivy image --format json --output scan.json payment-api:local
# Exit with a non-zero code when findings match, for use in scripts and CI
trivy image --severity CRITICAL,HIGH --ignore-unfixed --exit-code 1 payment-api:local \
&& echo "PASS" || echo "FAIL"
# Scan an image in a remote registry
trivy image registry.razorpay.in/payment-api:v3.1.0

By default Trivy exits with 0 even when it finds vulnerabilities. You must pass --exit-code 1 for a gate to fail.

Milestone 3: Scan Source, Dockerfiles and Infrastructure Files

Finding a problem before you build an image is cheaper than finding it after.

Bash
# Dependencies in your repo (package-lock.json, requirements.txt, go.sum, pom.xml)
trivy fs --severity CRITICAL,HIGH .
# Also look for hardcoded secrets in the project
trivy fs --scanners vuln,secret .
# Misconfigurations in a Dockerfile (root user, missing HEALTHCHECK, latest tags)
trivy config Dockerfile
# Compose, Kubernetes and Terraform files
trivy config compose.yaml
trivy config k8s/
trivy config terraform/
Milestone 4: Gate the Pipeline in GitHub Actions

The pattern is: build without pushing, scan the local image, upload results, and push only if the scan passed.

YAML
# .github/workflows/build-scan-push.yml
name: Build, scan and push
on:
push:
branches: [main]
pull_request:
branches: [main]
env:
REGISTRY: registry.razorpay.in
IMAGE_NAME: payment-api
jobs:
build-scan-push:
runs-on: ubuntu-latest
permissions:
contents: read
security-events: write
steps:
- uses: actions/checkout@v4
- uses: docker/setup-buildx-action@v3
- name: Build image locally
uses: docker/build-push-action@v6
with:
context: .
load: true
push: false
tags: ${{ env.IMAGE_NAME }}:${{ github.sha }}
cache-from: type=gha
cache-to: type=gha,mode=max
- name: Scan with Trivy
uses: aquasecurity/trivy-action@0.28.0
with:
image-ref: ${{ env.IMAGE_NAME }}:${{ github.sha }}
format: sarif
output: trivy-results.sarif
severity: CRITICAL,HIGH
ignore-unfixed: true
exit-code: "1"
- name: Upload results to GitHub Security tab
if: always()
uses: github/codeql-action/upload-sarif@v3
with:
sarif_file: trivy-results.sarif
- name: Log in to registry
if: github.ref == 'refs/heads/main'
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ secrets.REGISTRY_USERNAME }}
password: ${{ secrets.REGISTRY_PASSWORD }}
- name: Push the scanned image
if: github.ref == 'refs/heads/main'
uses: docker/build-push-action@v6
with:
context: .
push: true
tags: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }}
cache-from: type=gha

Notes on this workflow:

  • The push step only runs if every earlier step succeeded, so a failed scan blocks publication.
  • The tag is the commit SHA, never latest, so a scan result maps to exactly one image.
  • Pin the action to a released version or commit SHA, not @master, so a change in the action cannot silently alter your gate.
  • Because the pushed build uses the cached layers from the scanned build, the pushed image is the same content that was scanned.
Milestone 5: Manage Exceptions Deliberately

Sometimes a CVE does not apply (the vulnerable code path is unused) or a fix is not available yet. Record the decision rather than weakening the gate.

Bash
# .trivyignore
# Accepted until 2026-12-31: affects the Windows installer only, we ship Linux images
CVE-2025-12345
# Accepted until 2026-11-30: no upstream fix, service is not reachable from outside the VPC
CVE-2025-67890
YAML
# trivy.yaml in the project root
severity:
- CRITICAL
- HIGH
exit-code: 1
ignore-unfixed: true
timeout: 10m

Every ignore needs a reason and an expiry date, reviewed on a schedule. An ignore list without owners becomes a permanent hole.

Milestone 6: Use Registry Scanning and Rescan on a Schedule

A scan at build time only reflects what was known that day. Rescan images that are already running.

Bash
# ECR basic scanning on push for a repository
aws ecr put-image-scanning-configuration \
--repository-name payment-api \
--image-scanning-configuration scanOnPush=true \
--region ap-south-1
# Enable continuous enhanced scanning (Amazon Inspector) for the whole registry
aws ecr put-registry-scanning-configuration \
--scan-type ENHANCED \
--rules 'scanFrequency=CONTINUOUS_SCAN,repositoryFilters=[{filter=payment-*,filterType=WILDCARD}]' \
--region ap-south-1
# Read findings for a pushed image
aws ecr describe-image-scan-findings \
--repository-name payment-api \
--image-id imageTag=v3.1.0 \
--region ap-south-1

If you do not use ECR, add a weekly scheduled workflow that runs trivy image against the tags currently deployed to production and opens an issue on failure.

Milestone 7: Keep Base Images Current Automatically

Scanning finds problems, patching fixes them. Most OS CVEs are removed simply by rebuilding on a newer base image.

Bash
# See which base your Dockerfile uses
head -1 Dockerfile
# Resolve the exact digest of a tag
docker pull node:20-alpine
docker inspect --format '{{index .RepoDigests 0}}' node:20-alpine
Dockerfile
# Pin tag and digest: readable for people, exact for builds
FROM node:20-alpine@sha256:84f9c2b1d3e5a7c9e1b3d5f7a9c1e3b5d7f9a1c3e5b7d9f1a3c5e7b9d1f3a5c7 AS builder

Pinning by digest makes builds reproducible but means you never get patches by accident. Pair it with Renovate or Dependabot, which open a pull request when the base image changes. The pull request triggers your scan gate, so you merge updates only when they pass.

Production Best Practices & Common Pitfalls

  1. Scan on every pull request. Do not wait for the merge to main.
  2. Gate with --exit-code 1. A scan that cannot fail the build is a report, not a control.
  3. Use --ignore-unfixed in the gate. Report unfixed issues separately.
  4. Scan the filesystem too. trivy fs . catches vulnerable dependencies before the image exists.
  5. Rescan deployed images. New CVEs appear after release.
  6. Prefer minimal bases. Fewer packages mean fewer findings.
  7. Expire every ignore. Add a reason, an owner and a date.
Common Mistake

Setting exit-code: 0 to stop pipeline failures. The scan then never blocks anything and gives a false sense of safety. Fix or consciously accept the findings instead.

Tip

Run trivy fs . as a pre-commit or pre-push check so a vulnerable dependency is fixed in package.json before CI ever sees it.

Remember

A clean scan is a snapshot. Schedule rescans of what is running in production.

Quick Reference & Troubleshooting Commands

Command Description
trivy image IMG Scan an image
trivy image --severity CRITICAL,HIGH --ignore-unfixed IMG Actionable findings only
trivy fs . Scan project dependencies
trivy config Dockerfile Check a Dockerfile for misconfigurations
trivy image --format json -o scan.json IMG JSON report for tooling
trivy image --input image.tar Scan an exported image
Symptom Likely cause and fix
Scan passes but CVEs exist Default exit code is 0, add --exit-code 1
Too many findings Add --ignore-unfixed and --severity CRITICAL,HIGH
Scan times out Increase --timeout and cache the database
Cannot scan private image Run docker login first, or set TRIVY_USERNAME and TRIVY_PASSWORD
Database download fails in CI Network limits, cache ~/.cache/trivy between runs

Resources

Explore More in Docker Security and Production Practices

All 5 Topics

Frequently Asked Questions

Is Scanning Docker Images with Trivy in CI free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Scanning Docker Images with Trivy in CI topic cover?

Scan Docker images for CVEs with Trivy, fail CI builds on critical findings, and keep base images patched with automated updates.

Found a mistake, an outdated step or a broken link?