Kubernetes Security Context: set uid for a Pod

By default, any container that we launch will run as root. Most of the processes we launch don't really require, for example, to be able to install packages on the container. We can reduce it's privileges by setting the SecurityContext at the Pod level or at the container level.

Let's say we want to run a pod using the UID 1001 and the GID 1002. In the following YAML definition we are setting the securityContext at the pod leve, so all the containers will run as user's UID 1001 and GID 1002:

apiVersion: v1
kind: Pod
metadata:
  name: setUID
spec:
  securityContext:
    runAsUser: 1001
    runAsGroup: 1002
  containers:
  - image: busybox:latest
    name: setUID
    args:
      - sleep
      - "24h"

Once we deploy this pod:

$ kubectl apply -f pod-context.yml

It will keep running for 24h: We can run a command on it to get the UID and GID using kubectl exec to check it is working as expected:

$ kubectl exec setUID -- id
uid=1001 gid=1002

We could also set the securityContext at the container level, so each container within the Pod can ran using a different UID:

apiVersion: v1
kind: Pod
metadata:
  name: setUID
spec:
  containers:
  - image: busybox:latest
    securityContext:
      runAsUser: 1001
      runAsGroup: 1002
    name: setUID1001
    args:
      - sleep
      - "24h"
  - image: busybox:latest
    securityContext:
      runAsUser: 9999
      runAsGroup: 9999
    name: setUID9999
    args:
      - sleep
      - "24h"

Posted on 19/02/2021