docker-security-guide

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

🚨 CRITICAL GUIDELINES

🚨 关键指南

Windows File Path Requirements

Windows文件路径要求

MANDATORY: Always Use Backslashes on Windows for File Paths
When using Edit or Write tools on Windows, you MUST use backslashes (
\
) in file paths, NOT forward slashes (
/
).
Examples:
  • ❌ WRONG:
    D:/repos/project/file.tsx
  • ✅ CORRECT:
    D:\repos\project\file.tsx
This applies to:
  • Edit tool file_path parameter
  • Write tool file_path parameter
  • All file operations on Windows systems
⚠️ 强制要求:在Windows系统中使用文件路径时必须使用反斜杠
在Windows系统上使用编辑或写入工具时,文件路径必须使用反斜杠(
\
),而不能使用正斜杠(
/
)。
示例:
  • ❌ 错误:
    D:/repos/project/file.tsx
  • ✅ 正确:
    D:\repos\project\file.tsx
此要求适用于:
  • 编辑工具的file_path参数
  • 写入工具的file_path参数
  • Windows系统上的所有文件操作

Documentation Guidelines

文档指南

NEVER create new documentation files unless explicitly requested by the user.
  • Priority: Update existing README.md files rather than creating new documentation
  • Repository cleanliness: Keep repository root clean - only README.md unless user requests otherwise
  • Style: Documentation should be concise, direct, and professional - avoid AI-generated tone
  • User preference: Only create additional .md files when user specifically asks for documentation

除非用户明确要求,否则绝不要创建新的文档文件。
  • 优先级:优先更新现有README.md文件,而非创建新文档
  • 仓库整洁性:保持仓库根目录整洁——除非用户要求,否则仅保留README.md
  • 风格:文档应简洁、直接、专业——避免AI生成式语气
  • 用户偏好:仅当用户明确要求文档时,才创建额外的.md文件

Docker Security Guide

Docker安全指南

This skill provides comprehensive security guidelines for Docker across all platforms, covering threats, mitigations, and compliance requirements.
本指南提供跨平台的Docker全面安全规范,涵盖威胁、缓解措施及合规要求。

Security Principles

安全原则

Defense in Depth

纵深防御

Apply security at multiple layers:
  1. Image security: Minimal, scanned, signed images
  2. Build security: Secure build process, no secrets in layers
  3. Runtime security: Restricted capabilities, resource limits
  4. Network security: Isolation, least privilege
  5. Host security: Hardened host OS, updated Docker daemon
  6. Orchestration security: Secure configuration, RBAC
  7. Monitoring: Detection, logging, alerting
在多个层面应用安全措施:
  1. 镜像安全:最小化、已扫描、已签名的镜像
  2. 构建安全:安全的构建流程,镜像层中不包含密钥
  3. 运行时安全:受限的权限、资源限制
  4. 网络安全:隔离、最小权限
  5. 主机安全:加固的主机操作系统、已更新的Docker守护进程
  6. 编排安全:安全配置、RBAC(基于角色的访问控制)
  7. 监控:检测、日志记录、告警

Least Privilege

最小权限

Grant only the minimum permissions necessary:
  • Non-root users
  • Dropped capabilities
  • Read-only filesystems
  • Minimal network exposure
  • Restricted syscalls (seccomp)
  • Limited resources
仅授予必要的最低权限:
  • 非root用户
  • 移除不必要的内核能力
  • 只读文件系统
  • 最小化网络暴露
  • 受限的系统调用(seccomp)
  • 有限的资源

Image Security

镜像安全

Base Image Selection

基础镜像选择

Threat: Vulnerable or malicious base images
Mitigation:
dockerfile
undefined
威胁:存在漏洞或恶意的基础镜像
缓解措施:
dockerfile
undefined

Use official images only

仅使用官方镜像

FROM node:20.11.0-alpine3.19 # Official, specific version
FROM node:20.11.0-alpine3.19 # 官方、特定版本

NOT

不要使用

FROM randomuser/node # Unverified source FROM node:latest # Unpredictable, can break

**Verification:**
```bash
FROM randomuser/node # 未经验证的来源 FROM node:latest # 不可预测,可能导致故障

**验证:**
```bash

Verify image source

验证镜像来源

docker image inspect node:20-alpine | grep -A 5 "Author"
docker image inspect node:20-alpine | grep -A 5 "Author"

Enable Docker Content Trust (image signing)

启用Docker内容信任(镜像签名)

export DOCKER_CONTENT_TRUST=1 docker pull node:20-alpine
undefined
export DOCKER_CONTENT_TRUST=1 docker pull node:20-alpine
undefined

Minimal Images

最小化镜像

Threat: Larger attack surface, more vulnerabilities
Mitigation:
dockerfile
undefined
威胁:更大的攻击面、更多漏洞
缓解措施:
dockerfile
undefined

Prefer minimal distributions

优先选择最小化发行版

FROM alpine:3.19 # ~7MB FROM gcr.io/distroless/static # ~2MB FROM scratch # 0MB (for static binaries)
FROM alpine:3.19 # 约7MB FROM gcr.io/distroless/static # 约2MB FROM scratch # 0MB(适用于静态二进制文件)

vs

而非

FROM ubuntu:22.04 # ~77MB with more packages

**Benefits:**
- Fewer packages = fewer vulnerabilities
- Smaller attack surface
- Faster downloads and starts
- Less disk space
FROM ubuntu:22.04 # 约77MB,包含更多包

**优势:**
- 更少的包 = 更少的漏洞
- 更小的攻击面
- 更快的下载与启动速度
- 占用更少磁盘空间

Micro-Distros for Security-Critical Applications (2025)

安全关键应用的微发行版(2025)

Wolfi/Chainguard Images:
  • Zero-CVE goal, SBOM included by default
  • Nightly security patches, signed with provenance
  • Available for: Node, Python, Go, Java, .NET, etc.
Usage:
dockerfile
undefined
Wolfi/Chainguard镜像:
  • 零CVE漏洞目标,默认包含SBOM(软件物料清单)
  • 每日安全补丁,附带来源证明的签名
  • 支持:Node、Python、Go、Java、.NET等
使用示例:
dockerfile
undefined

Development stage (includes build tools)

开发阶段(包含构建工具)

FROM cgr.dev/chainguard/node:latest-dev AS builder WORKDIR /app COPY package*.json ./ RUN npm ci --only=production
FROM cgr.dev/chainguard/node:latest-dev AS builder WORKDIR /app COPY package*.json ./ RUN npm ci --only=production

Production stage (minimal, zero-CVE goal)

生产阶段(最小化,零CVE漏洞目标)

FROM cgr.dev/chainguard/node:latest WORKDIR /app COPY --from=builder /app/node_modules ./node_modules COPY . . USER node ENTRYPOINT ["node", "server.js"]

**When to use:** Security-critical apps, compliance requirements (SOC2, HIPAA, PCI-DSS), zero-trust environments, supply chain security emphasis.

See `docker-best-practices` skill for full image comparison table.
FROM cgr.dev/chainguard/node:latest WORKDIR /app COPY --from=builder /app/node_modules ./node_modules COPY . . USER node ENTRYPOINT ["node", "server.js"]

**适用场景:** 安全关键应用、合规要求(SOC2、HIPAA、PCI-DSS)、零信任环境、供应链安全重点场景。

查看`docker-best-practices`技能获取完整镜像对比表。

Vulnerability Scanning

漏洞扫描

Tools:
  • Docker Scout (built-in)
  • Trivy
  • Grype
  • Snyk
  • Clair
Process:
bash
undefined
工具:
  • Docker Scout(内置)
  • Trivy
  • Grype
  • Snyk
  • Clair
流程:
bash
undefined

Scan with Docker Scout

使用Docker Scout扫描

docker scout cves IMAGE_NAME docker scout recommendations IMAGE_NAME
docker scout cves IMAGE_NAME docker scout recommendations IMAGE_NAME

Scan with Trivy

使用Trivy扫描

trivy image IMAGE_NAME trivy image --severity HIGH,CRITICAL IMAGE_NAME
trivy image IMAGE_NAME trivy image --severity HIGH,CRITICAL IMAGE_NAME

Scan Dockerfile

扫描Dockerfile

trivy config Dockerfile
trivy config Dockerfile

Scan for secrets

扫描密钥

trivy fs --scanners secret .

**CI/CD Integration:**
```yaml
trivy fs --scanners secret .

**CI/CD集成:**
```yaml

GitHub Actions example

GitHub Actions示例

  • name: Scan image run: | docker scout cves my-image:${{ github.sha }} trivy image --exit-code 1 --severity CRITICAL my-image:${{ github.sha }}
undefined
  • name: Scan image run: | docker scout cves my-image:${{ github.sha }} trivy image --exit-code 1 --severity CRITICAL my-image:${{ github.sha }}
undefined

Multi-Stage Builds for Security

多阶段构建提升安全性

Threat: Build tools and secrets in final image
Mitigation:
dockerfile
undefined
威胁:最终镜像中包含构建工具与密钥
缓解措施:
dockerfile
undefined

Build stage with build tools

包含构建工具的构建阶段

FROM golang:1.21 AS builder WORKDIR /app COPY . . RUN go build -o app
FROM golang:1.21 AS builder WORKDIR /app COPY . . RUN go build -o app

Final stage - minimal, no build tools

最终阶段 - 最小化,无构建工具

FROM gcr.io/distroless/base-debian11 COPY --from=builder /app/app / USER nonroot:nonroot ENTRYPOINT ["/app"]

**Benefits:**
- No compiler/build tools in production image
- Secrets used in build don't persist
- Smaller, more secure final image
FROM gcr.io/distroless/base-debian11 COPY --from=builder /app/app / USER nonroot:nonroot ENTRYPOINT ["/app"]

**优势:**
- 生产镜像中无编译器/构建工具
- 构建中使用的密钥不会留存
- 最终镜像更小、更安全

Build-Time Security

构建时安全

Secrets Management

密钥管理

NEVER:
dockerfile
undefined
绝不要这样做:
dockerfile
undefined

BAD - Secret in layer history

错误 - 密钥存在于镜像层历史中

ENV API_KEY=abc123 RUN git clone https://user:password@github.com/repo.git COPY .env /app/.env

**DO:**
```dockerfile
ENV API_KEY=abc123 RUN git clone https://user:password@github.com/repo.git COPY .env /app/.env

**正确做法:**
```dockerfile

Use BuildKit secrets

使用BuildKit密钥

syntax=docker/dockerfile:1

syntax=docker/dockerfile:1

FROM alpine RUN --mount=type=secret,id=github_token
git clone https://$(cat /run/secrets/github_token)@github.com/repo.git

```bash
FROM alpine RUN --mount=type=secret,id=github_token
git clone https://$(cat /run/secrets/github_token)@github.com/repo.git

```bash

Build with secret (not in image)

使用密钥构建(密钥不会进入镜像)

docker build --secret id=github_token,src=./token.txt .
undefined
docker build --secret id=github_token,src=./token.txt .
undefined

BuildKit Frontend Security (2025)

BuildKit前端安全(2025)

Threat: Malicious or compromised BuildKit frontends can execute arbitrary code during build
🚨 2025 CRITICAL WARNING: BuildKit supports custom frontends (parsers) via
# syntax=
directive. Untrusted frontends have FULL BUILD-TIME code execution and can:
  • Steal secrets from build context
  • Modify build outputs
  • Exfiltrate data
  • Compromise the build environment
Risk Example:
dockerfile
undefined
威胁:恶意或被篡改的BuildKit前端可在构建期间执行任意代码
🚨 2025关键警告: BuildKit通过
# syntax=
指令支持自定义前端(解析器)。不可信的前端拥有完整的构建时代码执行权限,可能:
  • 窃取构建上下文中的密钥
  • 修改构建输出
  • 泄露数据
  • 攻陷构建环境
风险示例:
dockerfile
undefined

🔴 DANGER - Untrusted frontend (code execution risk!)

🔴 危险 - 不可信前端(存在代码执行风险!)

syntax=docker/dockerfile:1@sha256:abc123...untrusted

syntax=docker/dockerfile:1@sha256:abc123...untrusted

FROM alpine RUN echo "This frontend could do anything during build"

**Mitigation:**

1. **Only use official Docker frontends:**
```dockerfile
FROM alpine RUN echo "此前端在构建期间可执行任意操作"

**缓解措施:**

1. **仅使用官方Docker前端:**
```dockerfile

✅ Safe - Official Docker frontend

✅ 安全 - 官方Docker前端

syntax=docker/dockerfile:1

syntax=docker/dockerfile:1

✅ Safe - Specific version

✅ 安全 - 特定版本

syntax=docker/dockerfile:1.5

syntax=docker/dockerfile:1.5

✅ Safe - Pinned with digest (verify from docker.com)

✅ 安全 - 使用摘要固定版本(从docker.com验证)

syntax=docker/dockerfile:1@sha256:ac85f380a63b13dfcefa89046420e1781752bab202122f8f50032edf31be0021

syntax=docker/dockerfile:1@sha256:ac85f380a63b13dfcefa89046420e1781752bab202122f8f50032edf31be0021


2. **Verify frontend sources:**
- Use ONLY `docker/dockerfile:*` frontends
- Pin to specific versions with SHA256 digest
- Verify digests from official Docker documentation
- Never use third-party frontends without thorough vetting

3. **Audit all Dockerfiles for unsafe syntax directives:**
```bash

2. **验证前端来源:**
- 仅使用`docker/dockerfile:*`前端
- 使用SHA256摘要固定到特定版本
- 从官方Docker文档验证摘要
- 未经过彻底审查,绝不要使用第三方前端

3. **审计所有Dockerfile中的不安全语法指令:**
```bash

Check all Dockerfiles for potentially malicious syntax directives

检查所有Dockerfile中潜在的恶意语法指令

grep -r "^# syntax=" . --include="Dockerfile*"
grep -r "^# syntax=" . --include="Dockerfile*"

Verify all frontends are official Docker images

验证所有前端均为官方Docker镜像

grep -r "^# syntax=" . --include="Dockerfile*" | grep -v "docker/dockerfile"

4. **BuildKit security configuration (defense in depth):**
```bash
grep -r "^# syntax=" . --include="Dockerfile*" | grep -v "docker/dockerfile"

4. **BuildKit安全配置(纵深防御):**
```bash

Restrict frontend sources in BuildKit config

在BuildKit配置中限制前端来源

/etc/buildkit/buildkitd.toml

/etc/buildkit/buildkitd.toml

[frontend."dockerfile.v0"]

Only allow official Docker frontends

allowedImages = ["docker.io/docker/dockerfile:*"]

**Supply Chain Protection:**
- Treat custom frontends as HIGH RISK code execution vectors
- Review ALL `# syntax=` directives in Dockerfiles before builds
- Use content trust for frontend images
- Monitor for frontend vulnerabilities
- Include frontend verification in CI/CD security gates
[frontend."dockerfile.v0"]

仅允许官方Docker前端

allowedImages = ["docker.io/docker/dockerfile:*"]

**供应链防护:**
- 将自定义前端视为高风险代码执行载体
- 构建前审查所有Dockerfile中的`# syntax=`指令
- 对前端镜像使用内容信任
- 监控前端漏洞
- 在CI/CD安全网关中包含前端验证

SBOM (Software Bill of Materials) Generation (2025)

SBOM(软件物料清单)生成(2025)

Critical 2025 Requirement: Document origin and history of all components for supply chain transparency and compliance.
Why SBOM is Mandatory:
  • Supply chain security visibility
  • Vulnerability tracking and response
  • Compliance requirements (Executive Order 14028, etc.)
  • License compliance
  • Incident response readiness
Generate SBOM with Docker Scout:
bash
undefined
2025关键要求: 记录所有组件的来源与历史,以实现供应链透明性与合规性。
SBOM为强制要求的原因:
  • 供应链安全可见性
  • 漏洞跟踪与响应
  • 合规要求(行政令14028等)
  • 许可证合规
  • 事件响应准备
使用Docker Scout生成SBOM:
bash
undefined

Generate SBOM for image

为镜像生成SBOM

docker scout sbom IMAGE_NAME
docker scout sbom IMAGE_NAME

Export SBOM in different formats

导出不同格式的SBOM

docker scout sbom --format spdx IMAGE_NAME > sbom.spdx.json docker scout sbom --format cyclonedx IMAGE_NAME > sbom.cyclonedx.json
docker scout sbom --format spdx IMAGE_NAME > sbom.spdx.json docker scout sbom --format cyclonedx IMAGE_NAME > sbom.cyclonedx.json

Include SBOM attestation during build

构建期间包含SBOM证明

⚠️ WARNING: BuildKit attestations are NOT cryptographically signed!

⚠️ 警告:BuildKit证明不具备加密签名!

docker buildx build
--sbom=true
--provenance=true
--tag my-image:latest
.
docker buildx build
--sbom=true
--provenance=true
--tag my-image:latest
.

View SBOM attestations (unsigned metadata only)

查看SBOM证明(仅为未签名元数据)

docker buildx imagetools inspect my-image:latest --format "{{ json .SBOM }}"

**🚨 CRITICAL SECURITY LIMITATION:**
BuildKit attestations (`--sbom=true`, `--provenance=true`) are **NOT cryptographically signed**. This means:
- Anyone with push access can create tampered attestations
- SBOMs can be incomplete or falsified
- Provenance data cannot be trusted without external verification
- **For production:** Use external signing tools (cosign, Notary) and Syft for SBOM generation

**Generate SBOM with Syft:**
```bash
docker buildx imagetools inspect my-image:latest --format "{{ json .SBOM }}"

**🚨 关键安全限制:**
BuildKit证明(`--sbom=true`、`--provenance=true`)**不具备加密签名**。这意味着:
- 任何拥有推送权限的人都可创建被篡改的证明
- SBOM可能不完整或被伪造
- 来源数据无外部验证则不可信
- **生产环境:** 使用外部签名工具(cosign、Notary)和Syft生成SBOM

**使用Syft生成SBOM:**
```bash

Install Syft

安装Syft

Generate SBOM from image

从镜像生成SBOM

syft my-image:latest
syft my-image:latest

Generate in specific format

生成特定格式的SBOM

syft my-image:latest -o spdx-json > sbom.spdx.json syft my-image:latest -o cyclonedx-json > sbom.cyclonedx.json
syft my-image:latest -o spdx-json > sbom.spdx.json syft my-image:latest -o cyclonedx-json > sbom.cyclonedx.json

Generate from Dockerfile

从Dockerfile生成SBOM

syft dir:. -o spdx-json > sbom.spdx.json

**SBOM in CI/CD Pipeline:**
```yaml
syft dir:. -o spdx-json > sbom.spdx.json

**CI/CD流水线中的SBOM:**
```yaml

GitHub Actions example

GitHub Actions示例

name: Build with SBOM
jobs: build: steps: - name: Build image with SBOM run: | docker buildx build
--sbom=true
--provenance=true
--tag my-image:${{ github.sha }}
--push
.
  - name: Generate SBOM with Syft
    run: |
      syft my-image:${{ github.sha }} -o spdx-json > sbom.json

  - name: Upload SBOM artifact
    uses: actions/upload-artifact@v3
    with:
      name: sbom
      path: sbom.json

  - name: Scan SBOM for vulnerabilities
    run: |
      grype sbom:sbom.json --fail-on high

**SBOM Best Practices:**

1. **Generate for every image:**
   - Production images: mandatory
   - Development images: recommended
   - Base images: critical

2. **Store SBOMs with provenance:**
   - Version control alongside Dockerfile
   - Artifact registry with image
   - Dedicated SBOM repository

3. **Automate SBOM generation:**
   - Integrate into CI/CD pipeline
   - Generate on every build
   - Fail builds if SBOM generation fails

4. **Use SBOM for vulnerability management:**
```bash
name: Build with SBOM
jobs: build: steps: - name: Build image with SBOM run: | docker buildx build
--sbom=true
--provenance=true
--tag my-image:${{ github.sha }}
--push
.
  - name: Generate SBOM with Syft
    run: |
      syft my-image:${{ github.sha }} -o spdx-json > sbom.json

  - name: Upload SBOM artifact
    uses: actions/upload-artifact@v3
    with:
      name: sbom
      path: sbom.json

  - name: Scan SBOM for vulnerabilities
    run: |
      grype sbom:sbom.json --fail-on high

**SBOM最佳实践:**

1. **为每个镜像生成SBOM:**
   - 生产镜像:强制要求
   - 开发镜像:推荐
   - 基础镜像:关键

2. **随来源信息存储SBOM:**
   - 与Dockerfile一起存入版本控制
   - 与镜像一起存入制品仓库
   - 存入专用SBOM仓库

3. **自动化SBOM生成:**
   - 集成到CI/CD流水线
   - 每次构建都生成
   - 若SBOM生成失败则终止构建

4. **使用SBOM进行漏洞管理:**
```bash

Scan SBOM instead of image (faster)

扫描SBOM而非镜像(更快)

grype sbom:sbom.json trivy sbom sbom.json
grype sbom:sbom.json trivy sbom sbom.json

Compare SBOMs between versions

比较不同版本的SBOM

diff <(syft old-image:1.0 -o json) <(syft new-image:2.0 -o json)

5. **SBOM formats:**
   - **SPDX:** Industry standard, ISO/IEC 5962:2021
   - **CycloneDX:** OWASP standard, security-focused
   - Choose based on compliance requirements

**Chainguard Images with Built-in SBOM:**
```bash
diff <(syft old-image:1.0 -o json) <(syft new-image:2.0 -o json)

5. **SBOM格式:**
   - **SPDX**:行业标准,ISO/IEC 5962:2021
   - **CycloneDX**:OWASP标准,聚焦安全
   - 根据合规要求选择

**内置SBOM的Chainguard镜像:**
```bash

Chainguard images include SBOM attestation by default

Chainguard镜像默认包含SBOM证明

docker buildx imagetools inspect cgr.dev/chainguard/node:latest
docker buildx imagetools inspect cgr.dev/chainguard/node:latest

Extract SBOM

提取SBOM

cosign download sbom cgr.dev/chainguard/node:latest > chainguard-node-sbom.json

**Or use multi-stage and don't include secrets:**
```dockerfile
FROM node AS builder
ARG NPM_TOKEN
RUN echo "//registry.npmjs.org/:_authToken=${NPM_TOKEN}" > .npmrc && \
    npm install && \
    rm .npmrc  # Still in layer history!
cosign download sbom cgr.dev/chainguard/node:latest > chainguard-node-sbom.json

**或者使用多阶段构建且不包含密钥:**
```dockerfile
FROM node AS builder
ARG NPM_TOKEN
RUN echo "//registry.npmjs.org/:_authToken=${NPM_TOKEN}" > .npmrc && \
    npm install && \
    rm .npmrc  # 仍存在于镜像层历史中!

Better - secret only in build stage

更好的方式 - 密钥仅存在于构建阶段

FROM node AS dependencies RUN --mount=type=secret,id=npmrc,target=/root/.npmrc
npm install
FROM node AS runtime COPY --from=dependencies /app/node_modules ./node_modules
FROM node AS dependencies RUN --mount=type=secret,id=npmrc,target=/root/.npmrc
npm install
FROM node AS runtime COPY --from=dependencies /app/node_modules ./node_modules

No .npmrc in final image

最终镜像中无.npmrc

undefined
undefined

Secure Build Context

安全的构建上下文

Threat: Sensitive files included in build context
Mitigation: Create comprehensive
.dockerignore
:
undefined
威胁:构建上下文中包含敏感文件
缓解措施: 创建全面的
.dockerignore
文件:
undefined

Secrets

密钥

.env .env.local *.key *.pem credentials.json secrets/
.env .env.local *.key *.pem credentials.json secrets/

Version control

版本控制

.git .gitignore
.git .gitignore

Cloud credentials

云凭证

.aws/ .gcloud/
.aws/ .gcloud/

Private data

私有数据

database.sql backups/
database.sql backups/

SSH keys

SSH密钥

.ssh/ id_rsa id_rsa.pub
.ssh/ id_rsa id_rsa.pub

Sensitive logs

敏感日志

*.log logs/
undefined
*.log logs/
undefined

Image Signing

镜像签名

Enable Docker Content Trust:
bash
undefined
启用Docker内容信任:
bash
undefined

Enable image signing

启用镜像签名

export DOCKER_CONTENT_TRUST=1
export DOCKER_CONTENT_TRUST=1

Set up keys

设置密钥

docker trust key generate my-key docker trust signer add --key my-key.pub my-name my-image
docker trust key generate my-key docker trust signer add --key my-key.pub my-name my-image

Push signed image

推送已签名的镜像

docker push my-image:tag
docker push my-image:tag

Pull only signed images

仅拉取已签名的镜像

docker pull my-image:tag # Fails if not signed
undefined
docker pull my-image:tag # 若未签名则拉取失败
undefined

Runtime Security

运行时安全

User Privileges

用户权限

Threat: Container escape via root
Mitigation:
dockerfile
undefined
威胁:通过root用户逃逸容器
缓解措施:
dockerfile
undefined

Create and use non-root user

创建并使用非root用户

FROM node:20-alpine RUN addgroup -g 1001 appuser &&
adduser -S appuser -u 1001 -G appuser USER appuser WORKDIR /home/appuser/app COPY --chown=appuser:appuser . . CMD ["node", "server.js"]

**Verification:**
```bash
FROM node:20-alpine RUN addgroup -g 1001 appuser &&
adduser -S appuser -u 1001 -G appuser USER appuser WORKDIR /home/appuser/app COPY --chown=appuser:appuser . . CMD ["node", "server.js"]

**验证:**
```bash

Check user in running container

检查运行中容器的用户

docker exec container-name whoami # Should not be root docker exec container-name id # Check UID/GID
undefined
docker exec container-name whoami # 不应为root docker exec container-name id # 检查UID/GID
undefined

Capabilities

内核能力

Threat: Excessive kernel capabilities
Default Docker capabilities:
  • CHOWN, DAC_OVERRIDE, FOWNER, FSETID
  • KILL, SETGID, SETUID, SETPCAP
  • NET_BIND_SERVICE, NET_RAW
  • SYS_CHROOT, MKNOD, AUDIT_WRITE, SETFCAP
Mitigation:
bash
undefined
威胁:过度的内核能力
默认Docker内核能力:
  • CHOWN, DAC_OVERRIDE, FOWNER, FSETID
  • KILL, SETGID, SETUID, SETPCAP
  • NET_BIND_SERVICE, NET_RAW
  • SYS_CHROOT, MKNOD, AUDIT_WRITE, SETFCAP
缓解措施:
bash
undefined

Drop all, add only needed

移除所有能力,仅添加所需的

docker run
--cap-drop=ALL
--cap-add=NET_BIND_SERVICE
my-image

**In docker-compose.yml:**
```yaml
services:
  app:
    cap_drop:
      - ALL
    cap_add:
      - NET_BIND_SERVICE
Common needed capabilities:
  • NET_BIND_SERVICE
    : Bind to ports < 1024
  • NET_ADMIN
    : Network configuration
  • SYS_TIME
    : Set system time
docker run
--cap-drop=ALL
--cap-add=NET_BIND_SERVICE
my-image

**在docker-compose.yml中:**
```yaml
services:
  app:
    cap_drop:
      - ALL
    cap_add:
      - NET_BIND_SERVICE
常见所需能力:
  • NET_BIND_SERVICE
    :绑定到1024以下的端口
  • NET_ADMIN
    :网络配置
  • SYS_TIME
    :设置系统时间

Read-Only Filesystem

只读文件系统

Threat: Container modification, malware persistence
Mitigation:
bash
docker run \
  --read-only \
  --tmpfs /tmp:noexec,nosuid,size=64M \
  --tmpfs /var/run:noexec,nosuid,size=64M \
  my-image
In Compose:
yaml
services:
  app:
    read_only: true
    tmpfs:
      - /tmp:noexec,nosuid,size=64M
      - /var/run:noexec,nosuid,size=64M
威胁:容器被篡改、恶意软件持久化
缓解措施:
bash
docker run \
  --read-only \
  --tmpfs /tmp:noexec,nosuid,size=64M \
  --tmpfs /var/run:noexec,nosuid,size=64M \
  my-image
在Compose中:
yaml
services:
  app:
    read_only: true
    tmpfs:
      - /tmp:noexec,nosuid,size=64M
      - /var/run:noexec,nosuid,size=64M

Security Options

安全选项

no-new-privileges:
bash
docker run --security-opt="no-new-privileges:true" my-image
Prevents privilege escalation via setuid/setgid binaries.
AppArmor (Linux):
bash
docker run --security-opt="apparmor=docker-default" my-image
SELinux (Linux):
bash
docker run --security-opt="label=type:container_runtime_t" my-image
Seccomp (syscall filtering):
bash
undefined
no-new-privileges:
bash
docker run --security-opt="no-new-privileges:true" my-image
防止通过setuid/setgid二进制文件提升权限。
AppArmor(Linux):
bash
docker run --security-opt="apparmor=docker-default" my-image
SELinux(Linux):
bash
docker run --security-opt="label=type:container_runtime_t" my-image
Seccomp(系统调用过滤):
bash
undefined

Use default profile

使用默认配置文件

docker run --security-opt="seccomp=default" my-image
docker run --security-opt="seccomp=default" my-image

Or custom profile

或使用自定义配置文件

docker run --security-opt="seccomp=./seccomp-profile.json" my-image
undefined
docker run --security-opt="seccomp=./seccomp-profile.json" my-image
undefined

Resource Limits

资源限制

Threat: DoS via resource exhaustion
Mitigation:
bash
docker run \
  --memory="512m" \
  --memory-swap="512m" \  # Disable swap
  --cpus="1.0" \
  --pids-limit=100 \
  --ulimit nofile=1024:1024 \
  my-image
In Compose:
yaml
services:
  app:
    deploy:
      resources:
        limits:
          cpus: '1.0'
          memory: 512M
          pids: 100
        reservations:
          cpus: '0.5'
          memory: 256M
    ulimits:
      nofile:
        soft: 1024
        hard: 1024
威胁:通过资源耗尽实现DoS攻击
缓解措施:
bash
docker run \
  --memory="512m" \
  --memory-swap="512m" \  # 禁用swap
  --cpus="1.0" \
  --pids-limit=100 \
  --ulimit nofile=1024:1024 \
  my-image
在Compose中:
yaml
services:
  app:
    deploy:
      resources:
        limits:
          cpus: '1.0'
          memory: 512M
          pids: 100
        reservations:
          cpus: '0.5'
          memory: 256M
    ulimits:
      nofile:
        soft: 1024
        hard: 1024

Comprehensive Secure Run Command

全面的安全运行命令

bash
docker run \
  --name secure-app \
  --detach \
  --restart unless-stopped \
  --user 1000:1000 \
  --cap-drop=ALL \
  --cap-add=NET_BIND_SERVICE \
  --read-only \
  --tmpfs /tmp:noexec,nosuid,size=64M \
  --security-opt="no-new-privileges:true" \
  --security-opt="seccomp=default" \
  --memory="512m" \
  --cpus="1.0" \
  --pids-limit=100 \
  --network=isolated-network \
  --publish 127.0.0.1:8080:8080 \
  --volume secure-data:/data:ro \
  --health-cmd="curl -f http://localhost/health || exit 1" \
  --health-interval=30s \
  my-secure-image:1.2.3
bash
docker run \
  --name secure-app \
  --detach \
  --restart unless-stopped \
  --user 1000:1000 \
  --cap-drop=ALL \
  --cap-add=NET_BIND_SERVICE \
  --read-only \
  --tmpfs /tmp:noexec,nosuid,size=64M \
  --security-opt="no-new-privileges:true" \
  --security-opt="seccomp=default" \
  --memory="512m" \
  --cpus="1.0" \
  --pids-limit=100 \
  --network=isolated-network \
  --publish 127.0.0.1:8080:8080 \
  --volume secure-data:/data:ro \
  --health-cmd="curl -f http://localhost/health || exit 1" \
  --health-interval=30s \
  my-secure-image:1.2.3

Network Security

网络安全

Network Isolation

网络隔离

Threat: Lateral movement between containers
Mitigation:
yaml
networks:
  frontend:
    driver: bridge
  backend:
    driver: bridge
    internal: true  # No external access

services:
  web:
    networks:
      - frontend

  api:
    networks:
      - frontend
      - backend

  database:
    networks:
      - backend  # Isolated from frontend
威胁:容器间横向移动
缓解措施:
yaml
networks:
  frontend:
    driver: bridge
  backend:
    driver: bridge
    internal: true  # 无外部访问权限

services:
  web:
    networks:
      - frontend

  api:
    networks:
      - frontend
      - backend

  database:
    networks:
      - backend  # 与前端隔离

Port Exposure

端口暴露

Threat: Unnecessary network exposure
Mitigation:
bash
undefined
威胁:不必要的网络暴露
缓解措施:
bash
undefined

Bind to localhost only

仅绑定到本地主机

docker run -p 127.0.0.1:8080:8080 my-image
docker run -p 127.0.0.1:8080:8080 my-image

NOT (binds to all interfaces)

不要这样做(绑定到所有接口)

docker run -p 8080:8080 my-image

**In Compose:**
```yaml
services:
  app:
    ports:
      - "127.0.0.1:8080:8080"  # Localhost only
docker run -p 8080:8080 my-image

**在Compose中:**
```yaml
services:
  app:
    ports:
      - "127.0.0.1:8080:8080"  # 仅本地主机可访问

Inter-Container Communication

容器间通信

yaml
undefined
yaml
undefined

Disable default inter-container communication

禁用默认的容器间通信

/etc/docker/daemon.json

/etc/docker/daemon.json

{ "icc": false }

Then explicitly allow via networks:
```yaml
services:
  app1:
    networks:
      - app-network
  app2:
    networks:
      - app-network  # Can communicate with app1

networks:
  app-network:
    driver: bridge
{ "icc": false }

然后通过网络显式允许通信:
```yaml
services:
  app1:
    networks:
      - app-network
  app2:
    networks:
      - app-network  # 可与app1通信

networks:
  app-network:
    driver: bridge

Secrets Management

密钥管理

Docker Secrets (Swarm Mode)

Docker Secrets(Swarm模式)

bash
undefined
bash
undefined

Create secret

创建密钥

echo "mypassword" | docker secret create db_password -
echo "mypassword" | docker secret create db_password -

Use in service

在服务中使用密钥

docker service create
--name my-service
--secret db_password
my-image
docker service create
--name my-service
--secret db_password
my-image

Access in container at /run/secrets/db_password

在容器中通过/run/secrets/db_password访问密钥


**In stack file:**
```yaml
version: '3.8'

services:
  app:
    image: my-image
    secrets:
      - db_password

secrets:
  db_password:
    external: true

**在栈文件中:**
```yaml
version: '3.8'

services:
  app:
    image: my-image
    secrets:
      - db_password

secrets:
  db_password:
    external: true

Secrets Best Practices

密钥管理最佳实践

  1. Never in environment variables (visible in
    docker inspect
    )
  2. Never in images (in layer history)
  3. Never in version control (Git history)
  4. Mount as files with restricted permissions
  5. Use secret management systems (Vault, AWS Secrets Manager, etc.)
  6. Rotate regularly
Alternative: Mounted secrets:
bash
docker run -v /secure/secrets:/run/secrets:ro my-image
  1. 绝不要存放在环境变量中(可通过
    docker inspect
    查看)
  2. 绝不要存放在镜像中(存在于镜像层历史)
  3. 绝不要存放在版本控制中(Git历史)
  4. 以文件形式挂载,并设置受限权限
  5. 使用密钥管理系统(Vault、AWS Secrets Manager等)
  6. 定期轮换密钥
替代方案:挂载的密钥
bash
docker run -v /secure/secrets:/run/secrets:ro my-image

Compliance & Benchmarking

合规与基准测试

CIS Docker Benchmark

CIS Docker基准

Automated checking:
bash
undefined
自动化检查:
bash
undefined

Clone docker-bench-security

克隆docker-bench-security

git clone https://github.com/docker/docker-bench-security.git cd docker-bench-security sudo sh docker-bench-security.sh
git clone https://github.com/docker/docker-bench-security.git cd docker-bench-security sudo sh docker-bench-security.sh

Or run as container

或作为容器运行

docker run --rm --net host --pid host --userns host
--cap-add audit_control
-v /var/lib:/var/lib:ro
-v /var/run/docker.sock:/var/run/docker.sock:ro
-v /usr/lib/systemd:/usr/lib/systemd:ro
-v /etc:/etc:ro
docker/docker-bench-security
undefined
docker run --rm --net host --pid host --userns host
--cap-add audit_control
-v /var/lib:/var/lib:ro
-v /var/run/docker.sock:/var/run/docker.sock:ro
-v /usr/lib/systemd:/usr/lib/systemd:ro
-v /etc:/etc:ro
docker/docker-bench-security
undefined

Key CIS Recommendations

关键CIS建议

  1. Host Configuration
    • Keep Docker up to date
    • Restrict network traffic between containers
    • Set logging level to 'info'
    • Enable Docker Content Trust
  2. Docker Daemon
    • Use TLS for Docker daemon socket
    • Don't expose daemon on TCP without TLS
    • Enable user namespace support
  3. Docker Files
    • Verify Docker files ownership and permissions
    • Audit Docker files and directories
  4. Container Images
    • Create user for container
    • Use trusted base images
    • Don't install unnecessary packages
  5. Container Runtime
    • Run containers with limited privileges
    • Set resource limits
    • Don't share host network namespace
  1. 主机配置
    • 保持Docker为最新版本
    • 限制容器间的网络流量
    • 将日志级别设置为'info'
    • 启用Docker内容信任
  2. Docker守护进程
    • 对Docker守护进程套接字使用TLS
    • 不要在未使用TLS的情况下暴露守护进程到TCP
    • 启用用户命名空间支持
  3. Docker文件
    • 验证Docker文件的所有权与权限
    • 审计Docker文件与目录
  4. 容器镜像
    • 为容器创建专用用户
    • 使用可信的基础镜像
    • 不要安装不必要的包
  5. 容器运行时
    • 以受限权限运行容器
    • 设置资源限制
    • 不要共享主机网络命名空间

Monitoring & Detection

监控与检测

Logging

日志记录

yaml
services:
  app:
    logging:
      driver: "json-file"
      options:
        max-size: "10m"
        max-file: "3"
        labels: "service,env"
        env: "ENV,VERSION"
Centralized logging:
yaml
services:
  app:
    logging:
      driver: "syslog"
      options:
        syslog-address: "tcp://log-server:514"
        tag: "{{.Name}}/{{.ID}}"
yaml
services:
  app:
    logging:
      driver: "json-file"
      options:
        max-size: "10m"
        max-file: "3"
        labels: "service,env"
        env: "ENV,VERSION"
集中式日志:
yaml
services:
  app:
    logging:
      driver: "syslog"
      options:
        syslog-address: "tcp://log-server:514"
        tag: "{{.Name}}/{{.ID}}"

Runtime Monitoring

运行时监控

Tools:
  • Falco: Runtime security monitoring
  • Sysdig: Container visibility
  • Prometheus + cAdvisor: Metrics
  • Docker events: Real-time events
Monitor for:
  • Unexpected processes
  • File modifications
  • Network connections
  • Resource spikes
  • Failed authentication
  • Privilege escalation attempts
bash
undefined
工具:
  • Falco:运行时安全监控
  • Sysdig:容器可见性
  • Prometheus + cAdvisor:指标监控
  • Docker events:实时事件
监控重点:
  • 意外进程
  • 文件修改
  • 网络连接
  • 资源峰值
  • 认证失败
  • 权限提升尝试
bash
undefined

Monitor Docker events

监控Docker事件

docker events --filter 'type=container' --filter 'event=start'
docker events --filter 'type=container' --filter 'event=start'

Watch specific container

监控特定容器

docker events --filter "container=my-container"
docker events --filter "container=my-container"

Runtime security with Falco

使用Falco进行运行时安全监控

docker run --rm -it
--privileged
-v /var/run/docker.sock:/host/var/run/docker.sock
-v /dev:/host/dev
-v /proc:/host/proc:ro
falcosecurity/falco
undefined
docker run --rm -it
--privileged
-v /var/run/docker.sock:/host/var/run/docker.sock
-v /dev:/host/dev
-v /proc:/host/proc:ro
falcosecurity/falco
undefined

Platform-Specific Security

平台特定安全

Linux

Linux

User namespace remapping:
json
// /etc/docker/daemon.json
{
  "userns-remap": "default"
}
Benefits: Root in container → unprivileged on host
SELinux:
bash
undefined
用户命名空间映射:
json
// /etc/docker/daemon.json
{
  "userns-remap": "default"
}
优势:容器内的root用户对应主机上的非特权用户
SELinux:
bash
undefined

Enable SELinux for Docker

为Docker启用SELinux

setenforce 1
setenforce 1

Run with SELinux labels

使用SELinux标签运行容器

docker run --security-opt label=type:svirt_sandbox_file_t my-image
docker run --security-opt label=type:svirt_sandbox_file_t my-image

Volumes with SELinux

带SELinux的卷挂载

docker run -v /host/path:/container/path:z my-image

**AppArmor:**
```bash
docker run -v /host/path:/container/path:z my-image

**AppArmor:**
```bash

Check AppArmor status

检查AppArmor状态

aa-status
aa-status

Run with AppArmor profile

使用AppArmor配置文件运行容器

docker run --security-opt apparmor=docker-default my-image
undefined
docker run --security-opt apparmor=docker-default my-image
undefined

Windows

Windows

Hyper-V isolation:
powershell
undefined
Hyper-V隔离:
powershell
undefined

More isolated than process isolation

比进程隔离更安全

docker run --isolation=hyperv my-image

**Windows Defender:**
- Ensure real-time protection enabled
- Configure exclusions carefully
- Scan images regularly
docker run --isolation=hyperv my-image

**Windows Defender:**
- 确保实时保护已启用
- 谨慎配置排除项
- 定期扫描镜像

macOS

macOS

Docker Desktop security:
  • Keep Docker Desktop updated
  • Enable "Use gRPC FUSE for file sharing"
  • Limit file sharing to necessary paths
  • Review resource allocation
Docker Desktop安全:
  • 保持Docker Desktop为最新版本
  • 启用“Use gRPC FUSE for file sharing”
  • 限制文件共享到必要路径
  • 审查资源分配

Security Checklist

安全检查清单

Image:
  • Based on official, minimal image
  • Specific version tag (not
    latest
    )
  • Scanned for vulnerabilities
  • No secrets in layers
  • Runs as non-root user
  • Signed (Content Trust)
Build:
  • .dockerignore configured
  • Multi-stage build (if applicable)
  • Build secrets handled properly
  • Build from trusted sources only
Runtime:
  • Non-root user
  • Capabilities dropped
  • Read-only filesystem (where possible)
  • Security options set
  • Resource limits configured
  • Isolated network
  • Minimal port exposure
  • Secrets mounted securely
Operations:
  • CIS benchmark compliance
  • Logging configured
  • Monitoring in place
  • Regular vulnerability scans
  • Incident response plan
  • Regular updates
  • Audit logs enabled
镜像:
  • 基于官方、最小化镜像
  • 使用特定版本标签(非
    latest
  • 已扫描漏洞
  • 镜像层中无密钥
  • 以非root用户运行
  • 已签名(内容信任)
构建:
  • 已配置.dockerignore
  • 使用多阶段构建(如适用)
  • 构建密钥处理正确
  • 仅从可信源构建
运行时:
  • 使用非root用户
  • 已移除不必要的内核能力
  • 使用只读文件系统(如可行)
  • 已设置安全选项
  • 已配置资源限制
  • 使用隔离网络
  • 最小化端口暴露
  • 密钥已安全挂载
运维:
  • 符合CIS基准
  • 已配置日志记录
  • 已部署监控
  • 定期进行漏洞扫描
  • 具备事件响应计划
  • 定期更新
  • 已启用审计日志

Common Security Mistakes

常见安全错误

NEVER:
  • Run as root
  • Use
    --privileged
  • Mount Docker socket (
    /var/run/docker.sock
    )
  • Hardcode secrets
  • Use
    latest
    tag
  • Skip vulnerability scanning
  • Expose unnecessary ports
  • Disable security features
  • Ignore security updates
  • Trust unverified images
ALWAYS:
  • Run as non-root
  • Drop capabilities
  • Scan for vulnerabilities
  • Use secrets management
  • Tag with specific versions
  • Enable security options
  • Apply least privilege
  • Keep systems updated
  • Monitor runtime behavior
  • Use official images
This security guide represents current best practices. Security threats evolve constantly—always check the latest Docker security documentation and CVE databases.
绝不要这样做:
  • 以root用户运行
  • 使用
    --privileged
    参数
  • 挂载Docker套接字(
    /var/run/docker.sock
  • 硬编码密钥
  • 使用
    latest
    标签
  • 跳过漏洞扫描
  • 暴露不必要的端口
  • 禁用安全功能
  • 忽略安全更新
  • 信任未经验证的镜像
始终这样做:
  • 以非root用户运行
  • 移除不必要的内核能力
  • 扫描漏洞
  • 使用密钥管理
  • 使用特定版本标签
  • 启用安全选项
  • 应用最小权限原则
  • 保持系统更新
  • 监控运行时行为
  • 使用官方镜像
本安全指南代表当前最佳实践。安全威胁不断演变——请始终查阅最新的Docker安全文档与CVE数据库。