# 错误：容器设置了runAsNonRoot但镜像将以root运行。PodSecurityPolicy：不允许特权容器

- **ID:** `policy/kubernetes-pod-security-policy-privileged-container`
- **领域:** policy
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 85%

## 根因

Kubernetes PodSecurityPolicy（或Pod安全准入）拒绝该Pod，因为容器的安全上下文与策略冲突，具体来说，镜像以root运行但策略要求非root，或者容器请求特权模式。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| Kubernetes v1.25+ with Pod Security Admission | active | — | — |
| Kubernetes v1.21-1.24 with PodSecurityPolicy | active | — | — |
| kubectl v1.28 | active | — | — |
| Docker 24.0 | active | — | — |

## 解决方案

1. ```
   修改容器镜像以非root用户运行，在Dockerfile中添加USER指令并确保文件权限正确：FROM nginx:alpine; RUN addgroup -S appgroup && adduser -S appuser -G appgroup; USER appuser
   ```
2. ```
   如果镜像无法更改，将命名空间的Pod安全准入标签更新为更宽松的级别：kubectl label namespace my-namespace pod-security.kubernetes.io/enforce=baseline --overwrite（或'privileged'以获得完全访问）
   ```
3. ```
   对于使用PodSecurityPolicy（已弃用）的集群，创建允许特定容器安全上下文的自定义PSP：apiVersion: policy/v1beta1; kind: PodSecurityPolicy; metadata: {name: custom-psp}; spec: {privileged: true, runAsUser: {rule: RunAsAny}}
   ```

## 无效尝试

- **** — If the policy enforces runAsNonRoot, setting it to false will still be rejected; the policy must be changed or the image must be fixed. (80% 失败率)
- **** — If the base image runs a process as root by default (e.g., nginx:latest), simply adding a USER directive may not work if the process requires root permissions. (50% 失败率)
- **** — This weakens cluster security and may violate compliance; also, on newer clusters using Pod Security Admission, the policy is enforced at the namespace level via labels. (30% 失败率)
