---

title: Kubernetes Pod Security Admission与安全上下文实践

keywords:

  • Pod Security Admission
  • 安全上下文
  • runAsNonRoot
  • seccomp
  • capabilities
  • allowPrivilegeEscalation

description: 使用Pod Security Admission与安全上下文在集群中实施最小权限与隔离,提供可验证的命名空间标签与Deployment示例。

date: 2025-11-26

categories:

  • 文章资讯
  • 技术教程

---

概述

  • 目标:以PSA与安全上下文约束Pod权限与宿主机交互,构建默认受限的安全基线。
  • 适用:生产集群多命名空间治理、敏感服务隔离、合规要求。

核心与实战

  • 命名空间启用PSA受限:
apiVersion: v1
kind: Namespace
metadata:
  name: prod
  labels:
    pod-security.kubernetes.io/enforce: restricted
    pod-security.kubernetes.io/enforce-version: v1.29
  • 安全上下文示例:
apiVersion: apps/v1
kind: Deployment
metadata:
  name: api
  namespace: prod
spec:
  replicas: 2
  selector:
    matchLabels: { app: api }
  template:
    metadata:
      labels: { app: api }
    spec:
      securityContext:
        seccompProfile:
          type: RuntimeDefault
      containers:
        - name: api
          image: repo/api:1.0
          securityContext:
            runAsNonRoot: true
            allowPrivilegeEscalation: false
            capabilities:
              drop: ["ALL"]
            readOnlyRootFilesystem: true
          ports:
            - containerPort: 8080

示例

  • 应用并验证:
kubectl apply -f ns-prod.yaml
kubectl apply -f deploy-api.yaml
kubectl -n prod describe pod -l app=api | findstr -i SecurityContext
  • 不合规示例被拒:
apiVersion: v1
kind: Pod
metadata:
  name: bad
  namespace: prod
spec:
  containers:
    - name: c
      image: alpine
      securityContext:
        privileged: true

验证与监控

  • 审计与事件:
  • 检查kubectl events -n prod中被拒事件;启用审计日志记录PSA决策。
  • 配置一致性:
  • 使用kubectl diff比较变更;在GitOps中设定受限策略为默认。
  • 运行时强化:
  • 结合Cilium/Kyverno补充细粒度策略与准入控制。

常见误区

  • 仅设置命名空间标签未在工作负载中设定安全上下文;需双管齐下。
  • 设置readOnlyRootFilesystem后未配置写入目录挂载导致运行失败;需将可写路径挂载到临时卷。
  • 误用privileged或过多capabilities;应默认drop ALL并按需最小添加。

结语

  • PSA与安全上下文形成强有力的最小权限基线,通过验证与审计可在生产持续提升安全治理水平。

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部