
Container Image Security in 2026: Trivy, Grype, Distroless, and Hardened Base Images
A container image is a whole operating system that you ship with your app. Most teams think about their own code and forget the rest. Yet a typical image carries hundreds of packages that nobody chose on purpose: a shell, a package manager, compression libraries, and tools left over from the build. Each one can carry vulnerabilities, and each one is something an attacker can use after a break-in.
The fix has three parts. Start from a smaller and better-maintained base image. Scan what you build, and act on the results without drowning in noise. Then run the container with as few privileges as possible, so a compromise stays contained.
This guide covers all three. It explains how base images differ, including distroless images and the hardened images that Docker made free in December 2025. It shows multi-stage Dockerfiles, Trivy and Grype commands, a GitHub Actions workflow pinned to commit hashes, and the runtime settings that matter.
One event shapes this guide. In March 2026, attackers compromised the Trivy release process and its GitHub Action, and malicious code ran in thousands of CI pipelines. The scanner itself became the attack. Section 7 explains what happened and what it teaches about trusting security tools.
A note on testing. I did not build images or run scanners for this article, because this machine has no container runtime. Instead, I checked the details against primary sources. I read the scanner release data from GitHub, the action inputs from their source at the pinned tags, and the distroless image list from its repository. I also validated the workflow YAML. All of it was checked on November 26, 2026. Run the commands on your own images before you rely on them.
This article is part of my security series. It builds on my guides to supply chain security, dependency scanning, and secrets management.
Table of Contents
- The Short Answer
- What Is Inside an Image
- Choosing a Base Image
- A Hardened Dockerfile
- Scanning with Trivy
- Scanning with Grype and Syft
- The March 2026 Trivy Compromise
- A CI Pipeline That Scans Every Build
- Triage: Fixing What Matters
- Runtime Hardening
- Signing, SBOMs, and Provenance
- Keeping Images Fresh
- Common Mistakes
- Frequently Asked Questions
- Conclusion
- References
1. The Short Answer
| Goal | Do this |
|---|---|
| Smaller attack surface | Use a multi-stage build and a distroless or hardened runtime image |
| Fewer false alarms | Start from a minimal base, and fail builds only on fixable high and critical findings |
| Repeatable builds | Pin base images by digest, and let Renovate or Dependabot update the digests |
| Safe CI | Pin every action to a full commit SHA, and pin the scanner version too |
| Contained breaches | Run as non-root, read-only, with no capabilities or privilege escalation |
| Proof of what you shipped | Generate an SBOM, sign the image, and attach provenance |
If you do only one thing, switch the final stage of your Dockerfile to a distroless or hardened image that runs as a non-root user. That single change removes most of the packages your scanner complains about, and it takes away the shell an attacker would use.
Quick start path
If you only want the practical parts, read these three sections in order.
- The Dockerfile: Copy the pattern from section 4 for your language.
- The CI workflow: Adapt the pinned workflow in section 8, including the scheduled rescan.
- The runtime settings: Apply the Docker or Kubernetes settings in section 10.
The other sections explain why each choice matters and how to handle the findings.
2. What Is Inside an Image
An image is a stack of filesystem layers plus some metadata. The base layers come from the image in your first FROM line. Your own layers add your code and dependencies on top.
A full base image, such as node:24 or python:3.14, is built on a complete Debian install. It includes compilers, a shell, apt, curl, git, and many libraries. Those tools are useful while building, but your running app rarely needs them.
Why the extra packages hurt
- More vulnerabilities: Every package can have CVEs. A full Debian-based image often shows hundreds of findings in a scan, most in packages your app never touches.
- More tools for attackers: After exploiting a bug in your app, an attacker wants a shell,
curlto download tools, and a package manager to install more. A full image hands them all of that. - Alert fatigue: When every scan shows hundreds of findings, people stop reading scans. Then the one finding that matters gets missed.
What layers remember
Layers only ever add to the image. If one step copies a secret into the image and a later step deletes it, the secret is still in the earlier layer. Anyone who pulls the image can extract it. The same applies to build tools and caches that you remove in a later RUN step.
That is the main reason for multi-stage builds. The final stage copies only the finished artifacts from the build stage, so nothing else reaches the shipped image.
3. Choosing a Base Image
The main options
| Base image type | Examples | Shell | Package manager | Typical use |
|---|---|---|---|---|
| Full distribution | node:24, python:3.14 |
Yes | Yes | Build stages and local development |
| Slim distribution | node:24-trixie-slim, python:3.14-slim |
Yes | Yes | Apps that need a few system packages |
| Alpine | node:24-alpine |
Yes | Yes (apk) |
Small images, if musl libc works for you |
| Distroless | gcr.io/distroless/nodejs24-debian13 |
No | No | Production runtime |
| Docker Hardened Images | dhi.io/node:24 |
No, in runtime variants | No | Production runtime with vendor support options |
| Chainguard Images | cgr.dev/chainguard/node |
No, in runtime variants | No | Production runtime with a minimal CVE focus |
| Scratch | scratch |
No | No | Static binaries, such as Go or Rust |
Distroless
Google’s distroless images contain your language runtime and its direct dependencies, and almost nothing else. There is no shell and no package manager. The smallest, gcr.io/distroless/static-debian13, is about 2 MiB according to the project’s README.
The current images are based on Debian 13 (trixie), and the tag names say so. The repository lists images for static binaries, glibc-based binaries, Java 17, 21, and 25, Node.js 22, 24, and 26, and Python 3. Each comes in four variants: latest, nonroot, debug, and debug-nonroot.
- Use
nonrootin production. It runs as user ID 65532 by default. - Use
debugonly for troubleshooting. It adds a BusyBox shell, which defeats part of the purpose. - Name the Debian version in the tag. The distroless README warns that the unversioned names will move to a newer Debian release in the future.
Docker Hardened Images
In December 2025, Docker made its catalog of more than 1,000 hardened images free and open source under the Apache 2.0 license. They are built on Debian and Alpine, and they ship with SBOMs and signed provenance.
You pull them from Docker’s own registry after logging in with a Docker Hub account. No paid subscription is needed for the community images.
docker login dhi.io
docker pull dhi.io/node:24
Runtime images are minimal. Separate -dev variants include a shell and build tools for the build stage. Docker sells paid tiers with extra support and extended lifecycle coverage, but the free images are enough for most teams.
Chainguard Images
Chainguard builds images from source on its own Linux distribution, Wolfi, and focuses on keeping known CVEs near zero. Its free tier is limited, mainly to the latest tags of each image. Pinning older versions usually needs a paid plan. It is a strong choice if you want a vendor to own base image patching.
Alpine: small, with a catch
Alpine images are tiny and popular. They use musl instead of glibc, though, which occasionally causes subtle bugs, such as DNS edge cases or slower memory allocation in some runtimes. Python wheels built for glibc do not work on musl, so installs may compile from source. Alpine is fine if you test for this, but distroless or hardened images avoid the question.
How to choose
- Static binary from Go or Rust: Use
gcr.io/distroless/static-debian13:nonrootorscratch. - Node.js, Python, or Java: Use the matching distroless image or a Docker Hardened Image.
- You need system packages at runtime: Use a slim Debian image, install only what you need, and remove the package manager’s cache.
- You want a vendor to own patching: Look at the paid tiers of Docker Hardened Images or Chainguard.
4. A Hardened Dockerfile
Node.js on distroless
# syntax=docker/dockerfile:1
# ---- Build stage: full toolchain, never shipped ----
FROM node:24-trixie-slim AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build
# ---- Production dependencies only ----
FROM node:24-trixie-slim AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev --ignore-scripts
# ---- Runtime: no shell, no package manager, non-root ----
FROM gcr.io/distroless/nodejs24-debian13:nonroot
WORKDIR /app
ENV NODE_ENV=production
COPY --from=deps /app/node_modules ./node_modules
COPY --from=build /app/dist ./dist
USER nonroot
EXPOSE 3000
CMD ["dist/server.js"]
A few details matter here.
- The distroless Node image’s entrypoint is already
node, soCMDnames only the script. --ignore-scriptsstops install scripts from running in the dependency stage. Remove it only if a package truly needs a script, such as a native build.- The build and runtime share a Debian release. Native modules compiled on trixie then find the same glibc at runtime.
USER nonrootis already the default in thenonrootvariant. Stating it makes the intent clear to readers and to scanners.
Go on distroless static
# syntax=docker/dockerfile:1
FROM golang:1.26 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/app ./cmd/app
FROM gcr.io/distroless/static-debian13:nonroot
COPY --from=build /out/app /app
USER nonroot:nonroot
ENTRYPOINT ["/app"]
With CGO_ENABLED=0, Go produces a fully static binary. The runtime image then needs only CA certificates, time zone data, and a user entry, which the static distroless image provides.
Many Go projects leave cgo turned on without needing it. Check whether you use any C libraries, such as SQLite through mattn/go-sqlite3. If you do not, disable cgo and use the static image. If you do, use gcr.io/distroless/cc-debian13 or base-debian13, which include the C libraries the binary needs.
Using Docker Hardened Images instead
FROM dhi.io/node:24-dev AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build && npm prune --omit=dev
FROM dhi.io/node:24
WORKDIR /app
COPY --from=build /app/node_modules ./node_modules
COPY --from=build /app/dist ./dist
CMD ["node", "dist/server.js"]
Check the image’s documentation for its default user and entrypoint, since they can differ from distroless.
Pin base images by digest
A tag such as node:24-trixie-slim moves every time the image is rebuilt. A digest pins the exact image.
FROM node:24-trixie-slim@sha256:<digest> AS build
You can read the current digest with docker buildx imagetools inspect node:24-trixie-slim. Pinning makes builds repeatable, but it also freezes security fixes. Let Renovate or Dependabot open a pull request whenever the digest changes, as section 12 explains.
Never bake secrets into layers
If a build needs a token, such as for a private package registry, use a BuildKit secret mount. The secret is available during that one RUN step and never written to a layer.
RUN --mount=type=secret,id=npm_token \
NPM_TOKEN="$(cat /run/secrets/npm_token)" npm ci
docker build --secret id=npm_token,env=NPM_TOKEN -t myapp:1.0 .
Never pass secrets with ARG or ENV. Both end up in the image metadata, where docker history shows them.
Add a .dockerignore
.git
.env
.env.*
node_modules
dist
coverage
*.pem
*.key
Dockerfile
Without it, COPY . . sends your whole folder to the build, including .git history and local .env files. Those can end up in the build stage and, through a careless copy, in the final image.
5. Scanning with Trivy
Trivy is Aqua Security’s open source scanner. One binary scans container images, filesystems, Git repositories, Kubernetes clusters, and infrastructure as code. It finds vulnerabilities, secrets, misconfigurations, and license issues. The latest release when I checked was v0.76.2, published on November 5, 2026.
Pin the exact Trivy version wherever you install it, and pin any action that runs it to a commit SHA. Section 7 explains why, using an attack on Trivy itself.
Everyday Trivy commands
# Scan a local or remote image
trivy image myapp:1.0
# Only fixable high and critical findings, and fail the command if any exist
trivy image --severity HIGH,CRITICAL --ignore-unfixed --exit-code 1 myapp:1.0
# Check the Dockerfile and other config files for misconfigurations
trivy config .
# Scan the project folder for vulnerable dependencies and leaked secrets
trivy fs --scanners vuln,secret .
# Produce a CycloneDX SBOM of the image
trivy image --format cyclonedx --output sbom.cdx.json myapp:1.0
What the flags do
--severity: Reports only the listed severity levels.--ignore-unfixed: Hides findings that have no fixed version yet. You cannot act on those by upgrading, so they mostly add noise in a build gate.--exit-code 1: Makes the command fail when findings remain, which fails the CI job.--scanners: Picks which checks run on a filesystem scan.
trivy config reads your Dockerfile too. It flags issues such as a missing USER instruction, which Trivy reports as check AVD-DS-0002, “image user should not be root.”
Ignoring findings, with an expiry date
Some findings do not apply to you. Trivy reads ignore rules from .trivyignore, or from a YAML file that you pass with --ignorefile. The YAML format is marked experimental, but it is more expressive.
# .trivyignore.yaml
vulnerabilities:
- id: CVE-2026-12345
purls:
- "pkg:deb/debian/libexample"
expired_at: 2027-01-31
statement: Vulnerable function is not used. Re-check when 2.4.1 ships.
trivy image --ignorefile .trivyignore.yaml --show-suppressed myapp:1.0
Always set the expired_at field. An ignore rule without an expiry date becomes permanent by accident. The --show-suppressed flag lists what was hidden, so reviewers can see it.
6. Scanning with Grype and Syft
Grype is Anchore’s open source vulnerability scanner, and Syft is its companion SBOM generator. They split the job in two. Syft catalogs every package in an image, and Grype matches that catalog against vulnerability data. When I checked, the latest releases were Grype v0.122.1 from November 18, 2026, and Syft v1.57.2 from November 16, 2026. The pinning advice from section 7 applies to these tools as well.
Everyday Grype commands
# Scan an image directly
grype myapp:1.0
# Fail only on fixable findings of high severity or worse
grype myapp:1.0 --only-fixed --fail-on high
# Generate an SBOM once, then scan the SBOM
syft myapp:1.0 -o cyclonedx-json=sbom.cdx.json
grype sbom:./sbom.cdx.json
The SBOM-first workflow has a real advantage. You generate the SBOM once at build time and store it with the release. Later, you can rescan the SBOM against fresh vulnerability data without pulling the image again. When a new critical CVE appears, a quick scan of all stored SBOMs tells you which releases are affected.
Configuration
Grype reads .grype.yaml from the project folder.
# .grype.yaml
only-fixed: true
fail-on-severity: high
ignore:
# Review by 2027-01-31.
- vulnerability: CVE-2026-12345
reason: Not reachable, because we never parse untrusted archives.
package:
name: libexample
Grype ignore rules accept a reason, but they have no expiry field. Put the review date in a comment, and check it during code review. Grype can also read VEX documents, which section 9 covers.
Update your Grype
Anchore announced that Grype versions older than v0.88.0 stopped receiving vulnerability database updates on March 6, 2026. An old Grype binary in a forgotten CI image now scans against stale data and reports fewer problems than exist. Check the version in every pipeline.
Trivy or Grype?
| Aspect | Trivy | Grype with Syft |
|---|---|---|
| Scope | Vulnerabilities, secrets, misconfigurations, licenses | Vulnerabilities, with Syft for SBOMs |
| SBOM workflow | Generates and scans SBOMs | Built around SBOMs from the start |
| IaC and Kubernetes | Yes | No |
| Output formats | Table, JSON, SARIF, CycloneDX, SPDX, and more | Table, JSON, SARIF, CycloneDX, and more |
| License | Apache 2.0 | Apache 2.0 |
Both tools are good choices. Trivy is the broader tool in one binary. Grype and Syft suit teams that already treat the SBOM as the central artifact. Running both is common, because their vulnerability data and matching logic differ, and each finds things the other misses. If you must pick one, start with Trivy for its breadth. Adopt Syft and Grype once SBOMs become your primary release artifact.
7. The March 2026 Trivy Compromise
On March 19, 2026, a threat actor used compromised credentials against Aqua Security’s GitHub projects. According to Aqua and the GitHub security advisory, the attacker did three things.
- Published a malicious Trivy release, v0.69.4.
- Force-pushed 76 of the 77 version tags of the
aquasecurity/trivy-actionrepository to commits containing credential-stealing malware. - Replaced all 7 tags of the
aquasecurity/setup-trivyaction.
Any workflow that referenced the action by a tag, such as @v0.28.0, silently ran the malicious code before running a normal scan. The output looked fine, so nobody noticed. The malicious tags were live for about 12 hours, until around 05:40 UTC on March 20. Malicious Docker Hub images, tagged v0.69.5 and v0.69.6, followed on March 22 and 23. Researchers attribute the campaign to a group called TeamPCP, and it was tracked as CVE-2026-33634.
Some sources count 75 of 76 tags rather than 76 of 77. Either way, nearly every tag was affected. The one exception was v0.35.0, which GitHub’s immutable releases feature protected.
What it teaches
- Tags can be moved. Anyone with write access can move a tag to new code. A full commit SHA cannot be moved.
- Security tools run with secrets. Scanners often run in jobs that hold registry credentials and cloud tokens, which makes them attractive targets.
- Immutable releases really work. The only safe tag was the one protected by an immutable release.
- Pin the tool, not just the action. The action downloads a Trivy binary. Set its version explicitly, and verify release signatures where you install binaries yourself.
If your workflows used trivy-action or setup-trivy by tag between March 19 and 20, 2026, the advisory recommends treating the secrets in those jobs as exposed. Check the run logs from those dates and rotate the credentials.
8. A CI Pipeline That Scans Every Build
This GitHub Actions workflow builds the image, scans it with Trivy and Grype, and uploads the results to GitHub code scanning. Every action is pinned to a full commit SHA, with the version in a comment so Dependabot or Renovate can update it.
# .github/workflows/image-scan.yml
name: Image scan
on:
pull_request:
push:
branches: [main]
permissions:
contents: read
jobs:
scan:
runs-on: ubuntu-latest
permissions:
contents: read
security-events: write # upload SARIF results
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Build image
run: docker build -t myapp:${{ github.sha }} .
- name: Trivy scan
uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0
with:
version: v0.76.2 # pin the scanner too, the action default is older
image-ref: myapp:${{ github.sha }}
format: sarif
output: trivy.sarif
severity: HIGH,CRITICAL
ignore-unfixed: true
exit-code: "1"
- name: Grype scan
uses: anchore/scan-action@11983a512817154c80a9db660c1a184be7513ed6 # v7.4.3
id: grype
with:
image: myapp:${{ github.sha }}
only-fixed: true
severity-cutoff: high
fail-build: true
- name: Upload Trivy results
if: always()
uses: github/codeql-action/upload-sarif@915412ff23e8b7659517e607487dbeae018f2934 # v4.39.5
with:
sarif_file: trivy.sarif
category: trivy
- name: Upload Grype results
if: always()
uses: github/codeql-action/upload-sarif@915412ff23e8b7659517e607487dbeae018f2934 # v4.39.5
with:
sarif_file: ${{ steps.grype.outputs.sarif }}
category: grype
Why each choice
- Commit SHAs for every action. I resolved each tag to its commit through the GitHub API on November 26, 2026. Recheck them when you copy this, and let a bot keep them current.
version: v0.76.2on the Trivy action. At v0.36.0, the action’s default Trivy version is v0.70.0, which is older than the latest release.- The Grype defaults were checked. The scan action fails the build by default, outputs SARIF, and uses a default severity cutoff of
medium. The workflow raises the cutoff tohigh. if: always()on uploads. Results still reach the Security tab when the scan step fails the job.- Minimal permissions for the job. The job can read code and write security events, and nothing else.
persist-credentials: falsekeeps the checkout token out of the workspace.
I validated the YAML syntax, but I did not run this workflow. Test it on a branch first.
Scan on a schedule, too
New CVEs appear every day for images you built weeks ago. Add a scheduled run that rescans the images or SBOMs of everything in production. Otherwise you only learn about new vulnerabilities when someone happens to push code.
Here is a minimal skeleton. It rescans two production images every night and reports to the Security tab without failing.
# .github/workflows/scheduled-rescan.yml
name: Scheduled rescan
on:
schedule:
- cron: "17 5 * * *" # daily at 05:17 UTC
workflow_dispatch:
permissions:
contents: read
jobs:
rescan:
runs-on: ubuntu-latest
permissions:
contents: read
packages: read # pull private images from GHCR
security-events: write
strategy:
fail-fast: false
matrix:
image:
- ghcr.io/example/myapp:production
- ghcr.io/example/worker:production
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Log in to GHCR
run: echo "${{ secrets.GITHUB_TOKEN }}" | docker login ghcr.io -u "${{ github.actor }}" --password-stdin
- name: Grype scan
uses: anchore/scan-action@11983a512817154c80a9db660c1a184be7513ed6 # v7.4.3
id: grype
with:
image: ${{ matrix.image }}
only-fixed: true
severity-cutoff: high
fail-build: false # report, do not fail a nightly job
- name: Upload results
uses: github/codeql-action/upload-sarif@915412ff23e8b7659517e607487dbeae018f2934 # v4.39.5
with:
sarif_file: ${{ steps.grype.outputs.sarif }}
category: rescan-${{ strategy.job-index }}
Pin these SHAs the same way as in the main workflow, and resolve them again on the day you copy the file. New alerts then appear in the Security tab, where you can route them to email or chat. If your images live in another registry, replace the login step with that registry’s login.
9. Triage: Fixing What Matters
A scanner produces findings, not priorities. A good process turns hundreds of results into a short list of real work.
Ask five questions for each finding
- Is the package in the final image at all? A filesystem or lockfile scan also reports build tools and dev dependencies that never reach the runtime stage. Scan the image you actually ship, and judge findings against that.
- Is there a fix? If no fixed version exists, you cannot upgrade. Track it, and check for workarounds or a different base image.
- Is the package actually used? A vulnerable library in the base image may never load in your app. Removing it is better than arguing about it.
- Is the vulnerable code reachable? Some CVEs only matter for specific functions or configurations.
- How bad is it in your context? A network-facing parser bug matters more than a local denial of service in a build tool.
Use exploit data, not just CVSS
CVSS scores measure worst-case severity, not likelihood. Two other sources help you rank.
- CISA’s Known Exploited Vulnerabilities catalog lists CVEs that attackers are using in the wild. Treat any match as urgent.
- EPSS, the Exploit Prediction Scoring System, estimates the probability that a CVE will be exploited soon.
A medium-severity CVE on the KEV list deserves more attention than a critical one that nobody exploits.
Record decisions with VEX
VEX, the Vulnerability Exploitability eXchange, is a machine-readable way to say “this CVE does not affect this product, and here is why.” Formats include OpenVEX, CycloneDX VEX, and CSAF. Trivy and Grype can both read VEX documents and suppress the matching findings.
Here is a small OpenVEX document in the format that Trivy’s documentation shows. The product is identified by its package URL, which you can copy from Trivy’s JSON report.
{
"@context": "https://openvex.dev/ns/v0.2.0",
"@id": "https://example.com/vex/myapp-2026-11-26",
"author": "Example Security Team",
"timestamp": "2026-11-26T10:00:00Z",
"version": 1,
"statements": [
{
"vulnerability": { "name": "CVE-2026-12345" },
"products": [{ "@id": "pkg:deb/debian/libexample@2.4.0-1" }],
"status": "not_affected",
"justification": "vulnerable_code_not_in_execute_path",
"impact_statement": "The app never parses untrusted archives with this library."
}
]
}
trivy image --vex ./myapp.openvex.json --show-suppressed myapp:1.0
Grype matches VEX products in its own way, so check its documentation before reusing the same file there. Like ignore rules, VEX statements need a review date, because new code can make a vulnerable path reachable.
VEX is better than an ignore file, because the statement travels with the image. Your customers’ scanners can read it too, so they stop opening tickets about CVEs that do not apply.
The fastest fix is usually a rebuild
Most image findings live in the base image, not your code. Rebuilding on a fresh base image fixes them all at once. Moving to a distroless or hardened image fixes even more, because the vulnerable packages are simply gone.
10. Runtime Hardening
Scanning reduces known vulnerabilities. Runtime hardening limits the damage of the ones nobody knows about yet.
Docker
docker run \
--read-only \
--tmpfs /tmp \
--cap-drop ALL \
--security-opt no-new-privileges \
--user 65532:65532 \
--memory 512m --pids-limit 200 \
myapp:1.0
Kubernetes
apiVersion: apps/v1
kind: Deployment
metadata:
name: myapp
spec:
replicas: 2
selector:
matchLabels: { app: myapp }
template:
metadata:
labels: { app: myapp }
spec:
automountServiceAccountToken: false
securityContext:
runAsNonRoot: true
runAsUser: 65532
runAsGroup: 65532
seccompProfile:
type: RuntimeDefault
containers:
- name: app
image: registry.example.com/myapp@sha256:<digest>
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]
resources:
limits: { memory: "512Mi", cpu: "500m" }
volumeMounts:
- name: tmp
mountPath: /tmp
volumes:
- name: tmp
emptyDir: {}
What each setting does
- Non-root user: A process that breaks out of the app does not start as root inside the container.
- Read-only root filesystem: An attacker cannot drop tools or modify your code. Mount a small writable volume for
/tmpif the app needs one. - Drop all capabilities: Linux capabilities split root’s powers into pieces. Most apps need none of them.
- No privilege escalation: Blocks
setuidbinaries from raising privileges. - Seccomp
RuntimeDefault: Blocks dangerous system calls that normal apps never use. - No service account token: Most pods never call the Kubernetes API, so do not give them a token for it.
- Resource limits: A runaway or hijacked container cannot starve the node.
- Digest-pinned image: The cluster runs exactly the image you scanned and signed.
Kubernetes ships a “restricted” Pod Security Standard that enforces most of these settings. Turn it on per namespace with the pod-security.kubernetes.io/enforce: restricted label.
Roll it out gradually. The same standard also works with warn and audit labels. A warn label shows a warning to whoever applies a violating pod, and an audit label records it in the audit log. Neither one blocks anything. Start with warn: restricted and audit: restricted, fix what they report, and then switch to enforce.
A few settings undo most of this hardening, so treat them as red flags in review.
- Mounting the Docker socket: The container can start new privileged containers on the host.
--privilegedorprivileged: true: The container gets nearly every capability and access to host devices.hostPathvolumes: The container can read or write files on the node, sometimes including other pods’ data.hostNetwork: true: The pod shares the node’s network stack and can reach services bound to localhost.hostPIDorhostIPC: The pod can see or signal processes outside its own container.
The restricted standard blocks all of these, which is one more reason to enforce it.
11. Signing, SBOMs, and Provenance
Scanning tells you what is inside an image. Signing and provenance tell you where it came from, and that nobody changed it afterward.
- Sign images with Sigstore’s cosign. Keyless signing ties the signature to your CI identity, so there is no private key to manage.
- Attach an SBOM as an attestation, so anyone can scan the exact package list later.
- Generate build provenance, for example with GitHub artifact attestations, to record which workflow and commit produced the image.
- Verify at deploy time. A Kubernetes admission controller, such as Sigstore’s policy controller or Kyverno, can refuse unsigned images.
My supply chain security guide covers these tools in depth, with tested commands.
12. Keeping Images Fresh
An image that was clean last month is not clean today. New CVEs are published constantly, and fixes land in base images within days. Freshness is part of security.
Automate base image updates
Renovate and Dependabot both update Dockerfile FROM lines, including digests. With digest pinning plus a bot, you get repeatable builds and fast patching together. My dependency scanning guide compares the two tools.
A minimal Renovate setting looks like this.
{
"extends": ["config:recommended", "docker:pinDigests"],
"packageRules": [
{
"matchDatasources": ["docker"],
"matchUpdateTypes": ["digest"],
"automerge": true
}
]
}
Automerging digest-only updates is reasonable when your tests and scans run on every pull request. Major version updates should still get a human review.
Rebuild on a schedule
Rebuild and redeploy production images at least weekly, even without code changes. That picks up base image fixes that arrived since the last release. Some teams rebuild high-risk, internet-facing services daily.
13. Common Mistakes
- Shipping the build stage. Compilers, package managers, and source code have no place in production.
- Running the app as root. It is the default in most base images, so set
USERexplicitly. - Using
latesttags in production. You cannot tell what you are running, and every pull can change it. - Pinning digests without an update bot. The image stays frozen with all its old CVEs.
- Referencing actions by tag. The Trivy incident showed that tags can be moved to malicious code.
- Failing builds on every finding. Teams then disable the scanner, so gate only on fixable high and critical findings.
- Ignoring findings with no end date. Every ignore rule needs an owner and an expiry date.
- Copying secrets into the image. Deleted files still live in earlier layers.
- Scanning only at build time. Rescan running images and stored SBOMs on a schedule.
- Forgetting old scanner versions. Grype versions before v0.88.0 no longer get database updates.
- Giving scan jobs more secrets than they need. Scanners are a supply chain target, so keep registry credentials and cloud tokens out of scan jobs where you can.
- Trusting the default severity cutoff. The Grype action fails on
mediumby default, and the Trivy action reports every severity. Choose a threshold that matches your own risk tolerance.
14. Frequently Asked Questions
How do I debug a container with no shell?
Use the debug variant of the distroless image temporarily, or attach an ephemeral debug container. In Kubernetes, kubectl debug starts a container with tools next to your app, sharing its process namespace. You get a shell when you need one, without shipping it in production.
Are distroless images always better than Alpine?
Not always, but usually for production. Both are small, but distroless removes the shell and package manager, and it keeps glibc, which avoids musl compatibility issues. Alpine is easier to extend when you need extra packages.
Do Docker Hardened Images replace scanning?
No, because your own dependencies still need scanning. Hardened images cut the base image noise, so the remaining findings are mostly yours, which makes the scan results far more useful.
Should I use both Trivy and Grype?
Using both is common and cheap. They use different vulnerability data and matching rules, so each catches some findings the other misses. If you pick one, choose Trivy for breadth, or Grype with Syft for an SBOM-centered workflow.
Is it safe to keep using Trivy after the March 2026 compromise?
The project fixed the issue and published guidance, and many teams still use it. The lesson applies to every tool, not just Trivy. Pin actions by SHA, pin tool versions, verify release signatures, and keep secrets out of scan jobs when possible.
What about Docker Scout and commercial scanners?
Docker Scout, Snyk Container, and the scanners built into registries and cloud platforms all work on the same principles. They add dashboards, policy features, and fix suggestions. The practices in this guide apply to all of them.
15. Conclusion
Most container security work happens before the container ever runs. Choose a minimal base image, build in multiple stages, and keep secrets out of layers. Then scan every build, and focus on the findings that are fixable and actually exploitable.
Runtime settings catch what scanning misses. A non-root user, a read-only filesystem, and dropped capabilities turn many exploits into dead ends. Signing and provenance prove that the image you run is the image you built.
The Trivy compromise is the reminder to take home. Your security tools are part of your supply chain too. Pin them by commit, pin their versions, and give them as few secrets as possible. Tool versions and image catalogs change quickly, so treat the specifics here as accurate as of late November 2026.
16. References
Scanners
- Trivy releases
- Trivy documentation: filtering and ignore files
- Grype
- Syft
- Anchore: announcements, including the Grype database cutoff
- aquasecurity/trivy-action
- anchore/scan-action
The Trivy compromise
- GitHub advisory GHSA-69fq-xp46-6x23
- Aqua Security: Trivy supply chain attack, what you need to know
- Snyk: Trivy GitHub Actions supply chain compromise
Base images
- Google distroless
- Docker: hardened images for every developer
- Docker documentation: use a Docker Hardened Image
- Chainguard Images
Runtime and policy
- Kubernetes: Pod Security Standards
- Kubernetes: configure a security context
- Docker: build secrets
- CISA: Known Exploited Vulnerabilities catalog
- FIRST: EPSS
- OpenVEX