Kubernetes securityContext, Capabilities, and Pod Security Standards
The five fields that remove most container escapes, which of them only exist at container level, and how the restricted profile enforces the same settings at admission.

Quick Summary
securityContext is where a container's privileges are narrowed. It exists at two levels — pod and container — and container fields override pod fields for the container they belong to. The five settings that remove most container escapes: runAsNonRoot: true, allowPrivilegeEscalation: false, readOnlyRootFilesystem: true, capabilities.drop: ["ALL"], and seccompProfile.type: RuntimeDefault.
Capabilities are the meaningful half of root. A Linux container starts with a default set (CAP_NET_RAW, CAP_CHOWN, CAP_SETUID, …) that is far more than a web server needs; dropping ALL and adding back only what is used narrows the blast radius without changing the image. privileged: true is the opposite: it grants all capabilities and device access, and is almost never required outside a CNI or storage driver.
Pod Security Standards turn these settings into an admission policy at the namespace level. restricted is the hardened profile and refuses pods that omit seccompProfile, allow privilege escalation, run as root, or keep capabilities beyond a small allow-list. Labelling a namespace is the enforceable, cluster-wide version of writing the same fields by hand.
Basic Syntax & Core Signatures
apiVersion: v1
kind: Pod
metadata:
name: api
spec:
securityContext: # pod level: applies to all containers
runAsNonRoot: true
runAsUser: 10001
runAsGroup: 10001
fsGroup: 10001 # volume ownership for mounted files
fsGroupChangePolicy: OnRootMismatch
seccompProfile:
type: RuntimeDefault # RuntimeDefault | Localhost | Unconfined
containers:
- name: api
image: registry.example.com/shop/api:4.2.0
securityContext: # container level: overrides pod level
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
privileged: false
capabilities:
drop: ["ALL"]
add: ["NET_BIND_SERVICE"] # only if binding to port < 1024
procMount: Default
volumeMounts:
- { name: tmp, mountPath: /tmp }
- { name: cache, mountPath: /app/.cache }
volumes:
- name: tmp
emptyDir: {}
- name: cache
emptyDir: {}# Namespace labels: the policy as admission control
apiVersion: v1
kind: Namespace
metadata:
name: shop
labels:
pod-security.kubernetes.io/enforce: restricted
pod-security.kubernetes.io/enforce-version: latest
pod-security.kubernetes.io/audit: restricted
pod-security.kubernetes.io/warn: restrictedkubectl -n shop get deploy api -o jsonpath=\
'{.spec.template.spec.containers[0].securityContext}{"\n"}'
kubectl -n shop auth can-i --list
kubectl label --dry-run=server --overwrite ns shop \
pod-security.kubernetes.io/enforce=restricted # warns about existing pods
kubectl run t --rm -it --image=busybox:1.36 --restart=Never -- sh -c 'id; capsh --print 2>/dev/null || grep Cap /proc/self/status'Key Comparison Table
| Setting | Level | Default | Effect |
|---|---|---|---|
runAsNonRoot | pod / container | false | Refuses to start if the image user is UID 0 |
runAsUser | pod / container | image USER | Sets the UID |
allowPrivilegeEscalation | container | true (false when runAsNonRoot… not implied) | Blocks setuid escalation |
readOnlyRootFilesystem | container | false | Root filesystem mounted read-only |
capabilities.drop | container | inherited default set | Removing ALL is the strong form |
seccompProfile.type | pod / container | Unconfined before PSA | RuntimeDefault is the runtime's filter |
privileged | container | false | All capabilities, all devices |
fsGroup | pod | none | Group ownership of volume files |
| Profile | Rejects | Allows |
|---|---|---|
privileged | Nothing essentially | Host access, privileged containers |
baseline | privileged, host namespaces, hostPath, NET_RAW additions | Default capabilities, root |
restricted | Privilege escalation, running as root, missing seccomp, added caps beyond NET_BIND_SERVICE | A hardened pod that declares everything |
| Symptom | Meaning |
|---|---|
container has runAsNonRoot and image will run as root | Image has no numeric USER; set runAsUser |
Permission denied writing to /app after readOnlyRootFilesystem | Mount an emptyDir where the app writes |
Operation not permitted binding port 80 | Add NET_BIND_SERVICE or listen above 1024 |
Pod rejected with violates PodSecurity "restricted" | A field above does not satisfy the profile |
Practical Edge Cases & Deep Dives
1. allowPrivilegeEscalation: false and the setuid gap
A container running as UID 1000 can still execute a setuid-root binary inside the image and become root, because the kernel honours the file's setuid bit. allowPrivilegeEscalation: false sets no_new_privs on the process, which makes setuid and file capabilities ineffective for that process tree. It is the cheapest single hardening step and it has no effect on writability or networking.
$ kubectl exec api-xxx -- sh -c 'ls -l /bin/passwd; grep NoNewPrivs /proc/self/status'
-rwsr-xr-x 1 root root ... /bin/passwd
NoNewPrivs: 12. readOnlyRootFilesystem needs writable mounts, not a writable root
Most application images write to a handful of paths: /tmp, a cache directory, a log directory, or a PID file. With a read-only root those writes fail with EROFS and the container restarts, which looks like an application bug. Enumerate the paths first:
kubectl exec -it api-xxx -- sh -c 'touch /x /tmp/y /app/z 2>&1; ls -la /app | head'
# touch: /x: Read-only file systemThen mount an emptyDir for each writable path. Java's java.io.tmpdir, Python's __pycache__ writes, nginx's /var/cache/nginx and /var/run, and Node's .cache are the usual suspects. fsGroup matters at the same time: a mounted emptyDir is owned by root unless fsGroup is set, so a non-root container still cannot write.
3. Capabilities: what to drop and what to add back
capabilities:
drop: ["ALL"]
add:
- NET_BIND_SERVICE # bind ports < 1024
- CHOWN # chown files owned by another user
- SETUID / SETGID # su-exec, gosu entrypointsNET_RAW is the capability behind raw sockets and is a common requirement for ping and for some service meshes; it is also the one restricted disallows adding. Most web services need nothing at all. A container that must change its own UID at start-up (an entrypoint that drops privileges via gosu) needs SETUID, SETGID, and often CHOWN — the reason that pattern is worse than a fixed runAsUser in the manifest.
4. seccompProfile: RuntimeDefault and the syscalls it blocks
The container runtime ships a default seccomp profile that blocks roughly 40 dangerous syscalls (kexec_load, add_key, mount for unprivileged users, and others). It is permissive enough for nearly every application, and restricted requires it. A Localhost profile is a per-node JSON file allowing a custom set — useful for a workload that needs one blocked syscall, at the cost of shipping the profile to every node.
securityContext:
seccompProfile:
type: Localhost
localhostProfile: profiles/allow-keyctl.json # relative to the kubelet's seccomp root5. Pod level versus container level, and the fields that only exist at one
runAsUser, runAsGroup, runAsNonRoot, fsGroup, seccompProfile, and supplementalGroups exist at both levels. allowPrivilegeEscalation, capabilities, readOnlyRootFilesystem, privileged, and procMount exist only at the container level — putting them under pod.spec.securityContext is silently ignored by the API server in most versions, which is a common cause of "I set it and nothing changed". Always verify the effective value on the pod:
kubectl -n shop get pod api-xxx -o jsonpath=\
'{.spec.containers[0].securityContext}{"\n"}'runAsNonRoot: true without runAsUser relies on the image's numeric USER; if the image says USER app (a name), the kubelet cannot verify non-root-ness and refuses to start the container.
Common Runtime & Configuration Mistakes
| Symptom | Cause | Fix |
|---|---|---|
image will run as root | runAsNonRoot with no numeric USER | Set runAsUser numerically |
| Container crashloops writing files | Read-only root, no writable mounts | emptyDir for each writable path |
Permission denied on mounted volume | fsGroup missing for a non-root UID | Set fsGroup |
| Cannot bind port 80 | NET_BIND_SERVICE dropped | Add the capability, or use 8080 |
| Setting under the pod has no effect | Container-only field in pod context | Move it to the container's securityContext |
Pod rejected under restricted | Missing seccompProfile or runAsNonRoot | Declare all five fields |
| App fails on a blocked syscall | RuntimeDefault seccomp | Localhost profile with the syscall |
| Node driver stopped working | privileged removed | Keep privileged pods out of PS-namespaces |
exec into pod denied | RBAC, not security context | Grant pods/exec verbs |
| Sudden failures after a namespace relabel | Audit-only to enforce | Check warn output first |
Security context is declarative hardening, and it only has an effect where it is actually set: on the container that runs the workload, and in a namespace whose Pod Security level enforces it. Write the five fields explicitly in every manifest, verify them on the running pod, and let the namespace label catch what a later contributor forgets.
Try matching browser tools
All toolsSmall utilities that fit Kubernetes work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Kubernetes guides
All Kubernetes guideskubectl Output: jsonpath, custom-columns, and the Debugging Commands Worth Knowing
jsonpath for one value in a script, custom-columns for tables people read, and kubectl debug when the container has no shell. Includes the three quoting layers that break jsonpath.
Kubernetes Namespaces, ResourceQuotas, and LimitRanges
A namespace is only a boundary when quota and limit range make it one. Aggregate caps, per-pod defaults, the admission errors they produce, and namespaces stuck Terminating.
Kubernetes StatefulSets: Ordinal Identities, Headless Services, and PVC Lifecycle
Why each StatefulSet pod keeps a name, a DNS record, and its own PVC; how OrderedReady gates startup on readiness; and how partition-based updates canary a single quorum member.
Kubernetes PodDisruptionBudgets and Graceful Node Drains
A PDB paces voluntary disruption only. The percentage rounding that silently blocks every drain, the eviction API versus kubectl delete, and unhealthy pods that lock a node.
More in Kubernetes
All Kubernetes guidesThe guides filed next to this one in Kubernetes, in library order.