Kubernetes安全加固指南:从入门到精通

作为一名在生产环境中摸爬滚打多年的运维工程师,我深刻体会到K8s安全的重要性。今天想和大家分享一些实用的K8s安全加固经验。

一、RBAC权限控制

RBAC是K8s安全的基石,合理的权限控制能最大限度减少安全风险:

apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: production
  name: app-reader
rules:
- apiGroups: [""]
  resources: ["pods", "services"]
  verbs: ["get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: app-reader-binding
  namespace: production
subjects:
- kind: ServiceAccount
  name: app-sa
  namespace: production
roleRef:
  kind: Role
  name: app-reader
  apiGroup: rbac.authorization.k8s.io

最佳实践

  • 遵循最小权限原则,只授予必要的权限
  • 避免使用ClusterAdmin,优先使用Role/RoleBinding
  • 定期审计ServiceAccount的使用情况

二、Pod安全策略

使用PodSecurityPolicy或Pod Security Standards限制Pod的安全行为:

apiVersion: v1
kind: Pod
spec:
  securityContext:
    runAsNonRoot: true
    runAsUser: 10000
    fsGroup: 20000
  containers:
  - name: app
    image: myapp:latest
    securityContext:
      allowPrivilegeEscalation: false
      readOnlyRootFilesystem: true
      capabilities:
        drop:
        - ALL

三、网络策略隔离

通过NetworkPolicy实现Pod之间的网络隔离:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: api-isolation
  namespace: production
spec:
  podSelector:
    matchLabels:
      app: api
  policyTypes:
  - Ingress
  - Egress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          app: frontend
    ports:
    - protocol: TCP
      port: 8080

四、Secret管理

敏感信息一定要加密存储:

apiVersion: v1
kind: Secret
metadata:
  name: db-credentials
  namespace: production
type: Opaque
data:
  username: <base64-encoded>
  password: <base64-encoded>

推荐使用External Secrets Operator或HashiCorp Vault进行秘钥管理。

五、容器镜像安全

构建安全镜像的最佳实践:

FROM python:3.11-slim AS builder
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

FROM gcr.io/distroless/python3
COPY --from=builder /usr/local/lib/python3.11/site-packages /site-packages
COPY --from=builder /app /app
USER nonroot:nonroot
CMD ["/app/main.py"]

关键点:

  • 使用最小化基础镜像
  • 不在镜像中存储敏感信息
  • 定期扫描镜像漏洞
  • 使用多阶段构建减小镜像体积

结语

安全不是一次性工作,而是持续的过程。就像徒步前要检查装备一样,K8s安全也需要定期审查和更新。唯有保持警惕,才能让我们的集群固若金汤。

本文作者:侯万里(万里侯),守护集群安全的运维老兵

更多推荐