Skip to content
LF Cert Trainer

Lesson 86 · Section 7: Security

Lesson 86: Security contexts: users, capabilities and privileges for Pods

How a securityContext sets the user a container runs as, the Linux capabilities it keeps and whether it may gain more. Pod level against container level, which fields live where, how to prove the result, and the edit-and-recreate routine. · 18 min read · 3 min video

1/9Security contexts
0:00 / 3:04

Narrated by the local narrator voice. Keys: Space plays and pauses, J and L step, C captions, F full screen.

Why security contexts exist

The previous lesson showed what separates a container from its host: very little. Every container on a node runs on the same Linux kernel. Namespaces hide the other processes and files, but a process that runs as root, keeps a set of Linux capabilities and may gain more is one bug away from the node itself. Docker gave you flags such as --user, --cap-add and --privileged to control this.

A security context is the Kubernetes spelling of those flags. It is a block called securityContext in a Pod, in each container, or in both. The kubelet hands it to the container runtime, and the runtime starts the process with exactly that user, those groups and those capabilities. Without one, the container runs as whatever user its image says, which is very often root, with the runtime's default capabilities.

How it works

Two levels: the Pod and the container

Two places to write a security contextdefaultdefaultPod securityContextrunAsUser: 1000Container appno own settingRuns as 1000inheritedContainer sidecarrunAsUser: 2000Runs as 2000container winsPod onlyfsGroup, sysctlsContainer onlycapabilities, privileged
Two places to write a security context. The Pod's securityContext is the default for every container. A container's own securityContext wins for the fields it sets. Some fields exist only at one of the two levels.

Parts:

  • Pod securityContext (runAsUser: 1000)
  • Container app (no own setting)
  • Runs as 1000 (inherited)
  • Container sidecar (runAsUser: 2000)
  • Runs as 2000 (container wins)
  • Pod only (fsGroup, sysctls)
  • Container only (capabilities, privileged)

Connections:

  • Pod securityContext to Container app: default
  • Container app to Runs as 1000
  • Pod securityContext to Container sidecar: default
  • Container sidecar to Runs as 2000

You can write securityContext in two places, and they are two different types with overlapping fields:

apiVersion: v1
kind: Pod
metadata:
  name: demo
spec:
  securityContext:          # PodSecurityContext: the default for every container
    runAsUser: 1000
  containers:
    - name: app             # no securityContext: inherits runAsUser 1000
      image: busybox:1.37
      command: ["sleep", "3600"]
    - name: sidecar
      image: busybox:1.37
      command: ["sleep", "3600"]
      securityContext:      # SecurityContext: wins over the Pod for fields it sets
        runAsUser: 2000

The rule is simple: the container's value wins when both set the same field. A field set only on the Pod applies to every container, including init containers. A field set nowhere falls back to the image (for the user) or to the runtime's default (for everything else).

Some fields exist on only one level, and putting them on the wrong one is a validation error:

FieldPodContainerWhat it does
runAsUseryesyesThe UID of the container's first process. Overrides the image's USER
runAsGroupyesyesThe primary GID of the process. Without it, the GID is the image's, often 0
runAsNonRootyesyesThe kubelet refuses to start the container if it would run as UID 0
seccompProfileyesyesWhich system calls are allowed: RuntimeDefault, Localhost or Unconfined
seLinuxOptions, appArmorProfileyesyesLabels and profiles for the Linux security modules
fsGroupyesnoA group that owns mounted volumes, and is added to every process
supplementalGroupsyesnoMore GIDs added to every process
sysctlsyesnoNamespaced kernel parameters for the Pod, such as net.ipv4.ip_unprivileged_port_start
capabilitiesnoyesLinux capabilities to add and drop
privilegednoyesAlmost every capability and access to the host's devices
allowPrivilegeEscalationnoyesWhether a child process may gain more privileges than its parent
readOnlyRootFilesystemnoyesMounts the image's file system read only

Users and groups

runAsUser sets the UID, runAsGroup the primary GID, and the image's own USER instruction is only used when neither the container nor the Pod sets runAsUser. The UID does not need to exist in the image's /etc/passwd: Linux only cares about numbers. whoami may print "unknown uid 1000", and that is fine.

runAsNonRoot: true is a check, not a setting. Before the kubelet starts the container it works out the UID: the runAsUser value if there is one, otherwise the image's USER. If that UID is 0, or the image names a user that the kubelet cannot prove is not root (a name such as nginx instead of a number), the container is not started:

Warning  Failed  kubelet  Error: container has runAsNonRoot and image will run as root (pod: "web", container: web)

The Pod shows CreateContainerConfigError. The fix is to add runAsUser with a non-zero UID, or to use an image built to run as a non-root user.

fsGroup solves a different problem: volumes. A process running as UID 1000 often cannot write into a fresh volume owned by root. With fsGroup: 2000, the kubelet makes supported volumes (emptyDir, most persistent volumes, projected Secrets and ConfigMaps) group-owned by 2000, writable for the group, and adds 2000 to the groups of every process in the Pod. fsGroupChangePolicy: OnRootMismatch skips the slow recursive change when the top directory already has the right owner, which matters for large volumes.

Capabilities

Root's power in Linux is split into about forty capabilities. NET_ADMIN configures interfaces and routes, SYS_TIME sets the clock, NET_BIND_SERVICE binds ports below 1024, CHOWN changes file owners, and SYS_ADMIN is the catch-all that is almost as good as full root. A container runtime starts containers with a small default set (containerd's has 14, including CHOWN, NET_BIND_SERVICE, SETUID and NET_RAW), and you change it per container:

securityContext:
  capabilities:
    drop: ["ALL"]                  # start from nothing
    add: ["NET_BIND_SERVICE"]      # and add back exactly what the app needs

Write capability names without the CAP_ prefix the kernel uses. drop is applied first, so drop: ["ALL"] with an add list always means "only these". Capabilities apply to the container's processes as root; a non-root process does not get them in its effective set unless the image grants file capabilities, which is one more reason to combine a non-root user with drop: ["ALL"].

Privileged and privilege escalation

privileged: true turns nearly every protection off: all capabilities, access to the host's devices under /dev, no seccomp or AppArmor confinement. The process is root on the node in all but name. Only node-level tools such as some CNI and storage plugins need it.

allowPrivilegeEscalation: false sets the kernel's no_new_privs flag on the process, so a child can never gain more privileges than its parent: a setuid binary such as sudo or ping (on some images) cannot make it root. It is true by default, and Kubernetes treats it as always true when the container is privileged or has SYS_ADMIN, so the API rejects privileged: true together with allowPrivilegeEscalation: false.

Who enforces what

From a YAML field to a process on the nodeapplyscheduledcreatestartsyscallsPod manifestsecurityContextAPI serveradmission checkskubeletrunAsNonRoot checkContainer runtimecontainerd, runcProcessuid 1000, few capsLinux kernelsays yes or no
From a YAML field to a process on the node. Kubernetes enforces nothing by itself. The kubelet passes the security context to the container runtime, and the Linux kernel enforces the user and the capabilities on the process.

Parts:

  • Pod manifest (securityContext)
  • API server (admission checks)
  • kubelet (runAsNonRoot check)
  • Container runtime (containerd, runc)
  • Process (uid 1000, few caps)
  • Linux kernel (says yes or no)

Connections:

  • Pod manifest to API server: apply
  • API server to kubelet: scheduled
  • kubelet to Container runtime: create
  • Container runtime to Process: start
  • Process to Linux kernel: syscalls
  • The API server validates the fields and runs admission. With Pod Security Admission, a namespace labelled pod-security.kubernetes.io/enforce: restricted rejects Pods whose security context is not tight enough, with an error that names every missing field.
  • The kubelet resolves the user and performs the runAsNonRoot check, and applies fsGroup to volumes.
  • The container runtime creates the process with the UID, the GIDs, the capability sets, the seccomp profile and the read-only mount.
  • The kernel enforces all of it, on every system call, for the life of the process.
Under the hood · Hardening beyond the basics
Four switches that shrink what a container can doDefault containerroot, 14 capabilitiesrunAsNonRootplus runAsUserdrop: [ALL]add back only needsNo escalationallowPrivilegeEscalationRead-only rootreadOnlyRootFilesystemHardened containerlittle left to abuse
Four switches that shrink what a container can do. Each switch removes one kind of power. Together they are most of the restricted Pod Security Standard, and they cost an ordinary web application nothing.

Parts:

  • Default container (root, 14 capabilities)
  • runAsNonRoot (plus runAsUser)
  • drop: [ALL] (add back only needs)
  • No escalation (allowPrivilegeEscalation)
  • Read-only root (readOnlyRootFilesystem)
  • Hardened container (little left to abuse)

Connections:

  • Default container to runAsNonRoot
  • runAsNonRoot to drop: [ALL]
  • drop: [ALL] to No escalation
  • No escalation to Read-only root
  • Read-only root to Hardened container
  • The restricted Pod Security Standard asks for runAsNonRoot: true, allowPrivilegeEscalation: false, capabilities.drop: ["ALL"] (only NET_BIND_SERVICE may be added back) and seccompProfile.type: RuntimeDefault or Localhost. Writing those four into every Pod template makes it pass. Pod Security Admission and the standards are a CKS topic; for the CKA, recognise the error message and add the fields it lists.
  • seccompProfile: RuntimeDefault blocks about fifty rarely used system calls, such as loading kernel modules. It is not the default for a Pod unless the kubelet is configured with --seccomp-default.
  • readOnlyRootFilesystem: true stops an attacker from dropping tools into the image. Most applications need one writable place, so mount an emptyDir at /tmp or wherever the app writes.
  • User namespaces (spec.hostUsers: false) map root inside the container to an unprivileged UID on the node, so even a container that runs as root is nobody on the host. It needs support from the node's kernel and runtime.
  • Host namespaces are not part of the security context but sit next to it: hostNetwork, hostPID and hostIPC on the Pod spec share the node's network, process list or IPC with the container. Treat them like privileged.
  • Windows containers use windowsOptions.runAsUserName instead of UIDs; the Linux fields are ignored there.

Using it

Example · Run an existing Pod as a different user

Task: "The Pod ubuntu-sleeper in namespace default runs as root. Make it run with user ID 1010."

First check what you have:

kubectl exec ubuntu-sleeper -- whoami
root

The security context of a running Pod cannot be changed in place. kubectl edit would save your change to a temporary file and refuse it with spec: Forbidden: pod updates may not change fields other than .... So export, edit and replace:

kubectl get pod ubuntu-sleeper -o yaml > sleeper.yaml
vi sleeper.yaml
spec:
  securityContext:
    runAsUser: 1010
  containers:
    - name: ubuntu
      image: ubuntu
      command: ["sleep", "4800"]
kubectl replace --force -f sleeper.yaml       # deletes the old Pod and creates the new one
kubectl exec ubuntu-sleeper -- id
pod "ubuntu-sleeper" deleted
pod/ubuntu-sleeper replaced
uid=1010 gid=0(root) groups=0(root)

The GID is still 0 because only the user was asked for. Add runAsGroup when a task wants the group changed too. In a Deployment the same edit goes into spec.template.spec, and kubectl edit deployment works because the change only rolls out new Pods.

Example · Add capabilities to one container

Task: "Update the Pod ubuntu-sleeper to run as root with the SYS_TIME capability, and also NET_ADMIN."

spec:
  containers:
    - name: ubuntu
      image: ubuntu
      command: ["sleep", "4800"]
      securityContext:
        capabilities:
          add: ["SYS_TIME", "NET_ADMIN"]

Remove any runAsUser you added earlier (root is wanted here), replace the Pod, then prove that the capability works:

kubectl replace --force -f sleeper.yaml
kubectl exec ubuntu-sleeper -- date -s '19 APR 2026 11:14:00'
Sun Apr 19 11:14:00 UTC 2026

Without SYS_TIME the same command prints date: cannot set date: Operation not permitted, even as root. That is the kernel enforcing the capability set, not Kubernetes.

Example · Write a hardened Pod from scratch

Task: "Create a Pod secure with image busybox:1.37 that runs sleep 3600 as user 1000 and group 3000, cannot gain privileges, has no capabilities, and has a writable /data directory."

kubectl run has no flags for a security context, so let it write the rest:

kubectl run secure --image=busybox:1.37 --dry-run=client -o yaml -- sleep 3600 > secure.yaml

Then add the security context and the volume:

apiVersion: v1
kind: Pod
metadata:
  name: secure
spec:
  securityContext:
    runAsUser: 1000
    runAsGroup: 3000
    runAsNonRoot: true
    fsGroup: 2000
  volumes:
    - name: data
      emptyDir: {}
  containers:
    - name: secure
      image: busybox:1.37
      args: ["sleep", "3600"]
      volumeMounts:
        - name: data
          mountPath: /data
      securityContext:
        allowPrivilegeEscalation: false
        readOnlyRootFilesystem: true
        capabilities:
          drop: ["ALL"]
kubectl apply -f secure.yaml
kubectl exec secure -- sh -c 'id; touch /data/ok && ls -ln /data; touch /oops'
uid=1000 gid=3000 groups=2000,3000
total 0
-rw-r--r--    1 1000     2000             0 Nov 30 10:12 ok
touch: /oops: Read-only file system
command terminated with exit code 1

The file in /data belongs to group 2000 because of fsGroup, and the write to / fails because of readOnlyRootFilesystem. Both lines prove a field worked.

Example · Fix a Pod that will not start

A Deployment's Pods sit in CreateContainerConfigError:

kubectl describe pod web-7c9f5d8b6-x2kqp | tail -3
  Warning  Failed     4s (x3 over 20s)  kubelet  Error: container has runAsNonRoot and image will run as root (pod: "web-7c9f5d8b6-x2kqp_default(…)", container: web)

The template says runAsNonRoot: true, but the image (plain nginx) runs as root. Either give the container a non-root UID with runAsUser and an image that can run that way, or switch to an image built for it, such as nginxinc/nginx-unprivileged, which listens on 8080. Removing runAsNonRoot also "fixes" it, but undoes what the author wanted, so do that only when the task says so.

Tricks

Common mistakes

  • Putting capabilities or privileged on the Pod. They only exist under a container.
  • Writing CAP_SYS_TIME. Kubernetes wants SYS_TIME. The runtime may reject or ignore the prefixed name.
  • Trying to edit a running Pod's security context. The change is forbidden. Recreate the Pod.
  • Setting runAsNonRoot without a user. With an image that runs as root, the Pod never starts.
  • Forgetting the group. runAsUser alone leaves the primary GID at the image's value, often 0.
  • Setting the field on the wrong container. In a Pod with a sidecar, check the container name in the task.
  • Trusting the YAML. A typo in a field name inside a file applied with an old client, or the wrong container, goes unnoticed until you run id inside.
  • Expecting readOnlyRootFilesystem to keep working apps working. Give the app an emptyDir for the paths it writes.

Recap

  • A securityContext tells the container runtime the user, the groups, the capabilities and the privilege rules of a container. The kernel enforces them.
  • The Pod level is the default for all containers; the container level wins for fields it sets.
  • fsGroup, supplementalGroups and sysctls are Pod-only. capabilities, privileged, allowPrivilegeEscalation and readOnlyRootFilesystem are container-only.
  • runAsNonRoot is a check by the kubelet; a root image then fails with CreateContainerConfigError.
  • Capabilities are written without CAP_, and drop: ["ALL"] plus a short add list means "only these".
  • A running Pod's security context cannot change: export, edit, kubectl replace --force.
  • Prove the result with id, /proc/1/status and one action that must be refused.

Official docs

Quiz: check what you learned

5 questions on this lesson · about 3 min · instant feedback. Missed questions come back in your review queue.

Sign in to take the quiz and keep your score.

Practise: try it on a real cluster

A hands-on lab for this lesson. You get goals, not steps: any solution that reaches them passes.

  • Make a running app give up root, its capabilities and its writable root filesystem, and keep it working while you do.

    Fix · Level 2 · standard · target 20 min

Discussion

Learners ask and answer questions here. Sign in to read and join the discussion.