Security Contexts

Security Contexts

In this tutorial, we are going to discuss about security contexts in Kubernetes.

Security Contexts

When you run a docker container you have the option to define a set of security standards such as the ID of the user used to run the container, The Linux capabilities that can be added or removed from the container etc.

$ docker run --user=1005 nginx sleep 5000

$ docker run --cap-add SYS_ADMIN nginx

These security standards can be configured in Kubernetes as well. As you know already, in Kubernetes containers are encapsulated in PODs.

A security context defines privilege and access control settings for a Pod or Container.

You may choose to configure the security settings at a container level or at a POD level.

If you configure it at a POD level the settings will carry over to all the containers within the POD.

If you configure it at both the POD and the container the settings on the container will override the settings on the POD. let us start with a POD definition file.

apiVersion: v1
kind: Pod
metadata:
  name: web-pod
spec:
  containers:
     -name: nginx
      image: nginx
      command: ["sleep","5000"]

This POD runs an nginx image with the sleep command.

To configure security context on the container, add a field called security context under the specs section of the POD used to run as a user option to set the user id for the POD.

apiVersion: v1
kind: Pod
metadata:
  name: web-pod
spec:
  securityContext: 
    runAsUser: 1005
  containers:
     -name: nginx
      image: nginx
      command: ["sleep","5000"]

To set the same configuration on the container level move the whole section under the container specification like below

apiVersion: v1
kind: Pod
metadata:
  name: web-pod
spec:
  containers:
     -name: nginx
      image: nginx
      command: ["sleep","5000"]
      securityContext: 
        runAsUser: 1005

Now to add capabilities, use the capabilities option and specify a list of capabilities to add to the POD.

apiVersion: v1
kind: Pod
metadata:
  name: web-pod
spec:
  containers:
     -name: nginx
      image: nginx
      command: ["sleep","5000"]
      securityContext: 
        runAsUser: 1005
        capabilities: 
          add: ["SYS_ADMIN"]

Please note that, the capabilities are only supported at the container level and not at the POD level.

Security Contexts


Scroll to top