
SKILL LEVEL: Intermediate.
Plenty of small organizations run their websites, wikis and internal tools as Docker containers on one or two self-hosted servers. The containers keep running, but their images get old, and nobody can say which of them contain a critical vulnerability that already has a fix. Commercial scanners can tell you, but they usually cost money and add another SaaS account.
In this article we’ll set up a free, low-maintenance alternative using Trivy, an open-source scanner from Aqua Security. Once a week, a systemd timer scans every running container and the host itself, then saves the results as JSON. We’ll also show how to use Trivy to choose an upgrade, and point out a few problems we ran into while rolling this out on small servers.
sudo.Tested on Ubuntu 24.04 LTS with Docker 29.1 (Ubuntu’s docker.io package), Trivy 0.76.2 and systemd 255, November 2026.
What we’re building
- A pinned Trivy release, verified against its published checksum.
- A root-only script that scans each running container by its local image ID, plus the host filesystem.
- A hardened systemd service and a weekly timer.
- A quick way to read the results with
jq.
Install Docker, jq and two sample containers
If your server already runs Docker, skip the sample containers. For a test box, Ubuntu’s docker.io package is enough. For production you may prefer Docker’s official repository.
export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-get install -y docker.io jq curl ca-certificates
systemctl enable --now dockerNext, start two deliberately old images so the scan has something to find:
docker run -d --name demo-web --restart unless-stopped nginx:1.24.0
docker run -d --name demo-cache --restart unless-stopped redis:7.0.11
docker ps --format 'table {{.Names}}\t{{.Image}}\t{{.Status}}'Install a pinned, checksum-verified Trivy
Don’t install the scanner with a curl | sh command that always fetches the newest version. Pin one version, check it against the published checksum, and upgrade on purpose. This isn’t just caution. In March 2026, attackers compromised Trivy’s own release pipeline and published a malicious v0.69.4 (GHSA-69fq-xp46-6x23). A checksum only proves that the file you downloaded matches the release page. It doesn’t prove the release itself is safe. Pinning a known-good version and waiting a few days before adopting a new one is what protects you.
At the time of writing, the current release is v0.76.2 (release page). On ARM servers, change Linux-64bit to Linux-ARM64.
TRIVY_VERSION=0.76.2
TARBALL="trivy_${TRIVY_VERSION}_Linux-64bit.tar.gz"
WORK=$(mktemp -d)
cd "$WORK"
curl -fsSLO "https://github.com/aquasecurity/trivy/releases/download/v${TRIVY_VERSION}/${TARBALL}"
curl -fsSLO "https://github.com/aquasecurity/trivy/releases/download/v${TRIVY_VERSION}/trivy_${TRIVY_VERSION}_checksums.txt"
grep " ${TARBALL}\$" "trivy_${TRIVY_VERSION}_checksums.txt" | sha256sum -c -
tar -xzf "$TARBALL" trivy
install -m 0755 trivy /usr/local/bin/trivy
cd /
rm -rf "$WORK"
trivy --versionEvery release also includes a .sigstore.json signature bundle. If you have cosign installed, you can also verify the signature, as described in Trivy’s signature verification docs.
Write the scan script
Three decisions in this script came from problems we hit in real rollouts:
- Scan by image ID, not by tag. A tag like
nginx:latestcan be re-pulled after your container started, so it may no longer be the image that’s actually running. And if the tag isn’t present locally, Trivy falls back to the registry.docker inspect --format '{{.Image}}'returns the exact local image, and--image-src dockertells Trivy to read it from the local Docker engine only. - Track results by image, not by container. Containers get new IDs on every redeploy. If you track findings by container, each restart looks like “fixed, then new again”. The script scans each distinct image once and writes a
containers.tsvfile showing which containers use which image. - Skip Docker’s storage when scanning the host. Without
--skip-dirs /var/lib/docker, the host scan reads every image layer a second time and reports container findings as host findings.
Save this as /usr/local/sbin/cve-scan:
#!/usr/bin/env bash
# cve-scan: weekly Trivy scan of running containers and the host.
set -euo pipefail
STATE_DIR=/var/lib/cve-scan
CACHE_DIR="$STATE_DIR/cache"
RUN_DIR="$STATE_DIR/results/$(date -u +%Y%m%dT%H%M%SZ)"
export TMPDIR="${TMPDIR:-$STATE_DIR/tmp}"
umask 077
mkdir -p "$CACHE_DIR" "$TMPDIR" "$RUN_DIR"
COMMON=(--cache-dir "$CACHE_DIR" --scanners vuln --severity CRITICAL,HIGH
--ignore-unfixed --format json --quiet --timeout 30m)
# 1. Refresh the vulnerability databases once; every scan below reuses them.
trivy image --cache-dir "$CACHE_DIR" --download-db-only --quiet
trivy image --cache-dir "$CACHE_DIR" --download-java-db-only --quiet
# 2. Record which exact local image each running container uses.
docker ps --format '{{.Names}}' | while read -r name; do
printf '%s\t%s\t%s\n' "$name" \
"$(docker inspect --format '{{.Image}}' "$name")" \
"$(docker inspect --format '{{.Config.Image}}' "$name")"
done > "$RUN_DIR/containers.tsv"
# 3. Scan each distinct image once, by ID, from the local Docker engine.
failed=0
mapfile -t image_ids < <(cut -f2 "$RUN_DIR/containers.tsv" | sort -u)
for image_id in "${image_ids[@]}"; do
short="${image_id#sha256:}"
short="${short:0:12}"
if ! trivy image "${COMMON[@]}" --skip-db-update --image-src docker \
--output "$RUN_DIR/image-${short}.json" "$image_id"; then
echo "cve-scan: scan failed for image ${image_id}" >&2
failed=1
fi
done
# 4. Scan the host, skipping container storage and pseudo-filesystems.
if ! trivy rootfs "${COMMON[@]}" --skip-db-update \
--skip-dirs /var/lib/docker --skip-dirs /var/lib/containerd \
--skip-dirs "$STATE_DIR" --skip-dirs /proc --skip-dirs /sys \
--skip-dirs /dev --skip-dirs /run \
--output "$RUN_DIR/host.json" /; then
echo "cve-scan: host scan failed" >&2
failed=1
fi
# 5. Keep about three months of results.
find "$STATE_DIR/results" -mindepth 1 -maxdepth 1 -type d -mtime +90 -exec rm -rf {} +
echo "cve-scan: results in ${RUN_DIR}"
exit "$failed"chown root:root /usr/local/sbin/cve-scan
chmod 0700 /usr/local/sbin/cve-scan--ignore-unfixed hides vulnerabilities that have no fixed version yet, so the report lists only problems you can act on now. --scanners vuln turns off Trivy’s secret scanner, which is on by default for images, so the weekly report stays focused on vulnerabilities and runs faster. The script downloads two databases: the main vulnerability database and Trivy’s Java database. Both live under /var/lib/cve-scan and take up some disk space, so check the size with du -sh /var/lib/cve-scan after the first run.
Create a hardened systemd service
On some servers, /tmp is a RAM disk (tmpfs). Trivy unpacks image layers into its temp directory, and on one of our first runs that filled /tmp and slowed the whole server. The service below uses StateDirectory= to keep the cache and temp files under /var/lib/cve-scan. It also caps memory with MemoryMax= and runs the scan at low CPU and disk priority.
[Unit]
Description=Weekly Trivy vulnerability scan of containers and host
Wants=network-online.target
After=network-online.target docker.service
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/cve-scan
StateDirectory=cve-scan
StateDirectoryMode=0700
Environment=TMPDIR=/var/lib/cve-scan/tmp
MemoryMax=3G
Nice=10
IOSchedulingClass=idle
TimeoutStartSec=2h
PrivateTmp=yes
ProtectSystem=full
ProtectHome=read-only
NoNewPrivileges=yesIf your server holds many large images, look at the peak memory after a few runs (systemctl show -p MemoryPeak cve-scan.service) and adjust MemoryMax up or down.
Schedule it with a weekly timer
RandomizedDelaySec adds a random delay to the start time, so several servers don’t all scan at exactly 03:00. Persistent=true means that if the server was off at the scheduled time, the scan runs as soon as it boots.
[Unit]
Description=Run cve-scan weekly
[Timer]
OnCalendar=Mon *-*-* 03:00:00
RandomizedDelaySec=2h
Persistent=true
[Install]
WantedBy=timers.targetsystemctl daemon-reload
systemctl enable --now cve-scan.timer
systemctl list-timers cve-scan.timer --no-pagerRun it once now and read the results
Before the first host scan, apply pending updates with apt-get upgrade, and reboot if the kernel was updated. On a freshly built server, most host findings tend to be packages that are just waiting to be upgraded, kernel packages especially, and that noise hides the findings that matter.
Then start the first scan by hand. The first run downloads the vulnerability databases, so allow a few minutes.
systemctl start cve-scan.service
systemctl show -p Result -p ExecMainStatus cve-scan.service
journalctl -u cve-scan.service --no-pager -n 5The next block shows one summary line for the host and for each scanned image, then lists which containers use which image:
RUN_DIR=$(ls -1d /var/lib/cve-scan/results/*/ | tail -n 1)
echo "Results in ${RUN_DIR}"
for f in "${RUN_DIR}"*.json; do
jq -r --arg file "$(basename "$f")" '
[.Results[]?.Vulnerabilities[]?] as $v
| "\($file)\tcritical=\([$v[] | select(.Severity == "CRITICAL")] | length)\thigh=\([$v[] | select(.Severity == "HIGH")] | length)"' "$f"
done
cat "${RUN_DIR}containers.tsv"The output looks something like this (your counts will differ):
Results in /var/lib/cve-scan/results/20261125T031502Z/
host.json critical=<n> high=<n>
image-1a2b3c4d5e6f.json critical=<n> high=<n>
image-9f8e7d6c5b4a.json critical=<n> high=<n>
demo-cache sha256:9f8e7d6c5b4a... redis:7.0.11
demo-web sha256:1a2b3c4d5e6f... nginx:1.24.0The counts are package findings, not unique CVEs. One CVE can show up on several packages from the same source, so a high count can come down to a few fixes.
To see the actual packages, list one line per image and package. Because results are grouped by image and package rather than by container, they stay comparable from week to week. To do the same for the host, replace image-*.json with host.json.
RUN_DIR=$(ls -1d /var/lib/cve-scan/results/*/ | tail -n 1)
jq -r '.ArtifactName as $img
| .Results[]? | .Vulnerabilities[]?
| [($img | .[0:19]), .PkgName, .InstalledVersion, .FixedVersion, .Severity, .VulnerabilityID]
| @tsv' "${RUN_DIR}"image-*.json | awk 'NR <= 20'Compare candidate images before you upgrade
Scanning tells you what’s wrong. Choosing the upgrade that actually fixes it is a separate question. Vendors often publish several tags at once (a patch release, a newer minor release, a new major release), and a newer tag doesn’t always fix the vulnerability you care about. In one rollout, we found that a vendor’s latest patch release still contained a critical library vulnerability. Only the next major release fixed it.
Trivy can scan candidate tags straight from the registry (--image-src remote) using the same cache, without starting any containers. That lets you compare the options side by side. The loop runs in a subshell, so its settings don’t change your own shell. A scan that fails prints a “scan failed” message instead of a result line.
(
set -o pipefail
for img in redis:7.0.11 redis:7.2 redis:7.4; do
TMPDIR=/var/lib/cve-scan/tmp trivy image --cache-dir /var/lib/cve-scan/cache \
--skip-db-update --image-src remote \
--scanners vuln --severity CRITICAL,HIGH --ignore-unfixed --format json --quiet "$img" \
| jq -r --arg img "$img" '
[.Results[]?.Vulnerabilities[]?] as $v
| "\($img)\tcritical=\([$v[] | select(.Severity == "CRITICAL")] | length)\thigh=\([$v[] | select(.Severity == "HIGH")] | length)\t\([$v[] | select(.Severity == "CRITICAL") | .VulnerabilityID] | unique | join(","))"' \
|| echo "${img}: scan failed" >&2
done
)Look at the critical vulnerability IDs, not just the counts. The right upgrade is the one where the specific vulnerability from your weekly report is gone. Then check the vendor’s release notes before moving to a new major version.
Watch the age of the vulnerability database
This problem is easy to miss. Trivy matches packages against its own vulnerability database, which is rebuilt every 6 hours. When a Linux distribution publishes a fix after your copy of the database was built, that copy still lists the vulnerability as having no fix. With --ignore-unfixed, the vulnerability is then hidden from your report, even though apt could install the fix right now.
You can check how old your database is:
trivy version --cache-dir /var/lib/cve-scan/cacheVersion: 0.76.2
Vulnerability DB:
Version: 2
UpdatedAt: <timestamp>
NextUpdate: <timestamp>
DownloadedAt: <timestamp>
Java DB:
Version: 1
UpdatedAt: <timestamp>
NextUpdate: <timestamp>
DownloadedAt: <timestamp>In practice: the script asks for a fresh database at the start of every run, but Trivy only downloads one when the cached copy is more than about 24 hours old (the database itself is rebuilt every 6 hours). After an urgent advisory, delete the cached database first so the next run fetches the newest one:
trivy clean --vuln-db --cache-dir /var/lib/cve-scan/cache
systemctl start cve-scan.serviceAnd now and then, scan once without --ignore-unfixed to see what the filter is hiding.
Next steps
A JSON folder on each server is a start, but someone has to read it. On the servers we manage, each weekly bundle is uploaded to a central tracking server, so the results for every server live in one place and can be compared week to week. The tracking server re-checks the findings with a second scanner, Grype, and flags anything on CISA’s Known Exploited Vulnerabilities catalog. Even if you don’t build anything like that, checking your critical findings against the KEV list by hand is a good way to decide what to fix first.
To protect the host itself, see our Linux Security Best Practices guide.
Need more help?
Not sure what’s running on your servers, or don’t have time to keep up with the weekly report? Our IT Operations service includes vulnerability monitoring and patching for small nonprofits, law firms and mission-driven organizations. Contact us and we’ll get right back to you.