Container Image Scanning

Production-grade guide to container image scanning covering architecture patterns, implementation strategies, testing approaches, and operational best practices for enterprise engineering teams.

Container image scanning is the practice of analyzing container images for known vulnerabilities, misconfigurations, and compliance violations before they are deployed to production. It matters at every stage of the image lifecycle: when a base image is pulled, when application layers are built, when images are promoted between environments, and when they are scheduled for execution. A vulnerability in a base image layer, a compromised build tool, or an expired certificate embedded in an image can bypass network perimeter controls and execute inside any container runtime that pulls the image. Scanning provides the visibility needed to reject or remediate problematic images before they become runtime risk.

Scan a Single Image

The most common entry point is scanning an image that already exists in a registry or on disk. Tools query a vulnerability database—typically a CVE feed—and report matches against the packages and binaries present in the image’s filesystem layers.

Trivy is a widely adopted open-source scanner that supports image, filesystem, and repository scanning. The following command scans a specific image tag for critical and high-severity vulnerabilities and exits with a non-zero status if any are found:

trivy image --severity HIGH,CRITICAL myregistry.io/myapp:2024.07.15

If vulnerabilities are detected, trivy prints a table by default showing the vulnerability ID, title, installed version, and fixed version. The --exit-code 1 flag (which is the default when --severity is specified) ensures CI pipelines can fail the build when findings exceed the configured threshold.

$ trivy image --severity HIGH,CRITICAL myregistry.io/myapp:2024.07.15
[INFO] Detecting OS vulnerabilities...
[INFO] Detecting language-specific vulnerabilities...

MYAPP-2024-0145   CVE-2024-12345   PHP 8.1.25   PHP 8.1.28
  Severity: CRITICAL
  Title: Heap buffer overflow in PHP's array functions
  Installed: 8.1.25
  Fixed:        8.1.28

MYAPP-2024-0678   CVE-2024-56789   OpenSSL 3.0.4   OpenSSL 3.0.5
  Severity: HIGH
  Title: TLS record replay attack possible
  Installed: 3.0.4
  Fixed:        3.0.5

To suppress false positives or skip known-mitigated issues, trivy supports --skip-detectors, --ignore-unfixed, and a vulnerability ID whitelist via --vuln-id. The --quiet flag suppresses the header and summary, outputting only the raw JSON or TABLE format suitable for downstream tooling.

trivy image --severity HIGH,CRITICAL --skip-detectors os --quiet myregistry.io/myapp:2024.07.15

Scan a Repository or Registry

When images are stored in a registry, scanning a repository retrieves each tag and reports findings across the set. This is useful for nightly hygiene checks or pre-promotion validation.

trivy repo --type docker ghcr.io/org/app

The command pulls each tagged manifest, extracts the filesystem layers, and compares packages against the configured vulnerability source. By default, trivy uses the CNCF OSV database and the NVD feed. Alternative sources can be selected with --primary-source osv or --secondary-source nvd. If the registry requires authentication, trivy reads credentials from ~/.docker/config.json or a specified --authfile.

Error output from a repository scan typically looks like this when a tag is missing or inaccessible:

Error: unable to fetch manifest ghcr.io/org/app:latest: manifest unknown

Or when the repository is empty:

No images found in repository ghcr.io/org/app

Generate and Scan an SBOM

A Software Bill of Materials (SBOM) lists all packages, libraries, and binaries contained in an image. Generating an SBOM enables deeper analysis, dependency tracking, and automated remediation workflows.

Docker Scout can generate an SBOM from an image and immediately scan it for known vulnerabilities:

docker scout cve myregistry.io/myapp:2024.07.15

Alternatively, the SBOM can be generated separately and fed into any scanner that accepts SBOM input formats (CycloneDX, SPDX, or Syft JSON):

docker scout generate sbom myregistry.io/myapp:2024.07.15 > sbom.json
trivy fs --format json sbom.json

The docker scout generate sbom command walks the image’s manifest and layer diff to produce a comprehensive inventory. This inventory includes package names, versions, ecosystem identifiers (e.g., maven, pypi, npm), and relationship metadata. The resulting SBOM can be stored in an artifact repository, committed to version control, or pipelined into a policy engine.

Integrate into CI/CD Pipelines

Container image scanning is most effective when invoked as a step in the build or promotion pipeline. The typical pattern is: build the image, push to a registry, then scan before any deployment manifest is applied.

In a GitHub Actions workflow, the pattern looks like this:

name: Image Scanning

on:
  push:
    branches: [ main ]
  pull_request:

jobs:
  scan:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Build and push Docker image
        uses: docker/build-push-action@v5
        with:
          context: .
          push: true
          tags: myregistry.io/myapp:${{ github.sha }}

      - name: Scan image with Trivy
        trivy-action/gha-trivy@master
        with:
          image: myregistry.io/myapp:${{ github.sha }}
          format: 'table'
          exit-code: '1'
          severity: 'HIGH,CRITICAL'

The trivy-action step pulls the freshly pushed image, runs the scanner, and exits with status 1 if any findings match the configured severity. This blocks merge or deployment until the image passes the threshold.

In Jenkins pipelines, the equivalent uses the trivy CLI directly:

stage('Scan Image') {
    steps {
        script {
            def img = "myregistry.io/myapp:${env.BUILD_ID}"
            sh "trivy image --severity HIGH,CRITICAL --exit-code 1 $img"
        }
    }
}

If the trivy command returns a non-zero exit code, the stage fails and the pipeline halts. The console output includes the full findings table, which Jenkins archives as a build artifact for downstream review.

Enforce Policy Beyond CVE

Scanning is not limited to CVE lookup. Most scanners support policy-as-code rules that check for runtime misconfigurations, secrets, and base-image compliance.

A typical policy check verifies that the image does not run as root, does not expose privileged ports, and uses a distroless or minimal base. In Trivy, this is expressed through the --policy flag with a YAML or Rego rule file:

trivy image --policy policies.yaml myregistry.io/myapp:2024.07.15

A policies.yaml file might contain:

# policies.yaml
deny:
  - cap: NET_RAW
    message: "Image should not have NET_RAW capability"
  - user: root
    message: "Image should not run as root"
  - port: "22/tcp"
    message: "SSH port should not be exposed"

When a policy violation is found, trivy reports it alongside any CVE findings, with a distinct severity label (POLICY):

POLICY   user: root   Image should not run as root

Policy files can be version-controlled and updated independently of scanner releases, allowing organizations to codify their security baselines without waiting for a new scanner version.

Sharp Edges and Gotchas

SBOM coverage gaps

Not every layer of every image is captured in an SBOM. If an image was built from a Dockerfile that uses COPY --from to pull artifacts from a multi-stage build, the intermediate layers may not be included in the final SBOM unless the scanner explicitly follows the full dependency chain. Trivy’s --scanning-mode flag controls whether it scans only the final filesystem or also intermediate layers, but behavior varies by image structure.

Severity misalignment

CVE severity ratings are assigned by the CVE Numbering Authority (CNA) and may not match your organization’s risk appetite. A vulnerability labeled "HIGH" by one vendor might be "MEDIUM" in another database. Scanners allow you to configure which sources contribute to the severity calculation and how they are weighted. If your team uses custom severity mappings, ensure the scanner’s --severity filter reflects those mappings, not the upstream CNA ratings.

Cache staleness

Scanners cache downloaded vulnerability feeds and parsed image layers to speed up repeated scans. If the vulnerability database is updated between scans but the local cache is not invalidated, newly published CVEs may be missed. Trivy respects the TRIVY_CACHE_DIR environment variable and provides a --no-cache flag to force a fresh fetch. In CI pipelines, it is prudent to clear or rotate the cache periodically, especially when a new CVE batch is released.

Language-specific detector limitations

Language-specific detectors (Python pip, Node npm, Ruby gem, etc.) rely on lockfiles or manifest files present in the image. If the image was built without a lockfile—e.g., pip install was used without requirements.txt—the detector may report "no requirements found" and skip the layer entirely, leaving packages unscanned. Conversely, if a lockfile pins an outdated version that has since been updated, the scanner will flag it as vulnerable even though the image was built with the latest released version at that time. Review the lockfile strategy for each language ecosystem in your images.

Network-dependent failure

Scanners require access to vulnerability feeds (OSV, NVD, or commercial feeds). In air-gapped or restricted environments, the scan may hang or timeout waiting for a network request. Trivy supports a local vulnerability database mirror via the TRIVY_VULN_DB flag, but setting this up requires an initial synchronized download from an online source. Plan for offline scan modes by maintaining a local mirror and configuring the scanner to prefer it with --offline.

False positives from transitive dependencies

A scanner may report a vulnerability in a transitive dependency that is never actually imported at runtime. For example, a Python image might list pytest in requirements.txt for testing purposes, but the production runtime never imports pytest. The scanner has no way to know the dependency is unused without runtime instrumentation. Some teams configure --ignore-unfixed to suppress vulnerabilities without a known fix, but this does not address unused dependencies. Policy reviews and dependency tree analysis are needed to separate reported findings from actual runtime risk.

Misconfigured skip-layers

Trivy and other scanners allow excluding specific layers or packages via --skip-layers or --skip-packages. If these are misconfigured—e.g., skipping a layer that contains a critical system library—the scanner will silently ignore findings in that layer. Always verify the skip-list contents and run a baseline scan without skips periodically to ensure no critical categories are being systematically ignored.

Build-time vs. runtime vulnerability surfaces

An image may scan clean at build time but acquire vulnerabilities later. If the base image is updated with a new CVE-fix release and the image is rebuilt without pinning the base tag, the new image will inherit the fix. However, if the image uses a fixed base tag (e.g., python:3.11-slim@sha256:...), the scanner will always see the same packages regardless of upstream fixes. Pinning base images with immutable digests is a recommended practice, but it means the scanner will not surface new CVEs in the base until the digest is updated. Track base image updates separately from image-specific scanning.

Conclusion

Container image scanning is a foundational devsecops practice, but its effectiveness depends on how it is configured, integrated, and maintained. Use real commands—trivy image, docker scout cve, trivy repo—with precise flags (--severity, --exit-code, --policy) to embed scanning into your pipelines. Anticipate the sharp edges: SBOM gaps, severity drift, cache staleness, language detector blind spots, network dependencies, skip-list misconfiguration, and base-image tagging strategy. Scan early, scan often, and treat scanner exit codes as pipeline gatekeepers. The goal is not zero findings—no scanner achieves that—but rather visibility, control, and a repeatable process for surfacing what matters before an image reaches production.

This page was rewritten on 12 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.