Security Contexts & Pod Security
Containers share the node's kernel. A container running as root with extra Linux capabilities is only a kernel bug away from owning the node. Security contexts let you drop privileges, and Pod Security Admission lets a cluster enforce minimum standards.
securityContext
It can be set for the whole Pod (spec.securityContext) and per container (containers[].securityContext, which wins when both set the same field).
apiVersion: v1
kind: Pod
metadata:
name: api
spec:
securityContext:
runAsNonRoot: true
runAsUser: 10001
runAsGroup: 10001
fsGroup: 10001 # group ownership for mounted volumes
seccompProfile:
type: RuntimeDefault
containers:
- name: api
image: ghcr.io/acme/api:2.3.1
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]
volumeMounts:
- {name: tmp, mountPath: /tmp} # writable scratch, since / is read-only
volumes:
- name: tmp
emptyDir: {}| Field | Effect |
|---|---|
runAsNonRoot: true |
Kubelet refuses to start the container if it would run as UID 0 |
runAsUser / runAsGroup |
UID/GID of the process |
readOnlyRootFilesystem |
The image filesystem is read-only; write only to volumes |
allowPrivilegeEscalation: false |
Blocks setuid binaries and no_new_privs escalation |
capabilities.drop: [ALL] |
Removes Linux capabilities (add back only e.g. NET_BIND_SERVICE) |
privileged: true |
Full access to the host's devices. Avoid except for node agents |
seccompProfile: RuntimeDefault |
Filters dangerous syscalls |
Merging Pod and container settings
Container-level fields override Pod-level ones. A model of the effective context:
pod_ctx = {"runAsUser": 10001, "runAsNonRoot": True, "seccompProfile": "RuntimeDefault"}
containers = {
"api": {"readOnlyRootFilesystem": True, "allowPrivilegeEscalation": False},
"legacy": {"runAsUser": 0},
"migrate": {"runAsUser": 20001},
}
def effective(pod_ctx, c_ctx):
merged = {**pod_ctx, **c_ctx}
problems = []
if merged.get("runAsNonRoot") and merged.get("runAsUser") == 0:
problems.append("CreateContainerConfigError: runAsNonRoot and runAsUser is 0")
return merged, problems
for name, ctx in containers.items():
merged, problems = effective(pod_ctx, ctx)
print(f"{name:8} runAsUser={merged['runAsUser']:<6} readOnlyRootFS={merged.get('readOnlyRootFilesystem', False)}")
for p in problems:
print(" ", p)api runAsUser=10001 readOnlyRootFS=True
legacy runAsUser=0 readOnlyRootFS=False
CreateContainerConfigError: runAsNonRoot and runAsUser is 0
migrate runAsUser=20001 readOnlyRootFS=False
Pod Security Standards
Kubernetes defines three Pod Security Standards profiles:
| Level | For | Highlights |
|---|---|---|
privileged |
System components | No restrictions |
baseline |
Typical apps | No privileged, no host namespaces (hostNetwork, hostPID), no hostPath, only a safe set of added capabilities |
restricted |
Hardened apps | Baseline plus: runAsNonRoot, allowPrivilegeEscalation: false, drop ALL capabilities, seccomp RuntimeDefault/Localhost, limited volume types |
Pod Security Admission (built in since 1.25) applies a level per namespace with labels, in three modes: enforce (reject), audit (log), warn (show a warning to the user):
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/warn: restrictedThis model checks a Pod against a subset of the restricted rules and prints messages like the real admission controller:
import yaml
def check_restricted(pod):
spec = pod["spec"]
psc = spec.get("securityContext", {})
errors = []
if spec.get("hostNetwork"):
errors.append("host namespaces (hostNetwork=true)")
if any("hostPath" in v for v in spec.get("volumes", [])):
errors.append("hostPath volumes")
for c in spec["containers"]:
sc = c.get("securityContext", {})
n = c["name"]
if sc.get("privileged"):
errors.append(f'privileged (container "{n}" must not set securityContext.privileged=true)')
if sc.get("allowPrivilegeEscalation", True):
errors.append(f'allowPrivilegeEscalation != false (container "{n}")')
if "ALL" not in sc.get("capabilities", {}).get("drop", []):
errors.append(f'unrestricted capabilities (container "{n}" must drop ALL)')
if not sc.get("runAsNonRoot", psc.get("runAsNonRoot", False)):
errors.append(f'runAsNonRoot != true (container "{n}")')
if sc.get("seccompProfile", psc.get("seccompProfile", {})).get("type") not in ("RuntimeDefault", "Localhost"):
errors.append(f'seccompProfile (container "{n}" must set type to RuntimeDefault or Localhost)')
return errors
pods = yaml.safe_load_all("""
metadata: {name: hardened}
spec:
securityContext: {runAsNonRoot: true, seccompProfile: {type: RuntimeDefault}}
containers:
- name: api
securityContext: {allowPrivilegeEscalation: false, capabilities: {drop: [ALL]}}
---
metadata: {name: naive}
spec:
containers:
- name: web
---
metadata: {name: agent}
spec:
hostNetwork: true
volumes: [{name: logs, hostPath: {path: /var/log}}]
securityContext: {runAsNonRoot: true, seccompProfile: {type: RuntimeDefault}}
containers:
- name: agent
securityContext: {privileged: true, allowPrivilegeEscalation: false, capabilities: {drop: [ALL]}}
""")
for pod in pods:
errors = check_restricted(pod)
name = pod["metadata"]["name"]
if not errors:
print(f'pod/{name} created')
else:
print(f'Error: pods "{name}" is forbidden: violates PodSecurity "restricted:latest":')
for e in errors:
print(" -", e)pod/hardened created
Error: pods "naive" is forbidden: violates PodSecurity "restricted:latest":
- allowPrivilegeEscalation != false (container "web")
- unrestricted capabilities (container "web" must drop ALL)
- runAsNonRoot != true (container "web")
- seccompProfile (container "web" must set type to RuntimeDefault or Localhost)
Error: pods "agent" is forbidden: violates PodSecurity "restricted:latest":
- host namespaces (hostNetwork=true)
- hostPath volumes
- privileged (container "agent" must not set securityContext.privileged=true)
The naive Pod (no security settings at all) fails four checks: the defaults are permissive, so hardening has to be explicit.
Building images for this
runAsNonRoot needs an image that works as a non-root user. In your Dockerfile, create a user and switch to it with a numeric UID (the kubelet can only verify numbers):
FROM python:3.13-slim
RUN useradd --uid 10001 --create-home app
WORKDIR /app
COPY --chown=10001:10001 . .
USER 10001
CMD ["python", "-m", "app"]Tip: Beyond Pod Security Admission, policy engines like Kyverno and OPA Gatekeeper (or built-in
ValidatingAdmissionPolicywith CEL) can enforce your own rules: "images must come from our registry", "every Deployment needs resource limits".
Go further: Pod Security Standards and Hardened Pods evaluates manifests against the three Pod Security levels.
Test yourself
What does readOnlyRootFilesystem: true do?
- Makes volumes read-only
- Makes the container's image filesystem read-only; writes must go to volumes
- Prevents reading files
- Mounts / from the host
How do you enforce the restricted Pod Security Standard in a namespace?
- A PodSecurityPolicy object
- The label
pod-security.kubernetes.io/enforce: restrictedon the namespace - An RBAC Role
- A NetworkPolicy
A Pod sets runAsNonRoot: true and a container sets runAsUser: 0. What happens?
- It runs as root
- It runs as UID 65534
- The container fails to start with a config error
- The Pod-level setting is ignored silently