Skip to main content

Command Palette

Search for a command to run...

How to Scan Container Images in AWS Using ECR Image Scanning + Inspector

Published
9 min read
How to Scan Container Images in AWS Using ECR Image Scanning + Inspector
G

I am experienced Cloud Devops Engineer I blog about Solutions, Cloud and DevOps Projects that boost your portfolio and provide troubleshooting guides on Cloud and DevOps

A practical guide to implementing automated container vulnerability scanning in AWS


Introduction

Container security is no longer optional—it's a critical requirement for modern cloud applications. Vulnerabilities in container images can expose your entire infrastructure to security risks, data breaches, and compliance violations.

AWS addresses this challenge with two powerful services that work seamlessly together:

Amazon ECR (Elastic Container Registry) - Your Secure Container Registry

Amazon ECR is AWS's fully managed container registry service for storing, managing, and deploying container images. Unlike public registries, ECR provides:

  • Private, Encrypted Storage: Images encrypted at rest (AWS KMS) and in transit (HTTPS)

  • Fine-Grained Access Control: IAM integration for precise permissions

  • Lifecycle Management: Automatic cleanup of old images to reduce costs and security risks

  • High Availability: Built on AWS infrastructure with cross-region replication

  • Native AWS Integration: Seamless integration with ECS, EKS, Lambda, and other services

Most importantly, ECR includes built-in image scanning that automatically checks images for vulnerabilities the moment they're pushed—no additional tools required.

Amazon Inspector v2 - Continuous Vulnerability Management

Amazon Inspector v2 represents a significant leap forward from traditional vulnerability scanners. Here's why:

Continuous Monitoring: Unlike one-time scans, Inspector automatically rescans images whenever new CVEs are published—even for images pushed months ago. You're protected against newly discovered vulnerabilities without manual intervention.

Deep Package Analysis: Inspector analyzes:

  • Operating system packages (apt, yum, apk)

  • Language-specific libraries (npm, pip, maven, gem)

  • Application dependencies across all image layers

  • Transitive dependencies other tools often miss

Software Bill of Materials (SBOM): Automatically generates and maintains a complete inventory of every software component in your images—critical for compliance and supply chain security.

Intelligent Prioritization: Inspector provides CVSS scores, exploit availability indicators, network reachability analysis, and fix recommendations to help you prioritize remediation.

Zero Configuration: Once enabled, Inspector automatically discovers and monitors all ECR repositories. No agents to install, no complex rules to configure.

Cost-Effective: Simple per-image-per-month pricing ($0.09 per image) makes costs predictable, even for large-scale deployments.

How They Work Together

When you combine ECR and Inspector v2, you get an automated security pipeline:

  1. Developer pushes a container image to ECR

  2. ECR triggers an immediate Inspector scan

  3. Inspector analyzes all layers, packages, and dependencies

  4. Findings are published with severity levels (CRITICAL, HIGH, MEDIUM, LOW)

  5. EventBridge routes critical findings to your team via SNS, Slack, or email

  6. Inspector continues monitoring—if a new CVE is discovered tomorrow, you're notified immediately

This guide shows you the complete workflow: from creating a repository to viewing scan results and setting up automated alerts—so you can implement production-grade container security in less than 30 minutes.

What You'll Build:

  • ✅ ECR repository with automatic scanning enabled

  • ✅ Sample containerized application demonstrating real vulnerabilities

  • ✅ Automated vulnerability detection with Inspector v2

  • ✅ Real-time email alerts for critical findings

  • ✅ CloudWatch dashboard for tracking security posture

  • ✅ Production-ready best practices

Time to Complete: ~30 minutes
Estimated Cost: ~$2 for testing (covered by AWS Free Tier)

Prerequisites

You'll Need:

  • AWS account with admin access

  • AWS CLI installed and configured

  • Docker installed locally

  • Basic knowledge of containers and AWS

AWS Permissions Required: ECR, Inspector, SNS, EventBridge


How It Works

Here's the complete flow:

Docker Image → ECR Repository → Inspector v2 Scan → Findings → Alerts

The Process:

  1. Push container image to ECR

  2. ECR triggers Inspector v2 scan automatically

  3. Inspector scans all layers for vulnerabilities

  4. Findings published with severity levels (CRITICAL, HIGH, MEDIUM, LOW)

  5. EventBridge routes high-severity findings to SNS

  6. Email alerts sent to your team


Step 1: Create ECR Repository

Create a repository with scanning enabled:

aws ecr create-repository \
  --repository-name sample-app \
  --image-scanning-configuration scanOnPush=true \
  --region us-east-1

Important: Note your repository URI from the output - you'll need it later:

123456789012.dkr.ecr.us-east-1.amazonaws.com/sample-app

Console Alternative: ECR → Create repository → Enable "Enhanced scanning"


Step 2: Enable Amazon Inspector v2

Enable Inspector for ECR scanning (one-time setup):

aws inspector2 enable \
  --resource-types ECR \
  --region us-east-1

Console Alternative: Inspector → Get started → Enable ECR scanning

Once enabled, Inspector automatically monitors all your ECR repositories and continuously scans for vulnerabilities.


Step 3: Create and Push a Sample Application

Create a simple Flask app with intentionally old packages to demonstrate scanning:

Create the Application Files

app.py:

from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/')
def home():
    return jsonify({'message': 'Container Scanner Demo'})

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

requirements.txt:

Flask==2.0.1
Werkzeug==2.2.2

Note: Using older versions to demonstrate vulnerability detection

Dockerfile:

FROM python:3.9-alpine
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app.py .
EXPOSE 5000
CMD ["python", "app.py"]

Build and Push to ECR

# Get your account ID
ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)

# Build image
docker build -t sample-app:v1.0 .

# Login to ECR
aws ecr get-login-password --region us-east-1 | \
  docker login --username AWS --password-stdin \
  $ACCOUNT_ID.dkr.ecr.us-east-1.amazonaws.com

# Tag and push
docker tag sample-app:v1.0 $ACCOUNT_ID.dkr.ecr.us-east-1.amazonaws.com/sample-app:v1.0
docker push $ACCOUNT_ID.dkr.ecr.us-east-1.amazonaws.com/sample-app:v1.0

What Happens Now: Inspector automatically scans your image (takes 2-5 minutes)


Step 4: View Scan Results

After 2-5 minutes, check your scan results.

In ECR Console

Navigate to ECR → Repositories → sample-app → Images

Click your image to see vulnerability summary:

  • Total vulnerabilities found

  • Breakdown by severity (CRITICAL, HIGH, MEDIUM, LOW)

Using CLI

# Get vulnerability counts
aws ecr describe-image-scan-findings \
  --repository-name sample-app \
  --image-id imageTag=v1.0 \
  --region us-east-1 \
  --query 'imageScanFindings.findingSeverityCounts'

Example output:

{
  "HIGH": 6,
  "MEDIUM": 8,
  "LOW": 2
}

View Details in Inspector

For detailed CVE information, go to Inspector → Findings

📸 SCREENSHOT LOCATION #12: Insert Inspector findings list

Click any finding to see:

  • CVE ID and description

  • CVSS score

  • Affected package and version

  • Fix recommendation

Example Finding:

CVE-2024-34069 - Werkzeug
Severity: HIGH (CVSS 7.5)
Package: werkzeug 2.2.2
Fix: Upgrade to 2.2.3

Step 5: Set Up Automated Alerts (Optional)

Get email notifications for high-severity vulnerabilities using EventBridge and SNS.

Create SNS Topic and Subscribe

# Create topic
aws sns create-topic --name container-vulns-high --region us-east-1

# Subscribe your email (replace with yours)
aws sns subscribe \
  --topic-arn arn:aws:sns:us-east-1:YOUR_ACCOUNT_ID:container-vulns-high \
  --protocol email \
  --notification-endpoint your-email@example.com \
  --region us-east-1

Check your email and confirm the subscription!

Create EventBridge Rule

# Route HIGH/CRITICAL findings to SNS
aws events put-rule \
  --name inspector-high-severity \
  --event-pattern '{
    "source": ["aws.inspector2"],
    "detail-type": ["Inspector2 Finding"],
    "detail": {"severity": ["HIGH", "CRITICAL"]}
  }' \
  --state ENABLED \
  --region us-east-1

# Add SNS as target
aws events put-targets \
  --rule inspector-high-severity \
  --targets "Id"="1","Arn"="arn:aws:sns:us-east-1:YOUR_ACCOUNT_ID:container-vulns-high" \
  --region us-east-1

Now you'll receive email alerts whenever HIGH or CRITICAL vulnerabilities are detected!

Monitoring Your Security Posture

Track vulnerabilities over time using Inspector's built-in dashboard and CloudWatch.

Inspector Dashboard

Navigate to Amazon InspectorDashboard to see:

  • Active findings by severity

  • Coverage status

  • Trends over time

Optional: CloudWatch Dashboard

Create a custom dashboard at CloudWatchDashboards:

  1. Add widget for Inspector findings count (by severity)

  2. Add widget for scan completion trends

  3. Add alarm for CRITICAL findings


Best Practices

1. Always Enable Scan-on-Push

aws ecr put-image-scanning-configuration \
  --repository-name your-repo \
  --image-scanning-configuration scanOnPush=true \
  --region us-east-1

2. Use Minimal Base Images

Reduce attack surface by using slim images:

FROM python:3.9-alpine  # Instead of python:3.9

3. Set Up Lifecycle Policies

Remove old, vulnerable images automatically:

# Keep only last 10 images
aws ecr put-lifecycle-policy \
  --repository-name sample-app \
  --lifecycle-policy-text '{
    "rules": [{
      "rulePriority": 1,
      "description": "Keep last 10 images",
      "selection": {
        "tagStatus": "any",
        "countType": "imageCountMoreThan",
        "countNumber": 10
      },
      "action": {"type": "expire"}
    }]
  }'

4. Integrate into CI/CD

Fail builds if critical vulnerabilities are found. Add this to your pipeline:

# Get findings after push
CRITICAL=$(aws ecr describe-image-scan-findings \
  --repository-name $REPO --image-id imageTag=$TAG \
  --query 'imageScanFindings.findingSeverityCounts.CRITICAL')

if [ "$CRITICAL" -gt 0 ]; then
  echo "Build failed: CRITICAL vulnerabilities detected"
  exit 1
fi

5. Regular Reviews

  • Weekly: Review HIGH/CRITICAL findings and update dependencies

  • Monthly: Audit MEDIUM findings and update base images


Troubleshooting

Scan Not Starting

Check if Inspector is enabled:

aws inspector2 batch-get-account-status --region us-east-1

Verify scan-on-push is enabled:

aws ecr describe-repositories --repository-names sample-app \
  --query 'repositories[0].imageScanningConfiguration'

No Findings Visible

Check via CLI (more reliable than console):

aws inspector2 list-findings \
  --filter-criteria '{"resourceType":[{"comparison":"EQUALS","value":"AWS_ECR_CONTAINER_IMAGE"}]}' \
  --max-results 10

Alerts Not Working

Verify SNS subscription is confirmed (check your email)

Check EventBridge rule status:

aws events describe-rule --name inspector-high-severity

Too Many Findings

Focus on CRITICAL/HIGH with fixes available:

aws inspector2 list-findings \
  --filter-criteria '{
    "severity": [{"comparison": "EQUALS", "value": "HIGH"}],
    "fixAvailable": [{"comparison": "EQUALS", "value": "YES"}]
  }'

Update your base image first - this usually fixes many CVEs at once.


Possible Causes:

  1. Image truly has no vulnerabilities (unlikely)

  2. Wrong region selected

  3. Filter applied in console

Solution:

# Check findings via CLI (more reliable)
aws inspector2 list-findings \
  --filter-criteria '{"resourceType":[{"comparison":"EQUALS","value":"AWS_ECR_CONTAINER_IMAGE"}]}' \
  --max-results 10 \
  --region us-east-1

# If no results, check if ECR repositories are being monitored
aws inspector2 list-coverage \
  --filter-criteria '{"resourceType":[{"comparison":"EQUALS","value":"AWS_ECR_REPOSITORY"}]}' \
  --region us-east-1

Issue 3: EventBridge Rule Not Triggering

Symptoms: Vulnerabilities detected but no email alerts received.

Possible Causes:

  1. SNS subscription not confirmed

  2. EventBridge rule disabled

  3. Incorrect event pattern

  4. Missing SNS permissions

Solution:

# Check rule status
aws events describe-rule \
  --name inspector-high-severity \
  --region us-east-1

# Verify targets
aws events list-targets-by-rule \
  --rule inspector-high-severity \
  --region us-east-1

# Check SNS subscription status
aws sns list-subscriptions-by-topic \
  --topic-arn <your-topic-arn> \
  --region us-east-1

# Look for "SubscriptionArn": "PendingConfirmation"
# If pending, check email and confirm

Issue 4: High Number of Findings

Symptoms: Hundreds of vulnerabilities detected, overwhelming.

Approach:

  1. Focus on CRITICAL and HIGH first

  2. Update base image (often fixes many CVEs)

  3. Update major dependencies

  4. Use .dockerignore to exclude unnecessary files

# Filter to actionable findings
aws inspector2 list-findings \
  --filter-criteria '{
    "severity": [
      {"comparison": "EQUALS", "value": "CRITICAL"},
      {"comparison": "EQUALS", "value": "HIGH"}
    ],
    "fixAvailable": [{"comparison": "EQUALS", "value": "YES"}]
  }' \
  --region us-east-1

Issue 5: Scan Taking Too Long

Symptoms: Scan stuck in IN_PROGRESS for >10 minutes.

Normal Duration: 2-5 minutes for most images

If longer:

  • Very large image (>5GB)

  • Many layers

  • Inspector backend delays (rare)

Solution:

  • Wait 15 minutes

  • If still stuck, retry:

      aws ecr start-image-scan \
        --repository-name sample-app \
        --image-id imageTag=v1.0 \
        --region us-east-1
    

Issue 6: False Positives

Symptoms: CVE reported but doesn't apply to your usage.

Example: Vulnerability in test dependency not in production image.

Solution:

  1. Verify it's truly a false positive

  2. Use multi-stage builds to exclude test dependencies

  3. Suppress the finding with documentation:

# Document suppression
aws securityhub batch-update-findings \
  --finding-identifiers Id=<finding-id> \
  --note '{"Text": "False positive - test dependency not in production", "UpdatedBy": "security-team"}' \
  --workflow Status=SUPPRESSED

Conclusion

You've successfully set up automated container vulnerability scanning with AWS ECR and Inspector v2!

Key Takeaways

  1. Inspector v2 provides continuous monitoring with deep OS and language package scanning

  2. Scan-on-push ensures every image is automatically checked

  3. Prioritize CRITICAL and HIGH severity vulnerabilities first

  4. Automate alerts so you never miss critical issues

  5. Update regularly - most vulnerabilities are fixed by updating base images

Resources

More from this blog

G

Godstime Chisom

22 posts

Cloud Engineer • DevOps • SRE •
I am Devops Engineer, I blog about Solutions to Devops/SRE Tasks. Be sure to find help and troubleshooting guides for DevOps-related topics here