How do you implement container image security scanning in a CI/CD pipeline?
Container image security scanning is a critical component of modern DevSecOps pipelines that detects vulnerabilities in container images before they reach production.
Why Scan Container Images?
- Detect CVEs (Common Vulnerabilities and Exposures) in OS packages and application dependencies
- Ensure base images are up-to-date and patched
- Enforce compliance requirements
- Prevent vulnerable images from reaching production
Common Scanning Tools
Trivy (Recommended)
Open-source, comprehensive vulnerability scanner by Aqua Security.
# GitHub Actions example
- name: Run Trivy vulnerability scanner
uses: aquasecurity/trivy-action@master
with:
image-ref: 'my-registry/my-app:${{ github.sha }}'
format: 'sarif'
exit-code: '1'
severity: 'CRITICAL,HIGH'
output: 'trivy-results.sarif'Grype
Open-source vulnerability scanner by Anchore.
grype my-registry/my-app:latest --fail-on criticalSnyk
Commercial tool with broad language and container support.
snyk container test my-registry/my-app:latest \
--file=Dockerfile --severity-threshold=highECR Image Scanning (AWS)
AWS provides native scanning via Amazon Inspector or basic ECR scanning for images pushed to ECR.
Integration Strategies
Shift Left Approach
- Build stage: Scan immediately after
docker build - Registry push gate: Block push if critical CVEs found
- Continuous monitoring: Re-scan images in registry periodically
Sample Pipeline Stage (GitHub Actions)
jobs:
build-and-scan:
steps:
- name: Build image
run: docker build -t myapp:${{ github.sha }} .
- name: Scan image
run: |
trivy image --exit-code 1 \
--severity CRITICAL,HIGH \
myapp:${{ github.sha }}
- name: Push image (only if scan passes)
run: docker push myapp:${{ github.sha }}Best Practices
- Use minimal base images (distroless, alpine) to reduce attack surface
- Set severity thresholds – block on CRITICAL, warn on HIGH
- Scan at multiple stages: Dockerfile, built image, registry, runtime
- Update base images regularly in Dockerfile
- Ignore false positives using
.trivyignorewith tracked justifications - Integrate SBOM (Software Bill of Materials) generation alongside scanning