Skip to content

镜像漏洞扫描

定期扫描镜像中的已知漏洞是安全最佳实践。

Docker Scout

Docker Scout 是 Docker 官方提供的镜像扫描工具。

安装

sh
# Docker Desktop 已内置
# 或使用 Docker CLI 插件
docker scout --version

扫描镜像

sh
# 扫描本地镜像
docker scout cves nginx:latest

# 扫描并生成报告
docker scout cves --format sarif nginx:latest > report.sarif

Trivy

Trivy 是一个流行的容器安全扫描工具。

安装

sh
# 使用包管理器
sudo apt-get install trivy  # Debian/Ubuntu
brew install trivy  # macOS

# 或使用 Docker
docker run aquasec/trivy image nginx:latest

使用

sh
# 扫描镜像
trivy image nginx:latest

# 扫描并输出 JSON
trivy image --format json nginx:latest

# 扫描并生成报告
trivy image --format template --template "@contrib/gitlab.tpl" \
  -o gl-container-scanning-report.json nginx:latest

集成到 CI/CD

GitHub Actions

yaml
- name: Run Trivy vulnerability scanner
  uses: aquasecurity/trivy-action@master
  with:
    image-ref: 'nginx:latest'
    format: 'sarif'
    output: 'trivy-results.sarif'

GitLab CI

yaml
trivy:
  image: aquasec/trivy:latest
  script:
    - trivy image --exit-code 0 --severity HIGH,CRITICAL nginx:latest

自动化扫描

构建时扫描

dockerfile
# 使用多阶段构建
FROM alpine:latest AS scanner
RUN apk add --no-cache trivy
COPY --from=build /app /app
RUN trivy fs --exit-code 1 --severity HIGH,CRITICAL /app

定期扫描

sh
#!/bin/bash
# scan.sh
for image in $(docker images --format "{{.Repository}}:{{.Tag}}"); do
  docker scout cves $image
done

最佳实践

  1. 定期扫描 - 设置自动化扫描任务
  2. 修复漏洞 - 及时更新基础镜像
  3. 集成 CI/CD - 构建时自动扫描
  4. 监控告警 - 发现高危漏洞及时告警
  5. 使用最小镜像 - 减少攻击面

警告

发现高危漏洞应该立即修复,不要在生产环境使用存在已知漏洞的镜像。


由 BSFC Tech 提供技术支持