Security contexts are used to set privileges and access control of Pods and containers.
We can set these at Pod-level and / or at container-level. The security context set at container-level will take precedence over the security context set at Pod-level.
How do we set securityContext
at Pod-level?
In this example, all the containers within the Pod will run processes with the user ID of 1234.
apiVersion: v1
kind: Pod
metadata:
name: busybox-pod
spec:
securityContext:
runAsUser: 1234
containers:
- name: busybox-container-1
image: busybox
command: ["sh", "-c", "sleep 1h"]
- name: busybox-container-2
image: busybox
command: ["sh", "-c", "sleep 1h"]
aliilman$ kubectl exec -it busybox-pod -c busybox-container-1 sh
/ $ ps
PID USER TIME COMMAND
1 1234 0:00 sleep 1h
7 1234 0:00 sh
16 1234 0:00 ps
aliilman$ k exec -it busybox-pod -c busybox-container-2 sh
/ $ ps
PID USER TIME COMMAND
1 1234 0:00 sleep 1h
7 1234 0:00 sh
16 1234 0:00 ps
How do we set securityContext
at container-level?
In this example, the first container will run processes with the user ID of 789 while the second container will run processes with the user ID of 1234, just like the value set at Pod-level.
apiVersion: v1
kind: Pod
metadata:
name: busybox-pod
spec:
securityContext:
runAsUser: 1234
containers:
- name: busybox-container-1
image: busybox
command: ["sh", "-c", "sleep 1h"]
securityContext:
runAsUser: 789
- name: busybox-container-2
image: busybox
command: ["sh", "-c", "sleep 1h"]
aliilman$ kubectl exec -it busybox-pod -c busybox-container-1 sh
/ $ ps
PID USER TIME COMMAND
1 789 0:00 sleep 1h
7 789 0:00 sh
16 789 0:00 ps
aliilman$ k exec -it busybox-pod -c busybox-container-2 sh
/ $ ps
PID USER TIME COMMAND
1 1234 0:00 sleep 1h
7 1234 0:00 sh
16 1234 0:00 ps