Kubernetes SecurityContext

A SecurityContext is a Kubernetes object, defined as part of the Pod spec, that describes the privileges and access control settings for a Pod. The primary settings for a SecurityContext are

  • runAsUser – allows you to run containers as a specified user
  • runAsGroup – allows you to run containers as a specified group
  • fsGroup allows you to run containers with and a specific file system group

These settings can be applied at the Pod or container level. If applied at the Pod level the settings will apply to all containers in the Pod. If the SecurityContext is defined at both the Pod and container level, the container level SecurityContext will take precedence.

Below is a sample Pod definition with a SecurityContext defined.

apiVersion: v1
kind: Pod
  name: security-context-demo
    runAsUser: 1000
    runAsGroup: 3000
    fsGroup: 2000
    - name: sec-context-volume
      emptyDir: {}
    - name: sec-context-demo-container
      image: busybox
      command: [ "sh", "-c", "sleep 3600" ]
        - name: sec-context-volume
          mountPath: /data/demo

Create the above Pod by running kubectl apply -f securitycontext-demo.yml from the sample code.

Once the Pod is created you can exec into the running container with  kubectl exec -it security-context-demo -- sh. Run ps to list the processes and the users running those processes. You’ll see that the sh and sleep 3600 commands were run by user 1000, as specified by the runAsUser attribute.

cd data/demo and create a test file with echo test >> testfile. Run ls -l and you’ll see that user  1000 owns the file and it belongs to group 2000. This corresponds to the values set in runAsUser and fsGroup respectively.

Finally, running  id displays the users ID (1000), their primary Group ID (3000) and supplementary groups they belong to (2000).

The sample code for these notes is available here.