kubernetes securitycontext runAsNonRoot不起作用

问题描述

我正在使用securityContext进行测试,但是将runAsNonRoot设置为true时无法启动pod。 我使用vagrant以abdelghani用户的身份向主机部署一个master和两个minions和ssh:

id $USER
uid=1001(abdelghani) gid=1001(abdelghani) groups=1001(abdelghani),27(sudo)

集群信息:

Kubernetes版本:4.4.0-185-通用 正在使用的云:(如果不在公共云上,则将裸机放入) 安装方式:手动 主机操作系统:ubuntu16.04.6 CNI和版本: CRI和版本:

apiVersion: v1
kind: Pod
Metadata:
  name: buggypod
spec:
  containers:
  - name: container
    image: Nginx
    securityContext:        
      runAsNonRoot: true

我愿意: kubectl套用-f pod.yml 它说创建了pod mybugypod,但是当我检查时: kubectl得到豆荚 窗格的状态为CreateContainerConfigError

我在做什么错了?

解决方法

默认情况下,Nginx服务将期望对其配置路径(/ etc / nginx)具有读和写权限,因此非root用户将拥有对该路径的访问权限,这就是失败的原因。 您只设置了runAsNonRoot,但不能期望或保证容器将以用户1001的身份启动服务。请尝试将runAsUser显式设置为1001,如下所示,这应该可以解决您的问题。

apiVersion: v1
kind: Pod
metadata:
  name: buggypod
spec:
  containers:
    - name: container
      image: nginx
      securityContext:        
        runAsUser: 1001 
,

我尝试根据您的要求运行Pod。失败的原因是Nginx要求修改root拥有的/ etc /中的某些配置,当您运行AsNonRoot时,它失败了,因为它无法编辑Nginx的默认配置。

这是您在运行它时实际上遇到的错误。

10-listen-on-ipv6-by-default.sh: error: can not modify /etc/nginx/conf.d/default.conf (read-only file system?)
/docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
/docker-entrypoint.sh: Configuration complete; ready for start up
2020/08/13 17:28:55 [warn] 1#1: the "user" directive makes sense only if the master process runs with super-user privileges,ignored in /etc/nginx/nginx.conf:2
nginx: [warn] the "user" directive makes sense only if the master process runs with super-user privileges,ignored in /etc/nginx/nginx.conf:2
2020/08/13 17:28:55 [emerg] 1#1: mkdir() "/var/cache/nginx/client_temp" failed (13: Permission denied)
nginx: [emerg] mkdir() "/var/cache/nginx/client_temp" failed (13: Permission denied)

我运行的规范。

apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: null
  labels:
    run: buggypod
  name: buggypod
spec:
  securityContext:
    runAsNonRoot: true
    runAsUser: 1000
  containers:
  - image: nginx
    name: buggypod
    resources: {}
  dnsPolicy: ClusterFirst
  restartPolicy: Always
status: {}

我的建议是您使用一个Dockerfile创建一个自定义的Nginx映像,该文件还会创建用户并为新的/var/cache/nginx、/etc/nginx/conf.d、/var/log/nginx文件夹提供权限创建的用户。这样您就可以将容器作为非根目录运行。