Shift-Left Container Security
Container images are the deployment unit of modern applications, but they are also a major attack vector. A single vulnerable base image can expose your entire production environment to known exploits.
The solution is shift-left security: scanning container images for vulnerabilities during the build process, before they ever reach production. Trivy, an open-source scanner from Aqua Security, has become the industry standard for this purpose.
This guide walks you through integrating Trivy into your CI/CD pipeline for automated, continuous container security scanning.
Why Trivy
Several container scanners exist -- Grype, Snyk Container, Clair, and cloud-native options like ECR scanning. Trivy stands out for several reasons:
Comprehensive scanning: Trivy scans OS packages, language-specific dependencies (npm, pip, gem, go modules), IaC files, and even Kubernetes manifests in a single tool.
Speed: A typical image scan completes in 10-30 seconds, fast enough to run on every commit without slowing down your pipeline.
No daemon required: Unlike some scanners, Trivy runs as a standalone binary. No server setup, no database to maintain.
Excellent vulnerability database: Trivy pulls from multiple sources including NVD, Red Hat, Debian, Ubuntu, Alpine, and language-specific advisory databases. Updates happen automatically.
Setting Up Trivy Locally
Before integrating into CI/CD, start by scanning images locally to understand the output and tune your policies.
Installation
Trivy installs easily on any platform: - Linux/Mac: Use Homebrew, apt, or download the binary directly - Docker: Run Trivy itself as a container - Windows: Download the binary or use WSL
Basic Image Scan
Scan a Docker image to see all vulnerabilities: - Trivy reports vulnerabilities by severity: CRITICAL, HIGH, MEDIUM, LOW - Each finding includes the CVE ID, affected package, installed version, and fixed version - Results are grouped by the layer that introduced the vulnerability
Filtering by Severity
In practice, you cannot fix every vulnerability immediately. Focus on what matters: - Block builds only on CRITICAL and HIGH severity findings - Report MEDIUM findings for tracking but do not block - Ignore LOW findings unless they affect sensitive components
CI/CD Integration Patterns
GitHub Actions
Add Trivy scanning as a step in your GitHub Actions workflow: - Scan the image after the Docker build step - Upload results as a SARIF file for GitHub Security tab integration - Fail the workflow if CRITICAL vulnerabilities are found - Cache the Trivy vulnerability database to speed up subsequent runs
GitLab CI
Trivy integrates natively with GitLab's security dashboard: - Use the Trivy GitLab template for standardized output - Results appear in the GitLab Security Dashboard automatically - Merge requests show new vulnerabilities introduced by the change
Jenkins
For Jenkins pipelines: - Run Trivy as a Docker container in the pipeline - Parse the JSON output for threshold-based gating - Publish results as build artifacts for audit trails - Integrate with Jenkins warnings plugin for trend tracking
Policy Configuration
Severity-Based Gating
Configure different policies for different environments: - Development builds: Warn on HIGH and CRITICAL, do not block - Staging deploys: Block on CRITICAL, warn on HIGH - Production deploys: Block on CRITICAL and HIGH with no known fix exceptions
Ignore Files
Not every CVE is exploitable in your context. Use Trivy's ignore file to suppress specific findings: - Document why each CVE is suppressed - Set expiration dates on suppressions (review quarterly) - Require team lead approval for any suppression
Custom Policies with OPA
For advanced use cases, write custom policies using Open Policy Agent: - Block images from untrusted registries - Require specific base image versions - Enforce maximum image age policies - Validate image labels and metadata
Scanning Beyond Container Images
Filesystem Scanning
Scan your source code repository for vulnerable dependencies before building the image: - Catches vulnerabilities in package.json, requirements.txt, go.mod, and Gemfile - Faster than building and scanning the full image - Useful as a pre-commit hook or early pipeline stage
IaC Scanning
Trivy also scans Infrastructure as Code files: - Terraform configurations for security misconfigurations - Kubernetes manifests for pod security violations - Dockerfiles for best practice violations (running as root, using latest tag) - CloudFormation templates for insecure resource configurations
SBOM Generation
Generate Software Bill of Materials (SBOM) for compliance: - CycloneDX and SPDX format support - Required for supply chain security compliance - Useful for tracking which images contain which dependencies
Operationalizing Container Security
Registry Scanning
Do not rely solely on build-time scanning. New CVEs are disclosed daily: - Enable automatic scanning in your container registry (ECR, ACR, GCR, Harbor) - Schedule weekly re-scans of all production images - Alert when new CRITICAL CVEs affect running images
Admission Control
Add a final enforcement point in your Kubernetes cluster: - Deploy Kyverno or OPA Gatekeeper as an admission controller - Reject pods that reference images with unresolved CRITICAL vulnerabilities - Require images to have been scanned within the last 7 days
Metrics and Reporting
Track your container security posture over time: - Mean time to remediate critical vulnerabilities - Percentage of images passing security gates on first scan - Trend of total vulnerabilities across your image portfolio - Number of suppressed CVEs and their expiration status
Getting Started
- Day 1: Install Trivy locally and scan your most critical production images
- Week 1: Add Trivy scanning to one CI/CD pipeline with CRITICAL-only blocking
- Week 2: Expand to all pipelines, add HIGH blocking for production
- Week 3: Enable registry scanning and admission control
- Ongoing: Review suppression list quarterly, track metrics monthly
Scaling Container Security Across the Enterprise
For a single team running one pipeline, Trivy integration is straightforward. The real challenge emerges when you need to roll out container security scanning across dozens or hundreds of pipelines spanning multiple teams, business units, and regions. This is the reality facing CTOs and VPs of Engineering at enterprises in the USA, Europe, and the Middle East.
Centralized Scanning Templates
Rather than asking every team to configure Trivy independently, build reusable pipeline templates that encapsulate your organization's security policies:
- Create a shared CI/CD library (GitHub Actions reusable workflows, GitLab CI templates, or Jenkins shared libraries) that wraps Trivy with your organization's default severity thresholds, ignore file conventions, and output formats
- Teams consume the template with a single include statement -- they get security scanning without needing to understand Trivy configuration
- Updates to scanning policies propagate automatically when the shared template is updated, ensuring consistency across all pipelines
This approach reduces configuration drift and ensures that a policy change -- such as tightening the severity threshold from CRITICAL-only to CRITICAL+HIGH -- rolls out uniformly.
Developer Experience Matters
Security tools that slow down developers or produce noisy results get disabled. Invest in developer experience:
- Fast feedback: Cache the Trivy vulnerability database in your CI/CD environment. A cold database download adds 30-60 seconds; a cached scan completes in under 15 seconds
- Clear remediation guidance: Configure Trivy output to include the fixed version for each vulnerability so developers know exactly what to upgrade
- IDE integration: Encourage developers to run Trivy locally before pushing. This reduces the number of build failures caused by security gates and puts remediation in the developer's hands earlier
- Noise reduction: Maintain a curated, organization-wide ignore file for CVEs that have been reviewed and determined to be non-exploitable in your context. This prevents the same false positives from frustrating multiple teams
Handling Base Image Vulnerabilities
A significant percentage of vulnerabilities flagged by Trivy originate from the base image rather than your application code. Establish a clear ownership model:
- Platform team responsibility: Maintain a catalog of approved, regularly patched base images (distroless, Alpine, or your own hardened images)
- Application team responsibility: Keep application dependencies updated and respond to vulnerabilities in packages they introduce
- Automated base image updates: Use tools like Dependabot or Renovate to create pull requests when new base image versions are available, triggering a fresh Trivy scan to validate the update
This division of responsibility prevents the common situation where application teams feel powerless over vulnerabilities they did not introduce.
Integrating Trivy with Kubernetes Admission Control
Build-time scanning is your first line of defense, but it cannot catch vulnerabilities disclosed after an image is built. Admission control is the enforcement layer that prevents vulnerable images from running in your Kubernetes clusters.
Kyverno Image Verification Policies
Deploy Kyverno policies that query scan results before admitting a pod:
- Require that every image has been scanned within the last 7 days
- Block images with unresolved CRITICAL vulnerabilities from production namespaces
- Allow exceptions for system components (kube-system) with appropriate audit logging
Connecting Scan Results to Admission Decisions
Use a scan results store that both your CI/CD pipeline and admission controller can query:
- Trivy scans produce results stored in a centralized database or OCI registry (using Trivy's SBOM attestation feature)
- The admission controller queries this store when a new pod is scheduled
- If the image has no recent scan results or has unresolved critical findings, the pod is rejected with a clear error message pointing the developer to remediation steps
Measuring Container Security Program Maturity
To justify continued investment in container security -- and to demonstrate progress to leadership and auditors -- track these metrics monthly:
Leading Indicators
- Scan coverage: Percentage of production images that have been scanned in the last 7 days (target: 100%)
- Mean time to scan: Average time from image build to scan results availability (target: under 2 minutes)
- First-pass rate: Percentage of builds that pass the security gate on the first attempt (improving trend indicates better developer awareness)
Lagging Indicators
- Mean time to remediate (MTTR): Average time from vulnerability disclosure to patched image deployed in production. Track separately for CRITICAL (target: 48 hours) and HIGH (target: 7 days)
- Vulnerability debt: Total count of known, unresolved vulnerabilities across all production images, segmented by severity
- Suppression hygiene: Number of suppressed CVEs, percentage with valid expiration dates, percentage reviewed on schedule
Present these metrics in a monthly security posture report. The trend matters more than the absolute numbers -- leadership wants to see continuous improvement. Organizations pursuing comprehensive cloud security should integrate these container-level metrics into their broader security dashboard alongside infrastructure and application-layer findings.
At Optivulnix, container security scanning is a core component of our DevSecOps practice. We help teams build security into their pipelines without slowing down delivery. Contact us for a free DevSecOps maturity assessment.


