What are Trivy and Grype, and how do their scopes differ?
Trivy and Grype both match the packages inside a container image against known vulnerability data, but their scopes differ. Grype only matches vulnerabilities. It pairs with Syft, a separate tool that builds a software bill of materials (SBOM). Grype can scan an image directly, cataloguing packages internally, or it can take a Syft SBOM as input. Trivy puts vulnerability, misconfiguration, secret and license checks in one binary, and it can generate SBOMs itself.
This shapes pipeline design. With Trivy you have one binary to pin, one database cache and one config surface. The cost is a wider blast radius: a single upgrade or config change affects every check type at once. With Grype and Syft, you generate the SBOM once at build time, store it as an artifact, and re-scan it later as new CVEs are published, without pulling the image again. The cost is a second tool to pin, update and cache.
| Trivy | Grype (+ Syft) | |
|---|---|---|
| Scope | Vulnerabilities, misconfiguration, secrets, licenses | Vulnerabilities only; Syft handles cataloguing |
| SBOM handling | Generates and scans CycloneDX/SPDX | Syft generates; Grype scans SBOMs as input |
| Ignore mechanism | .trivyignore file, VEX |
Ignore rules in .grype.yaml, VEX |
| Output formats | Table, JSON, SARIF, CycloneDX, SPDX, templates | Table, JSON, SARIF, CycloneDX, templates |
Trivy fits teams that want one scanner across many check types. Grype fits teams that want SBOM generation kept separate from vulnerability matching.
How does container vulnerability scanning work under the hood?
Both tools work in two phases. First they build an inventory. They unpack the image layers into a merged filesystem view and read package manager databases, such as dpkg status files, the RPM database, or apk's installed list, to find OS packages. Then they walk the filesystem for language artifacts: lockfiles, JAR metadata, Python site-packages, and the module information embedded in Go binaries. Grype delegates this step to Syft, while Trivy does it internally. In the second phase, each package name and version is matched against an advisory database compiled from distro security trackers, language ecosystem advisories and NVD.
Results for the same image can diverge at every step. One cataloger may find a JAR nested inside a fat JAR that the other misses. For OS packages, the distro's own tracker is the authoritative source because it records backported fixes and "not affected" decisions that upstream version numbers do not show. Tools that weigh vendor data against NVD differently will disagree. Version comparison rules also differ between dpkg, RPM, semver and PEP 440.
This makes finding counts a poor basis for comparison. A higher count often means more "won't fix" or disputed entries. Counts also change from week to week as databases update, even when the image has not changed.
Scanners only see what is recorded somewhere they can read. Common blind spots include:
- Statically linked C or Rust binaries that carry no dependency metadata
- Vendored source code
- Tools added with
COPYorcurlinstead of a package manager scratchimages that have no package database at all
A clean report is not proof that the image has no vulnerabilities. A critical severity rating also does not mean the vulnerable code is reachable in your deployment.
Where should container scanning run in a CI pipeline?
Each scan point answers a different question, so most pipelines need more than one.
On pull requests, the goal is fast feedback. Scan the image the PR builds and report findings as a comment or check, but limit blocking to issues the change introduced. A developer who bumps a base image tag should learn about it before merge, not after release.
Before pushing to a registry, the scan becomes a gate. Anything that reaches the registry can be deployed, so this is where policy is enforced: the job fails and the image is never published.
On a schedule against deployed images, you catch vulnerabilities disclosed after the build. An image that passed last month may fail today with no change to the image, because the vulnerability database changed. Without a scheduled scan, nothing tells you that production images are now exposed.
The scheduled scan is cheaper with an SBOM-first flow. Generate the SBOM once at build time, in CycloneDX or SPDX format, and store it with the image. That can be an artifact attached to the image in the registry, or a file stored under the image digest. Later scans read the SBOM against a fresh database, so you do not rebuild the image or pull it again. Both Trivy and Grype accept an SBOM as input.
This also reduces CI attack surface. A job that scans a saved image tarball or an SBOM does not need access to the Docker socket or registry credentials. Access to the Docker socket is effectively root on the runner host. Keep those privileges in the build job, and give the scan job only the files it reads.
PULL REQUEST MAIN BRANCH / RELEASE
+----------------------+ +------------------------------+
| PR build | | Build job (privileged) |
| -> image.tar | | Docker socket, push creds |
+----------+-----------+ | -> image.tar + SBOM |
| | (CycloneDX or SPDX) |
v +---------------+--------------+
+----------------------+ | files only
| PR scan (tarball) | v
| comment / check | +------------------------------+
| block only on issues | | Gate scan (tarball) |
| this PR introduced | | no socket, no creds |
+----------------------+ | policy fail -> never pushed |
+---------------+--------------+
| pass
v
+------------------------------+
| Registry |
| image@digest + SBOM artifact |
+---------------+--------------+
| SBOM only
SCHEDULE (e.g. nightly) v
+----------------------+ +------------------------------+
| Fresh vuln database +------------>| Scheduled scan of SBOM |
| (updated often) | | no rebuild, no image pull |
+----------------------+ | alert: new CVEs in prod |
+------------------------------+
The pipeline has three scan points: PR scans for fast feedback, a pre-push gate, and scheduled rescans of the stored SBOM against a fresh database. Only the build job holds the Docker socket and registry credentials.
How do you handle vulnerability database updates and caching in CI?
Both scanners fetch a vulnerability database before they scan. That download happens on every run unless you cache it. On ephemeral runners, the cache is lost each time, so each job re-downloads the database before it can do any scanning.
Cache once, scan many
Run a small job that refreshes the database and saves the scanner's cache directory with your CI system's cache mechanism. Scan jobs then restore that cache and run with automatic updates turned off. Key the cache on the date, not on the commit, so every pipeline that day shares one copy. Updating once or twice a day is enough for most teams. Advisories rarely require response times measured in minutes.
As an illustrative estimate: if the download adds 30 seconds to each scan and you run 2,000 scans a month, caching saves roughly 16 runner-hours a month.
Transient failures
A failed database download should not block merges. Retry the refresh job. If it still fails, fall back to yesterday's cache and log a warning. Set a maximum database age, for example three days, and fail the build only when the cache is older than that.
Freshness versus reproducibility
A new advisory can make Tuesday's run fail on the same commit that passed Monday. That is the scanner working as intended, but it confuses developers. Record the database build timestamp in every scan report so a failure can be traced to new data rather than new code. For release audits, pin and archive the exact database you scanned with.
Air-gapped runners
Mirror the database into an internal registry or artifact store from a host with internet access. Point offline runners at that mirror, and apply the same maximum-age check to it.
#!/usr/bin/env bash
# Run as two CI jobs: `db-refresh.sh refresh` once a day, then `db-refresh.sh scan` per pipeline.
# Your CI cache step saves/restores $CACHE, keyed on the date (e.g. scanner-db-2026-11-07).
set -euo pipefail
CACHE="${CACHE:-$PWD/.scanner-cache}"
IMAGE="${IMAGE:-registry.example.internal/app:1.4.2}"
export GRYPE_DB_CACHE_DIR="$CACHE/grype"
# Grype refuses a database built more than 3 days ago (the max-age rule).
export GRYPE_DB_VALIDATE_AGE=true
export GRYPE_DB_MAX_ALLOWED_BUILT_AGE=72h
retry() { # Retry transient download failures with a growing pause.
for n in 1 2 3; do "$@" && return 0; sleep $((n * 15)); done
return 1
}
if [ "${1:-}" = "refresh" ]; then
# On failure, keep the restored (older) cache and warn instead of blocking merges.
retry trivy image --download-db-only --cache-dir "$CACHE/trivy" \
|| echo "WARNING: Trivy DB refresh failed; using cached copy"
retry grype db update \
|| echo "WARNING: Grype DB refresh failed; using cached copy"
exit 0
fi
# Scan jobs never download: they use only the restored cache.
# Record which database was used so a new failure can be traced to new data, not new code.
grype db status | tee scan-db-info.txt
trivy image --skip-db-update --cache-dir "$CACHE/trivy" \
--severity HIGH,CRITICAL --exit-code 1 "$IMAGE"
GRYPE_DB_AUTO_UPDATE=false grype "$IMAGE" --fail-on high
A two-mode CI script that refreshes both scanners' databases once into a date-keyed cache with retries and fallback, then runs scans offline against that cache while enforcing a maximum Grype database age and logging which database version was used.
How do you build a CI security gate developers will tolerate?
Gate on what a developer can act on today. For Trivy, that means trivy image --severity HIGH,CRITICAL --ignore-unfixed --exit-code 1 <image>. For Grype, the equivalent is grype <image> --only-fixed --fail-on high. Here --fail-on high trips on High and anything above it. Both tools exit zero by default even when they find vulnerabilities, so set these flags explicitly. Without them, the scan step passes no matter what the scanner reports.
A scanner error, such as a failed database download or an unreachable registry, also produces a non-zero exit. Have the job print its findings report so a red build shows the cause directly. Developers should not have to tell a CVE failure from an infrastructure failure by reading raw logs.
Exceptions with an owner
Exceptions should live in version control next to the code:
- Trivy: add the CVE ID on its own line in
.trivyignore. - Grype: add an entry under
ignore:in.grype.yaml, for example- vulnerability: CVE-....
Require a comment on every entry with a reason, an owner and a review date. Enforce this in code review or with a small lint step. An entry without context stays in the file long after anyone remembers why it was added.
Why fixable-only matters
If a pipeline fails on unfixable CVEs, developers cannot fix the problem. Their only way to unblock the build is to suppress it, and they will reach for the broadest suppression available. Over time the ignore file turns into a list of everything, and the gate stops catching anything.
Track unfixed findings in a non-blocking report instead. Then reduce noise in one of two ways:
- VEX documents: both tools can consume VEX statements that mark a CVE as not affecting your image.
- Scheduled manual triage: review unfixed findings on a regular cadence rather than in the critical path of every merge.
#!/usr/bin/env bash
# CI gate: fail only on fixable HIGH/CRITICAL findings, and require every
# suppression to carry a reason, owner and review date.
set -euo pipefail
IMAGE="${IMAGE:-registry.example.com/team/app:1.4.2}"
# Ignore-file convention (comment line directly above each entry):
# .trivyignore:
# # reason: not reachable, no TLS in this image | owner: @alice | review: 2027-01-15
# CVE-2024-12345
# .grype.yaml:
# ignore:
# # reason: not reachable, no TLS in this image | owner: @alice | review: 2027-01-15
# - vulnerability: CVE-2024-12345
# Lint: reject any entry whose preceding line lacks reason/owner/review.
lint() { # $1 = file, $2 = regex matching an entry line
[ -f "$1" ] || return 0
awk -v pat="$2" -v f="$1" '
$0 ~ pat && (prev !~ /reason:/ || prev !~ /owner:/ || prev !~ /review:/) {
print f ": entry needs reason/owner/review comment: " $0; bad=1 }
{ prev = $0 }
END { exit bad }' "$1"
}
lint .trivyignore '^CVE-'
lint .grype.yaml 'vulnerability:'
# Both scanners exit 0 on findings unless told otherwise; set gating flags
# explicitly. The default table output stays in the job log, so a red build
# shows either the CVE list or the scanner error that caused it.
trivy image --severity HIGH,CRITICAL --ignore-unfixed --exit-code 1 "$IMAGE"
# Grype reads .grype.yaml from the working directory automatically.
grype "$IMAGE" --only-fixed --fail-on high
A CI script that lints .trivyignore and .grype.yaml so every suppression carries a reason, owner and review date, then runs Trivy and Grype with flags that fail the build only on fixable HIGH and CRITICAL vulnerabilities.
Which output formats should you use for humans, scripts and dashboards?
Both tools can emit the same scan in several formats. Pick the format based on who or what reads it.
| Format | Primary reader | Strength | Weakness |
|---|---|---|---|
| Table | Humans in CI logs | Quick to scan, shows package, installed and fixed version | Unreadable at hundreds of rows, hard to parse |
| JSON | Scripts, policy checks, diffing | Complete, stable structure, easy to filter and compare | Too verbose to read directly |
| SARIF | Code-scanning dashboards | Findings tracked over time, deduplicated across runs | Loses some package detail, depends on your dashboard's handling |
A base image with hundreds of findings turns a table into a wall of text, and reviewers stop reading it. Keep the log short in three ways:
- Severity filters: print only the severities that can fail the build, usually high and critical. A medium finding nobody acts on adds noise to the log.
- A baseline: compare the JSON report against the previous accepted scan and show only new findings. A reviewer of a dependency bump then sees what that change introduced, not every issue the image inherited.
- Summary in the log, full report as an artifact: write counts by severity plus the new findings to the job log, and store the full JSON and SARIF as build artifacts. Anyone investigating can still get the complete data.
This saves reviewer time because the log answers the one question that matters during review: did this change make the image worse? It also prevents alert fatigue. If developers see the same unchanged list of findings on every run, they learn to scroll past the scan step, including on the run where something new and exploitable appears.
#!/usr/bin/env bash
# Scan once, keep the CI log short, and store full reports as artifacts.
set -euo pipefail
IMAGE="registry.example.com/team/app:${CI_COMMIT_SHA:-dev}"
OUT=reports
BASELINE=baseline/trivy.json # JSON from the last accepted scan
mkdir -p "$OUT"
# Full scan at every severity. This JSON file is the source of truth.
trivy image --quiet --format json --output "$OUT/trivy.json" "$IMAGE"
# Convert the same results to SARIF for the code-scanning dashboard, without rescanning.
trivy convert --format sarif --output "$OUT/trivy.sarif" "$OUT/trivy.json"
# Log only counts per severity, not hundreds of table rows.
echo "== Findings by severity =="
jq -r '[.Results[]?.Vulnerabilities[]?.Severity] | group_by(.) | map("\(.[0]): \(length)") | .[]' "$OUT/trivy.json"
# List HIGH/CRITICAL findings as sorted "ID package" keys so two scans can be compared.
keys() {
jq -r '.Results[]?.Vulnerabilities[]?
| select(.Severity == "HIGH" or .Severity == "CRITICAL")
| "\(.VulnerabilityID) \(.PkgName)"' "$1" | sort -u
}
# Without a baseline, every finding counts as new.
if [[ -f "$BASELINE" ]]; then
NEW=$(comm -13 <(keys "$BASELINE") <(keys "$OUT/trivy.json"))
else
NEW=$(keys "$OUT/trivy.json")
fi
if [[ -n "$NEW" ]]; then
echo "== New HIGH/CRITICAL findings introduced by this change =="
echo "$NEW"
echo "Full report: $OUT/trivy.json (job artifact)"
exit 1
fi
echo "No new HIGH/CRITICAL findings compared to the baseline."
A CI step that runs Trivy once and saves the full JSON and SARIF reports as artifacts. The log shows only severity counts and the high or critical findings that are new since the baseline, and the build fails only when this change adds one.
When should you avoid relying on Trivy or Grype alone, and how do you choose between them?
Both tools find vulnerabilities by matching package metadata against advisory data. When that metadata is missing or wrong, the scan is incomplete and still reports success.
Where a scanner alone falls short
- Static or vendored builds. A C library compiled into a binary, a dependency copied into the repository, or a binary installed with
curland no package manager leaves no record that either tool can match. An empty result here means the scanner had nothing to inspect. - Exploitability and reachability. CVE matching shows that a vulnerable version is present. It does not show that your code calls the affected function. To prioritise, you need reachability analysis or human judgement.
- Compliance beyond CVEs. Licence policy, image provenance, base-image approval and evidence for auditors need their own controls.
For the gaps, consider these options:
- Use a second open-source scanner with different matching logic.
- Use registry-side scanning, which re-checks stored images as new advisories appear.
- Manually review anything built from source.
A selection method
- Run both tools on 10–20 representative images.
- Diff the overlapping and unique findings.
- Hand-check the unique findings for false positives.
- Time warm-cache scans on your own runners.
| Criterion | What to record |
|---|---|
| Unique true positives | Count per tool after manual review |
| False positives | Count per tool |
| Warm-cache scan time | Median seconds per image |
| Triage effort | Minutes per finding |
Illustrative estimate. These inputs are assumed:
- 15 images
- 4 hours to run both tools and review the results
- One tool produces 3 fewer false positives per week
- 20 minutes of triage per false positive
The lower-noise tool saves 60 minutes a week, so the 4-hour evaluation pays for itself in about a month.
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.
- Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.
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.
- Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
- 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.