容器安全指南
安全 Dockerfile
# 使用特定的最小基础镜像
FROM gcr.io/distroless/static-debian12:nonroot
# 不要用: FROM ubuntu:latest
# 多阶段构建减小最终镜像
FROM golang:1.22-alpine AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -ldflags="-w -s" -o server .
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=builder /app/server /server
# 以非 root 用户运行
USER nonroot:nonroot
EXPOSE 8080
ENTRYPOINT ["/server"]
Kubernetes 安全上下文
spec:
template:
spec:
# Pod 级别安全
securityContext:
runAsNonRoot: true
runAsUser: 1000
runAsGroup: 1000
fsGroup: 1000
seccompProfile:
type: RuntimeDefault
containers:
- name: app
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]
volumeMounts:
- name: tmp
mountPath: /tmp
volumes:
- name: tmp
emptyDir: {}
镜像安全扫描
# Trivy(扫描镜像 CVE)
trivy image myregistry/myapp:latest
# 发现 HIGH/CRITICAL 时退出失败
trivy image --exit-code 1 --severity HIGH,CRITICAL myapp:latest
# 扫描 Dockerfile 配置错误
trivy config ./Dockerfile
# Snyk
snyk container test myapp:latest