Scan Container Images for Vulnerabilities

Khimananda Oli 7 min read Database
Scan Container Images for Vulnerabilities

By Khimananda Oli | Last reviewed: August 2026

You cannot secure what you do not inspect, yet many teams still push unverified containers to production. To effectively scan container images for vulnerabilities, you must integrate automated scanners directly into your CI/CD pipeline as a blocking quality gate rather than an afterthought. This shifts security left, ensuring that every artifact deployed to your Amazon EKS or on-premise Kubernetes cluster has been validated against current CVE databases before it ever reaches a registry.

Code CommitGit Push / PRBuild ImageDocker / BuildpacksScan ImageTrivy / GrypePolicy GatePush RegistryECR / Harbor / GHCRFAIL: High/Crit CVE FoundPASS: Clean / Accepted Risk
CI/CD workflow to scan container images for vulnerabilities with automated pass/fail policy gates before registry push

How Do You Scan Container Images for Vulnerabilities in CI/CD?

Integrating scanning into your build pipeline is the single most effective control in modern DevSecOps. The goal is not just to generate a report but to enforce a security standard automatically. In practice, this means running a scanner immediately after the image is built but before it is tagged as latest or pushed to a shared registry. If the scan fails your defined policy, the pipeline must halt.

Step-by-Step GitHub Actions Integration

Trivy remains the industry standard for 2026 due to its comprehensive database coverage and SBOM support. Below is a production-grade configuration that scans an image and fails the build if critical vulnerabilities are detected.

name: Container Security Scan
on: [push]

jobs:
  build-and-scan:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Build Docker image
        run: docker build -t myapp:${{ github.sha }} .

      - name: Run Trivy vulnerability scanner
        uses: aquasecurity/trivy-action@master
        with:
          image-ref: 'myapp:${{ github.sha }}'
          format: 'table'
          exit-code: '1'
          ignore-unfixed: true
          vuln-type: 'os,library'
          severity: 'CRITICAL,HIGH'

      - name: Push to Registry
        if: success()
        run: |
          echo "${{ secrets.REGISTRY_PASSWORD }}" | docker login -u "${{ secrets.REGISTRY_USER }}" --password-stdin
          docker push myapp:${{ github.sha }}

The critical parameter here is exit-code: '1'. Without this, Trivy prints warnings but allows the pipeline to continue. Setting ignore-unfixed: true reduces noise by only flagging vulnerabilities that actually have a patch available, preventing developer fatigue from unfixable upstream issues.

Handling False Positives and Exceptions

No scanner is perfect. You will encounter false positives or accepted risks. Create a .trivyignore file in your repository root to document and suppress specific CVEs. This serves as an audit trail for compliance frameworks like SOC 2 or ISO 27001.

# .trivyignore
# CVE-2024-1234: False positive in libssl, verified by vendor advisory
CVE-2024-1234

# CVE-2023-5678: Accepted risk until Q3 migration, ticket JIRA-4521
CVE-2023-5678

Which Tools Best Scan Container Images for Vulnerabilities?

Choosing the right scanner depends on your ecosystem, compliance needs, and performance requirements. While many tools exist, three dominate the 2026 landscape for practical engineering use.

FeatureTrivyGrypeSnyk Container
Primary StrengthAll-in-one (OS, Lang, IaC, Secrets)SBOM-first scanning speedDeveloper remediation advice
Database SourceAqua DB + NVD + Multiple AdvisoriesNVD + OS Vendor FeedsProprietary Snyk Intel DB
SBOM SupportGenerate & Scan (CycloneDX/SPDX)Native SBOM ScanningLimited Proprietary Format
CI PerformanceModerate (~30-60s)Fast (~10-20s with SBOM)Variable (API dependent)
CostOpen Source (Apache 2.0)Open Source (Apache 2.0)Commercial (Free Tier Limited)
Best ForGeneral purpose, compliance auditsHigh-volume pipelines, SBOM workflowsTeams needing fix prioritization

In my experience managing multi-cloud environments, I recommend starting with Trivy for its breadth. If your pipeline becomes bottlenecked on scanning latency, introduce Grype specifically for SBOM-based scanning as a secondary fast-pass filter. Reserve commercial tools like Snyk when your team lacks security expertise and needs hand-holding on remediation paths.

Traditional Layer ScanningExtract Filesystem LayersParse Package Managers (dpkg/rpm)Match Against CVE DatabaseResult: Misses Nested/Custom AppsSBOM-Based ScanningGenerate SPDX/CycloneDX at BuildIngest Structured Component ListCorrelate Transitive DependenciesResult: Complete Supply Chain View
Layer scanning versus SBOM analysis when you scan container images for vulnerabilities in complex applications

What Severity Thresholds Should Block Production Deploys?

A common mistake is setting the bar too high initially, which leads to immediate pipeline breakage and team frustration. Conversely, setting it too low creates a false sense of security. For most production workloads in 2026, I recommend a tiered approach aligned with vulnerability management automation principles.

  • CRITICAL + HIGH (Fixed): Always block. These represent active exploitation risk with available patches. No exceptions without documented sign-off.
  • HIGH (Unfixed): Warn in PR comments, block after 7-day grace period. This gives teams time to find workarounds or wait for upstream fixes.
  • MEDIUM: Report only. Track trends in your Grafana dashboards but do not break builds unless count exceeds baseline.
  • LOW / UNKNOWN: Log for audit purposes. Never block CI for these unless operating in regulated environments like fintech or healthcare.

This policy balances security rigor with development velocity. Remember that a blocked pipeline costs money; ensure every block is actionable. If your team consistently ignores warnings, your threshold is wrong or your remediation path is unclear.

How Does SBOM Improve Container Image Scanning Accuracy?

Software Bill of Materials (SBOM) transforms scanning from filesystem guessing to structured data analysis. Traditional scanners unpack layers and try to identify packages heuristically. This misses statically compiled binaries, vendored dependencies, and custom-built components. An SBOM generated during the build process provides an exact manifest of every component, version, and relationship.

Generating and Scanning SBOMs with Syft and Grype

The modern pattern separates generation from scanning. Use Syft to create the SBOM as a build artifact, then use Grype to scan that SBOM. This decouples the expensive generation step from the scanning step, allowing you to rescan the same SBOM against updated vulnerability databases without rebuilding the image.

# Generate SBOM during build stage
syft packages docker:myapp:${SHA} -o cyclonedx-json > sbom.json

# Scan SBOM separately (fast, repeatable)
grype sbom:sbom.json --fail-on high

# Attach SBOM to image metadata for compliance
cosign attach sbom --sbom sbom.json myapp:${SHA}

For teams pursuing ISO 27001 or SOC 2 compliance, attaching signed SBOMs to your container images provides auditable proof of supply chain integrity. This aligns with SBOM generation best practices and satisfies increasingly strict regulatory requirements in Nepal's growing fintech sector and global markets alike.

Scan CompleteCritical/High Fixed CVE?YESNOBLOCK PIPELINEFail Build / Notify TeamUnfixed High CVE?YESNOGRACE PERIOD (7d)Warn + Create TicketALLOW DEPLOYLog Medium/Low OnlyRe-evaluate After Expiry
Policy decision tree for scan container images for vulnerabilities results in automated CI/CD gates

How Do You Maintain Vulnerability Databases in Air-Gapped Environments?

Many organizations in Nepal and regulated industries operate in restricted network environments where scanners cannot reach public CVE databases. Offline scanning requires pre-downloaded vulnerability feeds and careful synchronization.

Trivy supports offline mode through its Java DB and vulnerability database archives. Download these on a connected machine and transfer them securely to your air-gapped CI runners.

# On internet-connected machine
trivy image --download-db-only
tar -czvf trivy-db.tar.gz ~/.cache/trivy/db

# On air-gapped runner
mkdir -p ~/.cache/trivy/db
tar -xzvf trivy-db.tar.gz -C ~/.cache/trivy/db

# Scan without network access
trivy image --skip-update --offline-scan myapp:latest

Schedule weekly database transfers via secure media or approved transfer protocols. Document this process in your server security hardening runbooks. Stale databases are worse than no scanning, so implement monitoring to alert when the local DB age exceeds your acceptable threshold.

Implementing Sustainable Container Scanning Practices

To successfully scan container images for vulnerabilities long-term, treat scanning as infrastructure, not a checkbox. Automate database updates, tune severity policies based on real incident data, and integrate results into your existing observability stack. Start with Trivy in your CI pipeline today using the configurations above, then evolve toward SBOM-driven workflows as your maturity grows. If your team needs help designing compliant scanning architectures or tuning policies for your specific risk profile, reach out to discuss your container security strategy.

Frequently Asked Questions

Trivy remains the industry standard in 2026 for scanning container images for vulnerabilities due to its comprehensive database coverage, SBOM generation capabilities, and native integration with CI pipelines like GitHub Actions and GitLab CI without requiring a dedicated server.

Add the aquasecurity/trivy-action step after your docker build command. Configure severity thresholds to fail the pipeline on HIGH or CRITICAL findings, ensuring vulnerable images never reach your production registry or deployment environment.

Yes. Most scanners support local tarball or daemon scanning. Use trivy image --input image.tar or point directly to the local Docker socket to validate security posture before consuming network bandwidth or registry storage quotas.

SAST analyzes source code for flaws before compilation. Scanning container images for vulnerabilities inspects compiled binaries, OS packages, and dependencies in the final artifact, catching supply chain risks and outdated base layers that static analysis misses.

Daily. New CVEs emerge constantly. Configure automated nightly rescans against your production registry tags to detect newly disclosed vulnerabilities in previously safe images, triggering alerts or patch workflows immediately upon discovery.

Typically adds thirty to ninety seconds. Mitigate this by enabling layer caching, skipping unchanged base images, and running scans in parallel with unit tests to maintain fast feedback loops without sacrificing security visibility.

Create an ignore policy file referencing specific CVE IDs with justification and expiry dates. Review these exceptions quarterly during security audits to ensure valid risks are not permanently suppressed while reducing developer alert fatigue.

Both are excellent. Grype excels at matching against existing SBOMs generated by Syft, while Trivy offers broader out-of-the-box misconfiguration checks. Choose based on whether you prioritize pure vulnerability matching or comprehensive platform security assessment.

Block CRITICAL and HIGH severities by default. Allow MEDIUM with documented acceptance tickets. Never block LOW unless compliance mandates it, as excessive blocking causes teams to disable scanning entirely rather than fix actual risks.

Yes. Ensure your scanner has access to private registries via authenticated tokens. Proprietary bases still contain open source components and OS packages that require regular vulnerability assessment against public CVE databases.

Adopt distroless or Alpine base images to minimize attack surface. Implement virtual patching via runtime protection tools when immediate rebuilds are impossible, buying time for proper remediation without exposing production systems.

Not primarily. While some scanners include secret detection, dedicated tools like Gitleaks or TruffleHog specialize in credential scanning. Combine both approaches for comprehensive security coverage across code, configuration, and container artifacts.

SARIF or CycloneDX. These standardized formats integrate with security dashboards, enable trend analysis across repositories, and satisfy compliance reporting requirements without custom parsing logic or vendor lock-in.

For regulated industries, yes. Paid tools offer SLA-backed database updates, priority support, and compliance certifications. For most startups and mid-market teams, open source scanners provide sufficient coverage when properly configured and maintained.

Use Renovate or Dependabot to submit pull requests updating base images and dependencies when fixes are available. Pair with automated CI scans to validate patches resolve issues without introducing regressions before merging.