本文主要是介绍kubernetesr进阶--Security Context之为Pod设置Security Context,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在 Pod 的定义中增加 securityContext
字段,即可为 Pod 指定 Security 相关的设定。 securityContext
字段是一个 PodSecurityContext对象。通过该字段指定的内容将对该 Pod 中所有的容器生效。
Pod示例
以下面的 Pod 为例
apiVersion: v1
kind: Pod
metadata:name: security-context-demo
spec:securityContext:runAsUser: 1000runAsGroup: 3000fsGroup: 2000volumes:- name: sec-ctx-volemptyDir: {}containers:- name: sec-ctx-demoimage: busyboxcommand: [ "sh", "-c", "sleep 1h" ]volumeMounts:- name: sec-ctx-volmountPath: /data/demosecurityContext:allowPrivilegeEscalation: false
在上面的例子中:
-
spec.securityContext.runAsUser
字段指定了该 Pod 中所有容器的进程都以UserID1000
的身份运行,spec.securityContext.runAsGroup
字段指定了该 Pod 中所有容器的进程都以 -
- 如果该字段被省略,容器进程的GroupID为 root(0)
- 容器中创建的文件,其所有者为 userID 1000,groupID 3000
-
spec.securityContext.fsGroup
字段指定了该 Pod 的 fsGroup 为 2000- 数据卷 (本例中,对应挂载点
/data/demo
的数据卷为sec-ctx-demo
) 的所有者以及在该数据卷下创建的任何文件,其 GroupID 为 2000
- 数据卷 (本例中,对应挂载点
执行Pod示例
-
创建 Pod
查看
security-context-1.yaml
apiVersion: v1
kind: Pod
metadata:name: security-context-demo
spec:securityContext:runAsUser: 1000runAsGroup: 3000fsGroup: 2000volumes:- name: sec-ctx-volemptyDir: {}containers:- name: sec-ctx-demoimage: busyboxcommand: [ "sh", "-c", "sleep 1h" ]volumeMounts:- name: sec-ctx-volmountPath: /data/demosecurityContext:allowPrivilegeEscalation: false
执行yaml
kubectl apply -f security-context-1.yaml
执行结果
pod/security-context-demo created
-
验证 Pod 已运行
kubectl get pod security-context-demo
执行结果
NAME READY STATUS RESTARTS AGE security-context-demo 2/2 Running 0 69s
-
进入容器的命令行界面
kubectl exec -it security-context-demo -- sh
-
在该命令行界面中,查看正在运行的进程
ps
在该命令行界面中,查看正在运行的进程
PID USER TIME COMMAND1 1000 0:00 sh -c sleep 1h7 1000 0:00 sh13 1000 0:00 ps
-
在命令行界面中,切换到目录
/data
,并查看目录中的文件列表cd /data ls -l
请注意,
/data/demo
目录的 groupID 为 2000(由 fsGroup 指定),输出结果如下所示:drwxrwsrwx 2 root 2000 4096 Oct 4 05:08 demo
在命令行界面中,切换到目录
/data/demo
,并创建一个文件cd /data/demo echo hello > test ls -l
请注意,
test
的 groupID 为 2000 (由 FSGroup 指定),输出结果如下所示:-rw-r--r-- 1 1000 2000 6 Oct 29 16:14 test
-
在命令行界面中执行
id
命令,输出结果如下所示:id uid=1000(1000) gid=3000 groups=2000
- 请注意:
- gid 为 3000,与
runAsGroup
字段所指定的一致 - 如果
runAsGroup
字段被省略,则 gid 取值为 0(即 root),此时容器中的进程将可以操作 root Group 的文件
- gid 为 3000,与
- 请注意:
-
执行
exit
退出命令行界面
这篇关于kubernetesr进阶--Security Context之为Pod设置Security Context的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!