Trivy: CVE Scanning & SBOM
Scanning Images for CVEs
Trivy: One Tool for Everything
Trivy scans container images, Dockerfiles, Kubernetes manifests, and git repos for CVEs and misconfigurations. It's already installed in this environment.
trivy --version
Scan a Vulnerable Image
trivy image python:3.8 --severity HIGH,CRITICAL
The first run downloads the vulnerability database (~30 seconds). Expect 1600+ HIGH/CRITICAL CVEs — the Debian base image carries a huge attack surface.
Compare with Alpine
trivy image python:3.11-alpine --severity HIGH,CRITICAL
Expected: Significantly fewer results than python:3.8 — often zero or near-zero, though the exact count depends on the vulnerability database at the time you scan. CVEs are discovered continuously; even Alpine images may show some findings on any given day.
Alpine's minimal footprint and active patch cadence eliminate most OS-level CVEs compared to the Debian base.
The CI/CD Gate
With --exit-code 1, Trivy exits non-zero when it finds matching vulnerabilities. This is the hook that fails a pipeline build:
trivy image --exit-code 1 --severity CRITICAL --no-progress python:3.8
echo "Exit code: $?"
Expected: Exit code: 1
SBOM & Dockerfile Scanning
Software Bill of Materials
An SBOM is an inventory of every package in your software. Generate it once at build time, then re-scan it whenever a new CVE is disclosed — no need to rebuild or re-pull the image.
Generate an SBOM in SPDX format
trivy image --format spdx-json --output /tmp/python-sbom.spdx.json \
--no-progress python:3.8
echo "SBOM saved."
wc -l /tmp/python-sbom.spdx.json
Scan the SBOM directly
trivy sbom /tmp/python-sbom.spdx.json --severity HIGH,CRITICAL
The same vulnerabilities — but from a 30 KB JSON file instead of re-pulling the image.
Scanning Beyond Images
Trivy also catches misconfigurations in Dockerfiles and Kubernetes manifests.
Scan a bad Dockerfile
cat > /tmp/Dockerfile.test << 'EOF'
FROM ubuntu:latest
ENV SECRET_KEY=hardcoded_secret_123
USER root
CMD ["/bin/bash"]
EOF
trivy config /tmp/Dockerfile.test
Trivy flags: latest tag (unpinned), running as root, hardcoded secret in ENV.
Trivy Capabilities at a Glance
| What Trivy scans | Command |
|---|---|
| Image CVEs | trivy image <image> |
| SBOM generation | trivy image --format spdx-json |
| Scan existing SBOM | trivy sbom <file> |
| Dockerfile misconfigs | trivy config Dockerfile |
| Kubernetes manifests | trivy config pod.yaml |
| CI gate | trivy image --exit-code 1 --severity CRITICAL |
- Previous lesson
- Docker Image Hardening