错误:容器设置了runAsNonRoot但镜像将以root运行。PodSecurityPolicy:不允许特权容器
Error: container has runAsNonRoot and image will run as root. PodSecurityPolicy: Privileged containers are not allowed
ID: policy/kubernetes-pod-security-policy-privileged-container
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| Kubernetes v1.25+ with Pod Security Admission | active | — | — | — |
| Kubernetes v1.21-1.24 with PodSecurityPolicy | active | — | — | — |
| kubectl v1.28 | active | — | — | — |
| Docker 24.0 | active | — | — | — |
根因分析
Kubernetes PodSecurityPolicy(或Pod安全准入)拒绝该Pod,因为容器的安全上下文与策略冲突,具体来说,镜像以root运行但策略要求非root,或者容器请求特权模式。
English
Kubernetes PodSecurityPolicy (or Pod Security Admission) rejects the pod because the container's security context conflicts with the policy, specifically the image runs as root but the policy requires non-root, or the container requests privileged mode.
官方文档
https://kubernetes.io/docs/concepts/security/pod-security-standards/解决方案
-
修改容器镜像以非root用户运行,在Dockerfile中添加USER指令并确保文件权限正确:FROM nginx:alpine; RUN addgroup -S appgroup && adduser -S appuser -G appgroup; USER appuser
-
如果镜像无法更改,将命名空间的Pod安全准入标签更新为更宽松的级别:kubectl label namespace my-namespace pod-security.kubernetes.io/enforce=baseline --overwrite(或'privileged'以获得完全访问)
-
对于使用PodSecurityPolicy(已弃用)的集群,创建允许特定容器安全上下文的自定义PSP:apiVersion: policy/v1beta1; kind: PodSecurityPolicy; metadata: {name: custom-psp}; spec: {privileged: true, runAsUser: {rule: RunAsAny}}
无效尝试
常见但无效的做法:
-
80% 失败
If the policy enforces runAsNonRoot, setting it to false will still be rejected; the policy must be changed or the image must be fixed.
-
50% 失败
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.
-
30% 失败
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.