Skip to main content

Containers and Kubernetes · Intermediate · 17 min

Scan container images for vulnerabilities with Trivy

By Padding · Updated 18 Nov 2026
Ubuntu 26.04.1 LTS · Trivy 0.76.2

You will install Trivy 0.76 from Aqua's signed apt repository, scan a pinned public image straight from the registry, turn the report into a CI gate with severity filters, an ignore file with reasons and review dates, and misconfiguration checks for a Dockerfile and a Kubernetes manifest, then run the same scan in a GitHub Actions job with a cached database.

On this page

A container image carries a whole operating system's worth of packages, and every one of them can have known security holes. Trivy, an open-source scanner from Aqua Security, reads the package lists inside an image, matches them against a vulnerability database and tells you which packages are affected, how badly, and which version fixes them. It also checks Dockerfiles and Kubernetes manifests for risky settings.

In this tutorial you will scan a deliberately old Alpine image, learn to read the report, filter it down to what you can act on, make it fail a build, record an accepted risk properly, check configuration files, and finish with a GitHub Actions job that does all of this on every pull request. Trivy reads images straight from the registry, so you do not need Docker installed.

The numbers in your reports will differ from the ones described here. New vulnerabilities are published every day and the database is rebuilt every few hours, so treat every count below as "something like".

Step 1 · Install Trivy from Aqua's apt repository

Install Trivy from its vendor repository, with a key that may sign that repository only. Add a third-party apt repository safely explains each line and adds a pin that stops the repository replacing Ubuntu's own packages; follow it if you have not added a vendor repository before. The short version is:

Bash
sudo apt-get update
sudo apt-get install -y ca-certificates curl gpg jq
curl -fsSL https://aquasecurity.github.io/trivy-repo/deb/public.key -o /tmp/trivy-repo.asc
expected=825AD9036F7C850E6A6FED4935B8ACA44FD9CA9F
actual=$(gpg --show-keys --with-colons /tmp/trivy-repo.asc | awk -F: '$1 == "fpr" { print $10; exit }')
if [ "$actual" = "$expected" ]; then echo "OK: fingerprint matches"; else echo "STOP: fingerprint is $actual"; false; fi

The fingerprint above is the one in the SignWith: line of deb/conf/distributions in the aquasecurity/trivy-repo project on GitHub, read on 26 November 2026. Open that file yourself and compare, because the point is to check the key against a second source. Only continue when the script prints OK. Then store the key and describe the repository:

Bash
sudo install -d -m 0755 /etc/apt/keyrings
sudo install -m 0644 /tmp/trivy-repo.asc /etc/apt/keyrings/trivy-repo.asc
rm /tmp/trivy-repo.asc
sudo tee /etc/apt/sources.list.d/trivy.sources > /dev/null <<EOF
Types: deb
URIs: https://aquasecurity.github.io/trivy-repo/deb
Suites: generic
Components: main
Architectures: $(dpkg --print-architecture)
Signed-By: /etc/apt/keyrings/trivy-repo.asc
EOF
sudo apt-get update
sudo apt-get install -y trivy

Checking the key matters more than usual for this tool. In March 2026 attackers published a malicious Trivy release and rewrote the tags of the official GitHub Actions for a few hours. A scanner runs with access to your images and your CI secrets, so install it the careful way.

Check it worked

Bash
trivy --version

It prints something like Version: 0.76.2. Upgrades now arrive with sudo apt update && sudo apt upgrade.

Step 2 · Scan a pinned image straight from the registry

Make a folder for this tutorial and scan alpine:3.18.0, an Alpine release from May 2023. It is small (about 3 MB) and old enough to have plenty of known problems, which makes it a good practice target:

Bash
mkdir -p ~/trivy-demo
cd ~/trivy-demo
trivy image alpine:3.18.0

The first run downloads the vulnerability database from mirror.gcr.io (with ghcr.io as the fallback) into ~/.cache/trivy. That database is the largest download in this tutorial; run du -sh ~/.cache/trivy afterwards to see how much it took. If you pay for data by the bundle, as many readers on prepaid mobile data do, do the first run on Wi-Fi: later scans reuse the cached copy and only fetch a fresh database when the old one is out of date.

Trivy looks for the image in a local Docker Engine, containerd and Podman first, and pulls it from the registry when none of those has it. To make that explicit, add --image-src remote. Docker Hub limits anonymous pulls per IP address; if you hit the limit, log in with trivy registry login docker.io.

A tag such as 3.18.0 can in principle be moved. For a scan you need to repeat exactly, use the digest instead, in the form alpine@sha256:<digest>; the report header prints the digest Trivy actually scanned.

Check it worked

The output starts with a few log lines, including a warning something like This OS version is no longer supported by the distribution: Alpine 3.18 reached end of life in May 2025 and gets no more fixes. Then comes a table headed alpine:3.18.0 (alpine 3.18.0) with a Total: line that counts findings per severity, and rows for packages such as libcrypto3, libssl3 and busybox.

Step 3 · Read the report

Each row is one vulnerability in one package. The columns are:

  • Library: the package inside the image, for example libssl3. One upstream project often ships several packages, so the same CVE can appear on libcrypto3 and libssl3.
  • Vulnerability: the identifier, usually a CVE number such as CVE-2023-5363. Distributions sometimes use their own IDs.
  • Severity: CRITICAL, HIGH, MEDIUM, LOW or UNKNOWN. Trivy prefers the distribution's own rating and falls back to others such as NVD.
  • Status: fixed means a patched package exists. affected, will_not_fix, fix_deferred and end_of_life mean there is nothing to upgrade to yet, or ever.
  • Installed Version and Fixed Version: what the image has and the first version without the problem.
  • Title: a one-line description and a link with details.

Tables are for people. For scripts, ask for JSON and query it with jq. List the packages with fixable high and critical findings, with the version that fixes each:

Bash
trivy image --quiet --format json --output old.json alpine:3.18.0
jq -r '.Results[].Vulnerabilities[]? | select(.Severity == "HIGH" or .Severity == "CRITICAL") | "\(.Severity)\t\(.PkgName) \(.InstalledVersion) -> \(.FixedVersion)\t\(.VulnerabilityID)"' old.json | sort -u

Check it worked

You see lines something like HIGH libssl3 3.1.0-r4 -> 3.1.4-r0 CVE-2023-5363. Find CVE-2023-5363 in your list: it is fixed in OpenSSL 3.1.4-r0 on Alpine 3.18. Every fixed version Trivy names is a newer Alpine package, which tells you the fix is to rebuild on a newer base rather than to patch anything by hand.

Step 4 · Filter the report and make it a build gate

A full report is useful once. A build gate needs a rule you can defend, such as "no high or critical issue that has a fix". Three flags express that:

  • --severity HIGH,CRITICAL hides everything below high.
  • --ignore-unfixed hides findings with no fixed version yet. It is shorthand for --ignore-status affected,will_not_fix,fix_deferred,end_of_life.
  • --exit-code 1 makes Trivy exit with status 1 when anything is left, which fails a CI job.

Alpine publishes fixes rather than open issues, so on this image --ignore-unfixed removes little. On Debian and Ubuntu images it usually hides many affected and will_not_fix rows that you cannot act on. Keep those visible in a separate, non-blocking report if your security team wants them.

Run the gate on the old image:

Bash
trivy image --quiet --severity HIGH,CRITICAL --ignore-unfixed --exit-code 1 alpine:3.18.0 || echo "Gate failed with exit code $?"

Now scan a current Alpine release, the fix the report pointed to:

Bash
trivy image --quiet --severity HIGH,CRITICAL --ignore-unfixed --exit-code 1 alpine:3.24.4 && echo "Gate passed"

Check it worked

The first command prints a short table and then Gate failed with exit code 1. The second should print an empty or near-empty table and Gate passed. If a fresh high finding has landed on Alpine 3.24 since this was written, it fails too; check whether 3.24.5 or later exists, because a new patch release is the usual answer. Without --exit-code, Trivy exits 0 whatever it finds, so a pipeline that only prints the report never stops anything.

Step 5 · Record accepted risks in a .trivyignore file

Sometimes a finding does not apply to how you use the package, and the fix is weeks away. Hiding it silently is how a team ends up with a scanner nobody trusts. Write it down instead: what you accept, why, who decided, and when to look again.

Trivy reads .trivyignore from the current folder. One ID per line, comments start with #, and exp: sets a date after which the entry stops applying. Here the example accepts CVE-2024-5535, an OpenSSL issue that only affects programs calling SSL_select_next_proto with an empty list, and which OpenSSL itself rated Low:

Bash
cat > ~/trivy-demo/.trivyignore <<'EOF'
# CVE-2024-5535 (libssl3, libcrypto3): OpenSSL rates it Low; it needs an empty
# protocol list passed to SSL_select_next_proto, which our service never does.
# Accepted by: platform team, 2026-11-18. Review by 2027-02-28.
CVE-2024-5535 exp:2027-02-28
EOF
cd ~/trivy-demo
trivy image --quiet --format json --output ignored.json alpine:3.18.0
jq '[.Results[].Vulnerabilities[]? | select(.VulnerabilityID == "CVE-2024-5535")] | length' old.json ignored.json

The reason in the example is a template: write the reason that is true for your service, and replace the team and dates. Keep the file in the same repository as the Dockerfile so every change to it goes through review. An expiry date turns "we will look at it later" into a gate that fails again on that day, which is exactly the reminder you want.

Check it worked

jq prints two numbers: something like 2 for the earlier report (one row each for libcrypto3 and libssl3) and 0 for the new one. The gate on alpine:3.18.0 still fails, because the other high findings are not in the file. That is correct: an ignore file is for single, explained exceptions, not for getting an old base image through.

Step 6 · Check a Dockerfile and a Kubernetes manifest

Vulnerable packages are one risk; risky settings are another. trivy config checks Dockerfiles, Kubernetes manifests, Helm charts and Terraform against a library of rules. Write a Dockerfile and a Deployment with some common mistakes:

Bash
mkdir -p ~/trivy-demo/app
cd ~/trivy-demo/app
cat > Dockerfile <<'EOF'
FROM alpine:latest
RUN apk add curl
COPY server /app/server
CMD ["/app/server"]
EOF
cat > deploy.yaml <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
spec:
  replicas: 1
  selector:
    matchLabels:
      app: web
  template:
    metadata:
      labels:
        app: web
    spec:
      containers:
        - name: web
          image: nginx:latest
          ports:
            - containerPort: 80
EOF
trivy config --severity HIGH,CRITICAL .

Trivy reads files only; it does not build the image or contact a cluster, so the server file does not need to exist.

Check it worked

The report has a section for each file. For the Dockerfile you see something like DS-0002 (HIGH): Specify at least 1 USER command in Dockerfile with non-root user as argument and DS-0025 (HIGH): '--no-cache' is missing from apk add command. For deploy.yaml you see several KSV- findings about the container running as root, a writable root filesystem and a missing security context. Each finding quotes the offending lines.

Step 7 · Fix the findings and scan again

Rewrite both files. The Dockerfile pins its base, keeps no package cache and runs as a non-root user. The Deployment runs an unprivileged Nginx image as a fixed non-root user, drops every Linux capability, makes the root filesystem read-only (with a writable /tmp, which Nginx needs) and sets resource limits:

Bash
cd ~/trivy-demo/app
cat > Dockerfile <<'EOF'
FROM alpine:3.24.4
RUN apk add --no-cache curl
COPY server /app/server
USER 10001:10001
HEALTHCHECK CMD curl -fsS http://127.0.0.1:8080/health || exit 1
CMD ["/app/server"]
EOF
cat > deploy.yaml <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
spec:
  replicas: 1
  selector:
    matchLabels:
      app: web
  template:
    metadata:
      labels:
        app: web
    spec:
      automountServiceAccountToken: false
      securityContext:
        runAsNonRoot: true
        runAsUser: 10001
        runAsGroup: 10001
        seccompProfile:
          type: RuntimeDefault
      containers:
        - name: web
          image: nginxinc/nginx-unprivileged:1.30-alpine
          ports:
            - containerPort: 8080
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities:
              drop: ["ALL"]
          resources:
            requests:
              cpu: 50m
              memory: 64Mi
            limits:
              cpu: 250m
              memory: 128Mi
          volumeMounts:
            - name: tmp
              mountPath: /tmp
      volumes:
        - name: tmp
          emptyDir: {}
EOF
trivy config --severity HIGH,CRITICAL --exit-code 1 Dockerfile && echo "Dockerfile passed"
trivy config --severity HIGH,CRITICAL deploy.yaml

Check it worked

The Dockerfile check prints Dockerfile passed. The manifest report is much shorter than before, and should have no high or critical findings left. Run trivy config . without the severity filter to see the medium and low suggestions, such as pinning the image by digest; decide which of those your team adopts before you make them blocking.

Step 8 · Run the scan in GitHub Actions with a cached database

In CI, two things matter: install a known Trivy build, and avoid downloading the full database on every run. The workflow below downloads the release .deb and checks it against the SHA-256 published with v0.76.2, so a tampered download stops the job. It keeps the database in a folder that actions/cache saves once a day, updates it once with --download-db-only, and then scans with --skip-db-update.

Save this as .github/workflows/trivy.yml in your repository. Replace alpine:3.24.4 with the image your project builds:

YAML
name: trivy
on:
  pull_request:
  push:
    branches: [main]
permissions:
  contents: read
jobs:
  scan:
    runs-on: ubuntu-latest
    env:
      TRIVY_VERSION: 0.76.2
      TRIVY_SHA256: 7edaf64c8a2a0ae02137f776c6e56adf285fc36ec76b045274afdc462f20f092
    steps:
      - uses: actions/checkout@v7
      - name: Install Trivy
        run: |
          deb="trivy_${TRIVY_VERSION}_Linux-64bit.deb"
          curl -fsSLO "https://github.com/aquasecurity/trivy/releases/download/v${TRIVY_VERSION}/${deb}"
          echo "${TRIVY_SHA256}  ${deb}" | sha256sum -c -
          sudo apt-get install -y "./${deb}"
      - name: Pick today's cache key
        id: day
        run: echo "date=$(date -u +%Y-%m-%d)" >> "$GITHUB_OUTPUT"
      - uses: actions/cache@v6
        with:
          path: .trivy-cache
          key: trivy-db-${{ steps.day.outputs.date }}
          restore-keys: trivy-db-
      - name: Update the vulnerability database
        run: trivy image --cache-dir .trivy-cache --download-db-only
      - name: Scan the image
        run: trivy image --cache-dir .trivy-cache --skip-db-update --severity HIGH,CRITICAL --ignore-unfixed --exit-code 1 alpine:3.24.4
      - name: Check the Dockerfile and manifests
        run: trivy config --cache-dir .trivy-cache --severity HIGH,CRITICAL --exit-code 1 .

The cache key changes each day, so the job saves a new copy at most once a day. On the other runs, restore-keys restores the most recent copy and --download-db-only only downloads when that copy is out of date. The job reads .trivyignore from the repository root, so your accepted risks apply in CI too. To move to a new Trivy release, change both TRIVY_VERSION and TRIVY_SHA256, taking the hash from the release's trivy_<version>_checksums.txt.

If you prefer Aqua's aquasecurity/trivy-action, pin it to a full commit SHA, not a tag: version tags are what the March 2026 attack rewrote. The same applies to any third-party action. Pinning actions/checkout and actions/cache by SHA as well is a stricter policy many teams adopt.

You can run the same commands on your own machine to see the cache at work:

Bash
cd ~/trivy-demo
trivy image --cache-dir .trivy-cache --download-db-only
trivy image --cache-dir .trivy-cache --skip-db-update --quiet --severity HIGH,CRITICAL --ignore-unfixed alpine:3.24.4
ls .trivy-cache

Check it worked

Locally, ls .trivy-cache shows a db folder, and the second command scans without the database download log line. On GitHub, open the pull request's Checks tab: the scan job's first run shows the database download, and a second run on the same day shows Cache restored from key: trivy-db-<date> in the actions/cache step. Change the image in the workflow to alpine:3.18.0 on a test branch and the Scan the image step fails with exit code 1, which blocks the merge once you make the check required in your branch protection rules.

When you are done, remove the practice folder and the cached database. Keep the apt repository if you will use Trivy again:

Bash
rm -rf ~/trivy-demo
trivy clean --all

Next steps

  • New to workflows, triggers and required checks: /tutorials/github-actions-first-workflow
  • Understand every line of the repository setup and add a pin: /tutorials/add-a-third-party-apt-repository-safely

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.