Security Contexts

For some background, containers share the host kernel but they run in their namespace managed by docker. Containers can have same user as host and they have root users also. If containers have root users, is not it dangerous for host? It is not, as only few capabilities are given to root users of containers.

Capabilities

These are the privileges or access level provided to root user. For example, KILL, CHOWN, MAC_ADMIN etc. We can find all these capabilities at location /usr/include/linux/capability.h

Security Context is used to define the user for pods and containers and capabilities for containers.

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

securityContext is set at pod level. It will apply to all the containers inside the pod, unless we defined securityContext for containers explicitly. For example,

apiVersion: v1
kind: Pod
metadata:
    name: nginx
spec:
    securityContext:
        runAsUser: 1001
    containers:
        - name: nginx
          image: nginx
          securityContext:
              runAsUser: 1002

Capabilities can only be provided to container.

apiVersion: v1
kind: Pod
metadata:
    name: nginx
spec:
    containers:
        - name: nginx
          image: nginx
          securityContext:
              capabilities:
                  add: 
                      - SYS_TIME
                      - NET_ADMIN