How do Trivy and Grype scan Docker images for vulnerabilities?

Trivy and Grype are open-source command-line scanners that answer the same question: which known vulnerabilities affect the software inside this image? Both work statically. They read the image's filesystem rather than running the container, and they follow the same four-stage pipeline:

  1. Unpack. The scanner pulls the image or reads it from a local daemon or tarball, then assembles the layers into the filesystem the container would see.
  2. Inventory. Analyzers catalog what is installed. For OS packages, they read the package manager's database, such as dpkg status files, the apk installed list or the RPM database. For language dependencies, they read lockfiles, manifests, JAR metadata and the build information embedded in Go binaries. Grype hands this step to Syft, which produces the inventory as an SBOM. Trivy uses its own built-in analyzers.
  3. Match. Each package and version is compared against a vulnerability database that the tool downloads and stores locally. The comparison uses ecosystem-specific version rules, because a Debian package version is not compared the same way as an npm semver range.
  4. Report. Findings are listed with a CVE or advisory ID, a severity and, when one exists, a fixed version.

When the two tools disagree on an image, speed is rarely the reason. The cause is usually coverage: which files each analyzer recognizes, and which advisory sources feed each database. Distro security trackers and language advisory databases often assign different severities or affected ranges to the same CVE.

Neither tool can report on software it never inventories. Both can miss three kinds of software:

  • Statically linked libraries.
  • Vendored source code.
  • Binaries installed with curl or make install instead of a package manager.

A clean scan means no known vulnerability was found in the components the scanner detected. It does not prove the image is safe.

+---------------------------+
| Image: registry, daemon,  |
| or tarball                |
+-------------+-------------+
              |
              v
+---------------------------+
| 1. Unpack: merge layers   |
|    into one filesystem    |
+-------------+-------------+
              |
              v
+---------------------------+     +-----------------------+
| 2. Inventory              |     | Not inventoried:      |
|  OS: dpkg, apk, RPM db    |  X  |  static-linked libs   |
|  Lang: lockfiles, JARs,   |     |  vendored source      |
|   manifests, Go buildinfo |     |  curl / make install  |
|  Trivy: built-in          |     |  => never reported    |
|  Grype: Syft -> SBOM      |     +-----------------------+
+-------------+-------------+
              | packages + versions
              v
+---------------------------+     +-----------------------+
| 3. Match                  |<----| Local vuln DB         |
|  ecosystem version rules  |     |  distro trackers +    |
|  (Debian vs npm semver)   |     |  language advisories  |
+-------------+-------------+     +-----------------------+
              |
              v
+---------------------------+
| 4. Report                 |
|  ID, severity, fixed ver. |
+---------------------------+

Trivy and Grype both unpack the image, inventory packages, match them against a local vulnerability database and report findings, so any software that never reaches the inventory step is never reported.

Trivy vs Grype: what is the real difference in scope?

Both tools match the packages they detect against vulnerability data, but they are built on different ideas of what a scanner should do.

Trivy is a general-purpose security scanner. One binary scans container images, filesystems and Git repositories. It also checks infrastructure-as-code for misconfigurations, finds hardcoded secrets and generates SBOMs. Grype does one job: it matches packages against known vulnerabilities. SBOM generation is handled by Syft, a separate tool. Grype can scan an image directly because it includes Syft's cataloguing code as a library. Running Syft on its own is what lets you produce, store and reuse the SBOM as a separate artifact.

Concern Trivy Grype + Syft
Binaries to install and pin One Two (or one if Grype catalogues internally)
Scan types Vulnerabilities, misconfig, secrets, licences, SBOM Vulnerabilities (Grype), SBOM (Syft)
Config surface One large config covering many scanners Two smaller, focused configs
Upgrade path One release can change several behaviours at once Each tool upgrades independently
Learning curve Wide feature set and many flags Narrow tools, simpler mental model

With Trivy, you manage less tooling but more surface area. A single upgrade can change secret detection and vulnerability results in the same release, so you need to test both. With Grype and Syft, you pin and monitor two tools. In return, a change to SBOM cataloguing is isolated from changes in matching logic.

Pick Trivy if you want one tool to cover image, IaC and secret checks, and your team has no other scanners for those jobs. Pick Grype and Syft if SBOMs are a first-class artifact in your pipeline, or if you already use other tools for misconfiguration and secret scanning.

How should you use SBOMs with Trivy or Syft and Grype?

An SBOM records which packages are in an image at build time, and that list does not change after you push. The vulnerability data does change, because new CVEs are published against packages you already shipped. Separating these two facts lets you generate the inventory once and match it against fresh advisories as often as you like.

Generate once, at build time

Produce the SBOM in the same job that builds the image, while the image is still local. With Syft, syft <image> -o cyclonedx-json (or -o spdx-json) writes the inventory. With Trivy, trivy image --format cyclonedx --output sbom.json <image> does the same. Store the file next to the image, either as a build artifact keyed by image digest or attached to the image in the registry. Key it by digest, not tag, so a rescan always refers to exactly what was deployed.

Rescan the SBOM, not the image

When you check later, scan the stored file. Use grype sbom:./sbom.json or trivy sbom sbom.json. Neither command pulls layers or unpacks a filesystem. It reads a package list and queries the local vulnerability database.

The Syft/Grype split makes this explicit. Syft only catalogs and Grype only matches, so the SBOM is necessarily the contract between the two tools. Trivy supports the same workflow, but because one command can do both steps, teams often never separate them.

For a nightly job across hundreds of deployed images, this approach avoids pulling each image from the registry. Scans finish in seconds per image, and you can rescan old releases even after their images have been garbage-collected.

#!/usr/bin/env bash
set -euo pipefail

IMAGE="registry.example.com/shop/api:1.4.2"

# --- Build time: inventory the image while it is still local ---
docker build -t "$IMAGE" .
docker push "$IMAGE"

# Key the SBOM by digest, not tag, so a rescan refers to exactly what shipped
DIGEST=$(docker inspect --format '{{index .RepoDigests 0}}' "$IMAGE" | cut -d@ -f2)
mkdir -p sboms

# Option A: Syft catalogs only, then writes CycloneDX JSON to stdout
syft "$IMAGE" -o cyclonedx-json > "sboms/${DIGEST}.cdx.json"

# Option B: Trivy produces the same kind of inventory
# trivy image --format cyclonedx --output "sboms/${DIGEST}.cdx.json" "$IMAGE"

# Store sboms/ as a build artifact, or attach it to the image in the registry

# --- Later (e.g. nightly): rescan stored SBOMs, no image pull ---
grype db update   # refresh advisories once, then reuse the local DB for every file

for sbom in sboms/*.cdx.json; do
  echo "== ${sbom}"
  # Grype matches the package list against current vulnerability data
  grype "sbom:${sbom}" --fail-on high || echo "high+ findings in ${sbom}"

  # Trivy equivalent: read the SBOM, not the image
  # trivy sbom --severity HIGH,CRITICAL --exit-code 1 "$sbom"
done

A build job writes a CycloneDX SBOM keyed by image digest with Syft or Trivy, and a scheduled job later rescans the stored files with Grype or trivy sbom without pulling any image.

How do you gate CI builds on scan results without stalling every pipeline?

Neither tool fails a build by default. Trivy exits zero unless you pass --exit-code 1, and it applies that exit code only to findings that match --severity. Grype uses --fail-on <severity>, which fails on findings at or above that level. A Trivy step that blocks on fixable criticals combines --exit-code 1 --severity CRITICAL --ignore-unfixed. The Grype equivalent is --fail-on critical --only-fixed. The CI configurations below show both steps in full.

The "fixed" filter decides how much friction the gate creates. If you block on unfixed CVEs, builds can stall until an upstream maintainer ships a patch, and the developer has nothing to change in the meantime. If you drop unfixed findings everywhere, you can miss real exposure. Gate on fixable findings, and keep a separate non-blocking report that includes unfixed ones so someone tracks them.

Roll the gate out in stages:

  1. Run the scan in report-only mode for a few weeks so you can see the baseline noise.
  2. Block on critical findings that have fixes.
  3. Consider adding high-severity findings once the backlog is manageable.

A gate can break without any change to the image. A new CVE entry in the database or a scanner upgrade that improves package detection can turn yesterday's passing image into a failure. Pin the scanner version, and treat database-driven failures as new information rather than flakiness.

To keep output useful, write JSON or SARIF to a separate output file for code-scanning dashboards and PR annotations. Print table output to the job log so engineers can read results without downloading artifacts.

#!/usr/bin/env bash
# CI scan step: always produce reports, and block only when GATE_MODE=block.
# Pin scanner versions in your CI image so upgrades are deliberate.
set -euo pipefail

IMAGE="registry.example.com/team/app:${CI_COMMIT_SHA:-local}"
GATE_MODE="${GATE_MODE:-report}"   # stage 1: report, stage 2: block

# --- Report pass: full picture, including unfixed CVEs. Never fails the job.
# Machine-readable output goes to files for dashboards and PR annotations.
trivy image --format sarif --output trivy.sarif --exit-code 0 "$IMAGE"
grype "$IMAGE" -o sarif --file grype.sarif

# Human-readable table in the job log, including unfixed findings.
trivy image --format table --severity HIGH,CRITICAL --exit-code 0 "$IMAGE"

if [ "$GATE_MODE" != "block" ]; then
  echo "Report-only mode: not gating on findings."
  exit 0
fi

# --- Gate pass: fail only on critical findings that have a fix available.
# Trivy: exit code 1 applies only to findings matching --severity.
trivy image --format table \
  --severity CRITICAL --ignore-unfixed --exit-code 1 \
  "$IMAGE"

# Grype equivalent: fail on critical or above, ignoring unfixed findings.
grype "$IMAGE" -o table --only-fixed --fail-on critical

# Stage 3 (later): widen to HIGH once the backlog is manageable, e.g.
#   trivy ... --severity HIGH,CRITICAL   /   grype ... --fail-on high

A CI shell step that always writes SARIF reports and a log table, then gates on fixable critical findings with Trivy and Grype once GATE_MODE is switched from report to block.

How should you cache the vulnerability database in CI?

Both tools pull a vulnerability database before they scan. Trivy downloads its DB into its cache directory, which you can set with --cache-dir or TRIVY_CACHE_DIR. Grype keeps its DB in a directory you can set with GRYPE_DB_CACHE_DIR. On ephemeral runners that download happens on every job. It adds time to each run, and it fails whenever the upstream registry rate-limits you or goes down. At high pipeline concurrency, rate limiting is the more common cause of flaky failures than real outages.

Persist that directory with your CI system's cache mechanism. Key the cache on a time bucket, such as the current date, so it refreshes on a predictable schedule rather than never. A better pattern is to update the DB in one scheduled job and have scan jobs read it without fetching:

  • Trivy: scan jobs use --skip-db-update. If your network blocks the default registry or you hit its rate limits, --db-repository lets you pull the DB from an internal mirror instead.
  • Grype: run grype db update once, then set GRYPE_DB_AUTO_UPDATE=false in the scan jobs.

Caching introduces a risk: stale data hides new CVEs. A scan against a week-old database can pass an image that is vulnerable today. Treat DB age as an explicit gate. Grype enforces a maximum age through GRYPE_DB_VALIDATE_AGE and GRYPE_DB_MAX_ALLOWED_BUILT_AGE, and it errors when the DB is older than that. With Trivy, fail the job when the DB update fails instead of continuing with whatever is cached.

Decide the policy up front. For example, a branch build might warn on a stale or missing DB, while a release build fails on it. What you should avoid is a scan that quietly produces no findings because the database was never loaded.

#!/usr/bin/env bash
# Runs inside a CI job. Restore ./.cache from the CI cache before this step,
# keyed on a time bucket such as the date (for example db-2026-11-08).
set -euo pipefail

IMAGE="registry.example.com/team/app:1.4.2"
export TRIVY_CACHE_DIR="$PWD/.cache/trivy"
export GRYPE_DB_CACHE_DIR="$PWD/.cache/grype"

# Policy is explicit: release pipelines set STRICT_DB=true, branch builds do not.
STRICT="${STRICT_DB:-false}"

db_problem() {
  if [ "$STRICT" = "true" ]; then
    echo "ERROR: $1, failing the build" >&2
    exit 1
  fi
  echo "WARNING: $1, results come from the cached DB and may miss new CVEs" >&2
}

# Refresh step. Run it in a scheduled job, or once per pipeline.
# A failed download is reported and never ignored.
trivy image --download-db-only || db_problem "Trivy DB download failed"
grype db update || db_problem "Grype DB update failed"

# Trivy scan: read the cached DB without fetching it.
# Trivy errors out if no DB is present, so an empty scan cannot pass.
trivy image --skip-db-update --exit-code 1 --severity HIGH,CRITICAL "$IMAGE"

# Grype scan: no auto-update. Grype errors if the DB is older than the max age.
# In branch mode, validation follows STRICT so a stale DB only produces the warning above.
export GRYPE_DB_AUTO_UPDATE=false
export GRYPE_DB_VALIDATE_AGE="$STRICT"
export GRYPE_DB_MAX_ALLOWED_BUILT_AGE=72h
grype "$IMAGE" --fail-on high

A CI scan step that restores a cached Trivy and Grype database, refreshes it once, scans without fetching again, and makes a failed or stale database update a deliberate fail or warn decision based on build type.

How do you manage suppressions, false positives and triage?

Most scanner noise comes from three places. Vendors dispute some CVEs or rate them lower than the upstream advisory. Some flagged functions sit in code paths your service never calls. And distributions often backport a fix without bumping the upstream version, so a version-matching rule reports a package as vulnerable when it is already patched. Each finding takes minutes to investigate. When the same ones come back on every run, engineers learn that red output doesn't mean anything. With strict gating and no triage process, the usual result is that someone sets the exit code to zero "temporarily," and the scanner stays disabled.

Make every suppression accountable

Keep an ignore file in the repository. Each entry should record four things: the vulnerability ID, a written reason, an owner, and an expiry date. Trivy and Grype each have their own ignore format, so check which fields your tool actually enforces. Where it doesn't support owner or expiry natively, put them in a comment and have a CI step fail on entries past their date. Reasons like "not reachable: we never parse untrusted XML" or "fixed in distro backport" let the next reviewer re-check the claim instead of starting over.

For risks you accept across many images, use VEX-style statements. A VEX statement declares that a component is "not affected," along with a justification, and the scanner reads it so the finding stops appearing on every run.

Ignore files decay because the code changes while the entries stay the same. A path that was unreachable last quarter may be called today. Review the file on a fixed schedule. Expiry dates make that review happen, because an expired entry fails the build until someone looks at it again.

When should you scan, and when is one of these tools the wrong choice?

Scan in three places. Pull requests get a fast scan of the changed image, so authors see new findings while the change is still small. The build step scans again before push, so nothing unscanned reaches the registry. A scheduled job rescans deployed images or their stored SBOMs, because new CVEs are published against images that haven't changed. That scheduled job produces alerts nobody asked for, so assign an owner before you turn it on. Without one, the alerts pile up and get ignored.

Skip Trivy if you only want vulnerability matching and the extra scanners (misconfiguration, secrets, licenses) would duplicate tools you already run. Skip Grype if you want one binary to cover all of those. Running both costs extra CI time and a second triage queue. It pays off only if you act on the differences between them. A registry's built-in scanning covers the scheduled case with no pipeline work, but it usually reports after push and gives you less control over gating. SBOM-only workflows suit teams that store SBOMs centrally and rescan those instead of pulling images.

Before choosing, run both tools against a representative set of your production images and compare the findings. Where they disagree, the cause is usually package detection or advisory data. Those gaps are what you would inherit by picking one.

Situation Reasonable choice
Small team, one pipeline, wants broad coverage Trivy alone
SBOM-centric workflow, separate IaC tooling Syft plus Grype
Platform team, many services, audit pressure Both, with scheduled SBOM rescans
Minimal CI effort, findings after push are acceptable Registry scanning

How OneEnv can help

Disclosure: OneEnv is the product behind this blog.

OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.

Applied to trivy vs grype, this is where it helps:

Saves time

  • Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
  • One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
  • Changing a shared variable is one edit and one review instead of editing every service's .env by hand.

Saves cost

  • Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
  • Less duplicated configuration to maintain: one shared definition inherited by many services.
  • A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
  • OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.

These are qualitative benefits, not measured results — how much you save depends on how many services share the value.

Want to try it? Start at oneenv.io.