Course contentsShow
← Docker, Kubernetes & CI/CD
Lesson 628 of 8029. CI/CD Pipeline EngineeringFree lesson

Scanning Container Images for Security Flaws

Integrate container image scanners like Trivy or Clair to identify OS-level vulnerabilities within build artifacts before they are pushed to the registry.

In this lesson, you will learn how to automate the detection of OS-level vulnerabilities by integrating scanning tools directly into your CI/CD pipeline before images reach your registry.

Why Pre-Push Scanning Matters

Even if your application code is secure, your container base image might contain unpatched system libraries (like openssl or glibc) with known CVEs (Common Vulnerabilities and Exposures). By shifting security left, we catch these flaws during the build phase. If an image fails the scan, we fail the build, preventing insecure artifacts from ever becoming candidates for deployment.

Integrating Trivy into the Pipeline

The most efficient way to achieve this is by running a scanner like Trivy immediately after the docker build step but before the docker push step. This ensures that the registry only hosts validated, secure images.

Consider this snippet for a typical CI job (e.g., in GitLab CI or GitHub Actions):

# Build the image first
docker build -t my-app:${CI_COMMIT_SHA} .

# Scan the image for vulnerabilities
# --exit-code 1 forces the build to fail if vulnerabilities are found
# --severity HIGH,CRITICAL ensures we only block on severe issues
trivy image --exit-code 1 --severity HIGH,CRITICAL my-app:${CI_COMMIT_SHA}

# Only proceed to push if the scan command above exits with code 0
docker push my-registry.com/my-app:${CI_COMMIT_SHA}

Strategic Implementation

When integrating scanners:

  1. Define Thresholds: Do not block builds for "Low" or "Medium" vulnerabilities initially, as this often leads to "alert fatigue" and stalled development. Focus on HIGH and CRITICAL findings.
  2. Use Cached Databases: To keep your pipelines fast, ensure your scanner fetches its vulnerability database from a local cache or a persistent volume so it isn't downloading large datasets on every single execution.
  3. Fail-Fast: By placing this scan before the docker push, you save bandwidth and maintain a "clean" registry, ensuring that your automated deployment processes only pull images that meet your security baseline.

Key Takeaway: Integrating an automated scanner like Trivy into your build process creates a critical quality gate that blocks vulnerable images from reaching your registry, ensuring only compliant artifacts are available for deployment.