container-scanning

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Container Scanning

容器镜像扫描

Scan container images for vulnerabilities and security misconfigurations.
扫描容器镜像中的漏洞和安全配置错误。

When to Use This Skill

何时使用此技能

Use this skill when:
  • Building container images
  • Implementing container security gates
  • Scanning registry images
  • Meeting compliance requirements
  • Hardening container deployments
在以下场景使用此技能:
  • 构建容器镜像时
  • 实施容器安全网关时
  • 扫描镜像仓库中的镜像时
  • 满足合规要求时
  • 加固容器部署时

Prerequisites

前提条件

  • Container runtime (Docker, Podman)
  • Container images to scan
  • Scanning tool installation
  • 容器运行时(Docker、Podman)
  • 待扫描的容器镜像
  • 已安装扫描工具

Tool Comparison

工具对比

ToolLicenseSpeedFeatures
TrivyOSSFastComprehensive, IaC
GrypeOSSFastAccurate, SBOM
ClairOSSMediumRegistry integration
Snyk ContainerCommercialFastFix suggestions
Docker ScoutCommercialFastGitHub integration
工具许可协议扫描速度功能特性
Trivy开源(OSS)快速全面覆盖,支持基础设施即代码(IaC)
Grype开源(OSS)快速精准检测,支持软件物料清单(SBOM)
Clair开源(OSS)中等镜像仓库集成
Snyk Container商业版快速提供修复建议
Docker Scout商业版快速GitHub集成

Trivy

Trivy

Installation

安装步骤

bash
undefined
bash
undefined

Linux

Linux

macOS

macOS

brew install trivy
brew install trivy

Docker

Docker

docker pull aquasec/trivy
undefined
docker pull aquasec/trivy
undefined

Image Scanning

镜像扫描

bash
undefined
bash
undefined

Scan local image

Scan local image

trivy image myapp:latest
trivy image myapp:latest

Scan remote image

Scan remote image

trivy image nginx:1.25
trivy image nginx:1.25

JSON output

JSON output

trivy image --format json -o results.json myapp:latest
trivy image --format json -o results.json myapp:latest

Filter by severity

Filter by severity

trivy image --severity HIGH,CRITICAL myapp:latest
trivy image --severity HIGH,CRITICAL myapp:latest

Ignore unfixed vulnerabilities

Ignore unfixed vulnerabilities

trivy image --ignore-unfixed myapp:latest
trivy image --ignore-unfixed myapp:latest

Exit code on vulnerability

Exit code on vulnerability

trivy image --exit-code 1 --severity CRITICAL myapp:latest
undefined
trivy image --exit-code 1 --severity CRITICAL myapp:latest
undefined

Filesystem Scanning

文件系统扫描

bash
undefined
bash
undefined

Scan project directory

Scan project directory

trivy fs /path/to/project
trivy fs /path/to/project

Scan Dockerfile

Scan Dockerfile

trivy config Dockerfile
trivy config Dockerfile

Scan Kubernetes manifests

Scan Kubernetes manifests

trivy config k8s/
undefined
trivy config k8s/
undefined

Configuration

配置

yaml
undefined
yaml
undefined

trivy.yaml

trivy.yaml

timeout: 10m severity:
  • HIGH
  • CRITICAL ignore-unfixed: true exit-code: 1
vulnerability: type: - os - library
scan: file-patterns: - "Dockerfile" - "*.yaml"
undefined
timeout: 10m severity:
  • HIGH
  • CRITICAL ignore-unfixed: true exit-code: 1
vulnerability: type: - os - library
scan: file-patterns: - "Dockerfile" - "*.yaml"
undefined

CI Integration

CI集成

yaml
undefined
yaml
undefined

GitHub Actions

GitHub Actions

name: Container Security
on: push: branches: [main] pull_request:
jobs: scan: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4
  - name: Build image
    run: docker build -t myapp:${{ github.sha }} .

  - name: Run Trivy
    uses: aquasecurity/trivy-action@master
    with:
      image-ref: 'myapp:${{ github.sha }}'
      format: 'sarif'
      output: 'trivy-results.sarif'
      severity: 'CRITICAL,HIGH'
      exit-code: '1'

  - name: Upload results
    uses: github/codeql-action/upload-sarif@v3
    with:
      sarif_file: 'trivy-results.sarif'
undefined
name: Container Security
on: push: branches: [main] pull_request:
jobs: scan: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4
  - name: Build image
    run: docker build -t myapp:${{ github.sha }} .

  - name: Run Trivy
    uses: aquasecurity/trivy-action@master
    with:
      image-ref: 'myapp:${{ github.sha }}'
      format: 'sarif'
      output: 'trivy-results.sarif'
      severity: 'CRITICAL,HIGH'
      exit-code: '1'

  - name: Upload results
    uses: github/codeql-action/upload-sarif@v3
    with:
      sarif_file: 'trivy-results.sarif'
undefined

Grype

Grype

Installation

安装步骤

bash
undefined
bash
undefined

Linux/macOS

Linux/macOS

Homebrew

Homebrew

brew install grype
undefined
brew install grype
undefined

Usage

使用方法

bash
undefined
bash
undefined

Scan image

Scan image

grype myapp:latest
grype myapp:latest

Scan from SBOM

Scan from SBOM

grype sbom:./sbom.json
grype sbom:./sbom.json

JSON output

JSON output

grype myapp:latest -o json > results.json
grype myapp:latest -o json > results.json

Filter severity

Filter severity

grype myapp:latest --fail-on high
grype myapp:latest --fail-on high

Scan directory

Scan directory

grype dir:/path/to/project
undefined
grype dir:/path/to/project
undefined

Configuration

配置

yaml
undefined
yaml
undefined

.grype.yaml

.grype.yaml

check-for-app-update: false fail-on-severity: high output: "json" scope: "Squashed"
ignore:
  • vulnerability: CVE-2023-12345 reason: "False positive" expires: "2024-12-31"
undefined
check-for-app-update: false fail-on-severity: high output: "json" scope: "Squashed"
ignore:
  • vulnerability: CVE-2023-12345 reason: "False positive" expires: "2024-12-31"
undefined

Docker Scout

Docker Scout

Usage

使用方法

bash
undefined
bash
undefined

Enable Docker Scout

Enable Docker Scout

docker scout quickview myapp:latest
docker scout quickview myapp:latest

Full CVE report

Full CVE report

docker scout cves myapp:latest
docker scout cves myapp:latest

Compare images

Compare images

docker scout compare myapp:v1 myapp:v2
docker scout compare myapp:v1 myapp:v2

Recommendations

Recommendations

docker scout recommendations myapp:latest
undefined
docker scout recommendations myapp:latest
undefined

CI Integration

CI集成

yaml
- name: Docker Scout
  uses: docker/scout-action@v1
  with:
    command: cves
    image: ${{ env.IMAGE_NAME }}
    sarif-file: scout-results.sarif
    summary: true
yaml
- name: Docker Scout
  uses: docker/scout-action@v1
  with:
    command: cves
    image: ${{ env.IMAGE_NAME }}
    sarif-file: scout-results.sarif
    summary: true

Registry Integration

镜像仓库集成

Amazon ECR

亚马逊ECR

bash
undefined
bash
undefined

Enable scan on push

Enable scan on push

aws ecr put-image-scanning-configuration
--repository-name myapp
--image-scanning-configuration scanOnPush=true
aws ecr put-image-scanning-configuration
--repository-name myapp
--image-scanning-configuration scanOnPush=true

Get scan findings

Get scan findings

aws ecr describe-image-scan-findings
--repository-name myapp
--image-id imageTag=latest
aws ecr describe-image-scan-findings
--repository-name myapp
--image-id imageTag=latest

Start manual scan

Start manual scan

aws ecr start-image-scan
--repository-name myapp
--image-id imageTag=latest
undefined
aws ecr start-image-scan
--repository-name myapp
--image-id imageTag=latest
undefined

Azure ACR

Azure容器注册表(ACR)

bash
undefined
bash
undefined

Enable Defender for Containers

Enable Defender for Containers

az security pricing create
--name Containers
--tier Standard
az security pricing create
--name Containers
--tier Standard

View scan results in Azure Portal or:

View scan results in Azure Portal or:

az acr repository show
--name myregistry
--image myapp:latest
undefined
az acr repository show
--name myregistry
--image myapp:latest
undefined

Google Artifact Registry

谷歌Artifact Registry

bash
undefined
bash
undefined

Enable vulnerability scanning

Enable vulnerability scanning

gcloud artifacts repositories update myrepo
--location=us-central1
--enable-vulnerability-scanning
gcloud artifacts repositories update myrepo
--location=us-central1
--enable-vulnerability-scanning

View vulnerabilities

View vulnerabilities

gcloud artifacts docker images describe
us-central1-docker.pkg.dev/project/myrepo/myapp:latest
--show-package-vulnerability
undefined
gcloud artifacts docker images describe
us-central1-docker.pkg.dev/project/myrepo/myapp:latest
--show-package-vulnerability
undefined

Admission Controllers

准入控制器

OPA Gatekeeper

OPA Gatekeeper

yaml
apiVersion: templates.gatekeeper.sh/v1beta1
kind: ConstraintTemplate
metadata:
  name: k8sallowedrepos
spec:
  crd:
    spec:
      names:
        kind: K8sAllowedRepos
      validation:
        openAPIV3Schema:
          properties:
            repos:
              type: array
              items:
                type: string
  targets:
    - target: admission.k8s.gatekeeper.sh
      rego: |
        package k8sallowedrepos
        
        violation[{"msg": msg}] {
          container := input.review.object.spec.containers[_]
          satisfied := [good | repo = input.parameters.repos[_]; good = startswith(container.image, repo)]
          not any(satisfied)
          msg := sprintf("container <%v> has an invalid image repo <%v>", [container.name, container.image])
        }
yaml
apiVersion: templates.gatekeeper.sh/v1beta1
kind: ConstraintTemplate
metadata:
  name: k8sallowedrepos
spec:
  crd:
    spec:
      names:
        kind: K8sAllowedRepos
      validation:
        openAPIV3Schema:
          properties:
            repos:
              type: array
              items:
                type: string
  targets:
    - target: admission.k8s.gatekeeper.sh
      rego: |
        package k8sallowedrepos
        
        violation[{"msg": msg}] {
          container := input.review.object.spec.containers[_]
          satisfied := [good | repo = input.parameters.repos[_]; good = startswith(container.image, repo)]
          not any(satisfied)
          msg := sprintf("container <%v> has an invalid image repo <%v>", [container.name, container.image])
        }

Kyverno

Kyverno

yaml
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: require-image-scan
spec:
  validationFailureAction: enforce
  rules:
    - name: check-vulnerabilities
      match:
        resources:
          kinds:
            - Pod
      verifyImages:
        - image: "*"
          attestations:
            - predicateType: cosign.sigstore.dev/attestation/vuln/v1
              conditions:
                - all:
                    - key: "{{ scanner.result.summary.criticalCount }}"
                      operator: Equals
                      value: "0"
yaml
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: require-image-scan
spec:
  validationFailureAction: enforce
  rules:
    - name: check-vulnerabilities
      match:
        resources:
          kinds:
            - Pod
      verifyImages:
        - image: "*"
          attestations:
            - predicateType: cosign.sigstore.dev/attestation/vuln/v1
              conditions:
                - all:
                    - key: "{{ scanner.result.summary.criticalCount }}"
                      operator: Equals
                      value: "0"

Scanning Policies

扫描策略

Policy Definition

策略定义

yaml
undefined
yaml
undefined

scan-policy.yaml

scan-policy.yaml

policies:
  • name: critical-vulnerabilities description: Block images with critical CVEs severity: CRITICAL action: block
  • name: high-vulnerabilities description: Warn on high severity CVEs severity: HIGH action: warn max_count: 5
  • name: age-policy description: Block images older than 30 days max_age_days: 30 action: block
  • name: base-image description: Only allow approved base images allowed_bases:
    • alpine:3.18
    • ubuntu:22.04
    • python:3.11-slim
undefined
policies:
  • name: critical-vulnerabilities description: Block images with critical CVEs severity: CRITICAL action: block
  • name: high-vulnerabilities description: Warn on high severity CVEs severity: HIGH action: warn max_count: 5
  • name: age-policy description: Block images older than 30 days max_age_days: 30 action: block
  • name: base-image description: Only allow approved base images allowed_bases:
    • alpine:3.18
    • ubuntu:22.04
    • python:3.11-slim
undefined

Common Issues

常见问题

Issue: False Positives

问题:误报

Problem: Scanner reports non-exploitable vulnerabilities Solution: Use ignore files, validate with context
问题:扫描工具报告了无法被利用的漏洞 解决方案:使用忽略文件,结合上下文验证结果

Issue: Slow Scans

问题:扫描速度慢

Problem: Scanning takes too long Solution: Use caching, scan incrementally, optimize image layers
问题:扫描耗时过长 解决方案:使用缓存、增量扫描、优化镜像层

Issue: Unfixed Vulnerabilities

问题:无法修复的漏洞

Problem: No patch available for CVE Solution: Update base image, implement compensating controls
问题:CVE暂无可用补丁 解决方案:更新基础镜像,实施补偿控制措施

Best Practices

最佳实践

  • Scan in CI/CD pipeline
  • Use minimal base images (Alpine, distroless)
  • Update base images regularly
  • Implement admission control
  • Track vulnerabilities over time
  • Set severity thresholds
  • Document accepted risks
  • Use multi-stage builds
  • 在CI/CD流水线中执行扫描
  • 使用轻量基础镜像(Alpine、distroless)
  • 定期更新基础镜像
  • 实施准入控制
  • 持续跟踪漏洞变化
  • 设置严重程度阈值
  • 记录已接受的风险
  • 使用多阶段构建

Related Skills

相关技能

  • docker-management - Container basics
  • container-hardening - Security hardening
  • kubernetes-hardening - K8s security
  • docker-management - 容器基础操作
  • container-hardening - 容器安全加固
  • kubernetes-hardening - Kubernetes安全加固