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.
| 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.
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 imagetrivy image payment-api:localThe report groups findings by target (OS packages, then each language ecosystem) with columns for library, CVE ID, severity, installed version and fixed version.
SecurityMounting
/var/run/docker.sockgives the container control of the Docker daemon. On shared machines prefer the installed binary, or scan an exported image tarball withtrivy 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.
# Only serious findingstrivy image --severity CRITICAL,HIGH payment-api:local # Only findings that have a patched version availabletrivy image --severity CRITICAL,HIGH --ignore-unfixed payment-api:local # Machine-readable output for toolingtrivy image --format json --output scan.json payment-api:local # Exit with a non-zero code when findings match, for use in scripts and CItrivy image --severity CRITICAL,HIGH --ignore-unfixed --exit-code 1 payment-api:local \ && echo "PASS" || echo "FAIL" # Scan an image in a remote registrytrivy image registry.razorpay.in/payment-api:v3.1.0By 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.
# 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 projecttrivy fs --scanners vuln,secret . # Misconfigurations in a Dockerfile (root user, missing HEALTHCHECK, latest tags)trivy config Dockerfile # Compose, Kubernetes and Terraform filestrivy config compose.yamltrivy 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.
# .github/workflows/build-scan-push.ymlname: 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=ghaNotes 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.
# .trivyignore# Accepted until 2026-12-31: affects the Windows installer only, we ship Linux imagesCVE-2025-12345 # Accepted until 2026-11-30: no upstream fix, service is not reachable from outside the VPCCVE-2025-67890# trivy.yaml in the project rootseverity: - CRITICAL - HIGHexit-code: 1ignore-unfixed: truetimeout: 10mEvery 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.
# ECR basic scanning on push for a repositoryaws 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 registryaws 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 imageaws ecr describe-image-scan-findings \ --repository-name payment-api \ --image-id imageTag=v3.1.0 \ --region ap-south-1If 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.
# See which base your Dockerfile useshead -1 Dockerfile # Resolve the exact digest of a tagdocker pull node:20-alpinedocker inspect --format '{{index .RepoDigests 0}}' node:20-alpine# Pin tag and digest: readable for people, exact for buildsFROM node:20-alpine@sha256:84f9c2b1d3e5a7c9e1b3d5f7a9c1e3b5d7f9a1c3e5b7d9f1a3c5e7b9d1f3a5c7 AS builderPinning 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
- Scan on every pull request. Do not wait for the merge to main.
- Gate with
--exit-code 1. A scan that cannot fail the build is a report, not a control. - Use
--ignore-unfixedin the gate. Report unfixed issues separately. - Scan the filesystem too.
trivy fs .catches vulnerable dependencies before the image exists. - Rescan deployed images. New CVEs appear after release.
- Prefer minimal bases. Fewer packages mean fewer findings.
- Expire every ignore. Add a reason, an owner and a date.
Common MistakeSetting
exit-code: 0to stop pipeline failures. The scan then never blocks anything and gives a false sense of safety. Fix or consciously accept the findings instead.
TipRun
trivy fs .as a pre-commit or pre-push check so a vulnerable dependency is fixed inpackage.jsonbefore CI ever sees it.
RememberA 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 |