容器安全加固指南:镜像与运行时防护 技术原理 容器安全是云原生架构的基石,涵盖镜像构建、分发、运行时的全生命周期。通过多层次的防护策略,可以有效降低容器化应用的安全风险。 镜像安全最佳实践 基础镜像选择 多阶段构建 最小权限用户 镜像扫描 运行时安全配置 只读根文件系统 资源限制 健康检查 网络安全策略 NetworkPolicy隔离 Service Mesh加密 秘密信息管理 避免硬编码 外部密钥管理 CI/CD安全集成 镜像构建扫描 策略即代码 运行时监控 Falco规则 审计日志 容器安全需要建立纵深防御体系,从镜像构建到运行时监控,每个环节都要实施相应的安全措施。通过自动化工具和策略即代码,可以建立可持续改进的安全防护体系。
容器安全是云原生架构的基石,涵盖镜像构建、分发、运行时的全生命周期。通过多层次的防护策略,可以有效降低容器化应用的安全风险。
# 避免使用过大的基础镜像 # FROM ubuntu:latest # 不推荐 # 推荐使用精简镜像 FROM alpine:3.19 # 更推荐使用官方维护的distroless镜像 FROM gcr.io/distroless/python3-debian12
# 构建阶段 FROM node:20-alpine AS builder WORKDIR /app COPY package*.json ./ RUN npm ci --production=false COPY . . RUN npm run build # 运行阶段:只包含必要文件 FROM alpine:3.19 WORKDIR /app COPY --from=builder /app/dist ./dist COPY --from=builder /app/node_modules ./node_modules # 不包含源代码和开发工具 USER nobody CMD ["node", "dist/index.js"]
FROM alpine:3.19 # 创建非root用户 RUN addgroup -g 1001 -S appuser && \ adduser -u 1001 -S appuser -G appuser WORKDIR /app COPY --chown=appuser:appuser . . USER appuser CMD ["./myapp"]
# 使用Trivy扫描本地镜像 trivy image myapp:latest # 扫描并生成JSON报告 trivy image --format json --output report.json myapp:latest # 只报告高危漏洞 trivy image --severity HIGH,CRITICAL myapp:latest # 在CI/CD中集成 trivy image --exit-code 1 --severity HIGH,CRITICAL myapp:latest
apiVersion: v1 kind: Pod metadata: name: secure-pod spec: containers: - name: app image: myapp:latest securityContext: readOnlyRootFilesystem: true volumeMounts: - name: tmp mountPath: /tmp - name: cache mountPath: /app/cache volumes: - name: tmp emptyDir: {} - name: cache emptyDir: {}
apiVersion: v1 kind: Pod metadata: name: limited-pod spec: containers: - name: app image: myapp:latest resources: requests: memory: "128Mi" cpu: "100m" limits: memory: "256Mi" cpu: "200m" securityContext: runAsNonRoot: true runAsUser: 1001 allowPrivilegeEscalation: false capabilities: drop: - ALL
apiVersion: v1 kind: Pod metadata: name: health-check-pod spec: containers: - name: app image: myapp:latest livenessProbe: httpGet: path: /health port: 8080 initialDelaySeconds: 30 periodSeconds: 10 failureThreshold: 3 readinessProbe: httpGet: path: /ready port: 8080 initialDelaySeconds: 5 periodSeconds: 5
apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: backend-policy spec: podSelector: matchLabels: app: backend policyTypes: - Ingress - Egress ingress: - from: - podSelector: matchLabels: app: frontend ports: - protocol: TCP port: 8080 egress: - to: - podSelector: matchLabels: app: database ports: - protocol: TCP port: 5432
apiVersion: security.istio.io/v1beta1 kind: PeerAuthentication metadata: name: default namespace: default spec: mtls: mode: STRICT
# 错误:直接在配置中存储敏感信息 # env: # - name: API_KEY # value: "hardcoded-key" # 正确:使用Secret apiVersion: v1 kind: Secret metadata: name: api-credentials type: Opaque stringData: api-key: "production-api-key" --- apiVersion: v1 kind: Pod metadata: name: secure-app spec: containers: - name: app image: myapp:latest env: - name: API_KEY valueFrom: secretKeyRef: name: api-credentials key: api-key
apiVersion: external-secrets.io/v1beta1 kind: ExternalSecret metadata: name: db-credentials spec: refreshInterval: 1h secretStoreRef: name: aws-secrets-manager kind: SecretStore target: name: db-credentials data: - secretKey: database-url remoteRef: key: prod/database/url
name: Build and Scan on: push: branches: [main] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Build image run: docker build -t myapp:${{ github.sha }} . - name: Scan for vulnerabilities uses: aquasecurity/trivy-action@master with: image-ref: myapp:${{ github.sha }} format: 'sarif' output: 'trivy-results.sarif' severity: 'HIGH,CRITICAL' exit-code: '1' - name: Upload results uses: github/codeql-action/upload-sarif@v2 with: sarif_file: 'trivy-results.sarif'
# OPA Gatekeeper约束 apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sRequiredLabels metadata: name: must-have-owner spec: match: kinds: - apiGroups: [""] kinds: ["Pod"] parameters: labels: ["owner"]
- rule: Detect shell in container desc: Detect shell spawned in container condition: > spawned_process and container and shell_procs and user.uid >= 1000 output: > Shell in container (user=%user.name container=%container.name) priority: WARNING
apiVersion: audit.k8s.io/v1 kind: Policy rules: - level: RequestResponse verbs: ["create", "update", "delete"] resources: - group: "" resources: ["pods", "deployments"]
容器安全需要建立纵深防御体系,从镜像构建到运行时监控,每个环节都要实施相应的安全措施。通过自动化工具和策略即代码,可以建立可持续改进的安全防护体系。