Kubernetes Security Contexts: A Practical Guide to Workload Hardening
Learn how to secure Kubernetes workloads using security contexts, Linux capabilities, seccomp, Pod Security Standards, and OpenShift SCCs.

On this page
Running applications on Kubernetes does not automatically make them secure. Containers share the host’s Linux kernel and interact with storage, networking, and the Kubernetes API. Without appropriate restrictions, a compromised application can potentially access sensitive resources or escalate privileges.
Kubernetes security contexts define operating-system privileges and security constraints applied to pods and containers. This guide explains how to use them in production, including considerations for OpenShift.
Understanding Security Contexts
A pod-level securityContext defines shared defaults such as execution identity, filesystem groups, and seccomp. A container-level securityContext controls privileges, Linux capabilities, and filesystem behavior. Container settings override corresponding pod defaults where supported.
apiVersion: v1
kind: Pod
metadata:
name: secure-app
spec:
securityContext:
runAsNonRoot: true
seccompProfile:
type: RuntimeDefault
containers:
- name: app
image: registry.example.com/app:1.0
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]This combines non-root execution, disabled privilege escalation, a read-only root filesystem, dropped capabilities, and runtime-default syscall filtering. These controls are one layer of defense, not a replacement for network policies, RBAC, image security, or runtime monitoring.
Running Containers Without Root Privileges
Many images assume UID 0, but applications should generally run without root privileges. A conventional Kubernetes deployment can specify:
securityContext:
runAsNonRoot: true
runAsUser: 10001
runAsGroup: 10001runAsNonRoot requires a non-root execution identity; runAsUser and runAsGroup specify numeric IDs.
OpenShift: Avoid Hardcoded UIDs Where Possible
OpenShift commonly allocates namespace-specific UID ranges through Security Context Constraints (SCCs). Hardcoding runAsUser: 10001 may conflict with those constraints and cause admission failures.
For portable images, prefer non-root execution without assuming a fixed UID:
securityContext:
runAsNonRoot: true
allowPrivilegeEscalation: falseThe image must still support a non-root identity. OpenShift-compatible images should tolerate arbitrary UIDs, avoid root-only writable paths, and use suitable filesystem permissions.
Preventing Privilege Escalation
Linux executables can gain privileges through mechanisms such as setuid binaries and file capabilities. For ordinary applications, disable this behavior:
securityContext:
allowPrivilegeEscalation: falseOn Linux, this uses the kernel’s no_new_privs behavior. It should be combined with capability restrictions and avoidance of privileged execution; privileged containers and containers with CAP_SYS_ADMIN cannot effectively disable privilege escalation this way.
Reducing Linux Capabilities
Linux capabilities split traditional root privileges into narrower permissions.
| Capability | Purpose |
|---|---|
NET_BIND_SERVICE | Bind privileged ports |
NET_ADMIN | Change network configuration |
NET_RAW | Use raw sockets |
SYS_PTRACE | Trace processes |
SYS_TIME | Modify system time |
SYS_ADMIN | Broad system administration operations |
Drop all capabilities by default:
securityContext:
capabilities:
drop:
- ALLOnly add back a capability when required and justified:
securityContext:
capabilities:
drop: ["ALL"]
add: ["NET_BIND_SERVICE"]Often even NET_BIND_SERVICE can be avoided by listening on port 8080 and exposing port 80 or 443 through a Kubernetes Service. Treat elevated capabilities as exceptions requiring review.
Making the Root Filesystem Read-Only
A writable root filesystem gives compromised processes more opportunities to alter files within the container. For applications that support it:
securityContext:
readOnlyRootFilesystem: trueMount explicit writable paths for temporary data:
containers:
- name: app
image: registry.example.com/app:1.0
securityContext:
readOnlyRootFilesystem: true
volumeMounts:
- name: temporary-data
mountPath: /tmp
volumes:
- name: temporary-data
emptyDir:
sizeLimit: 256MiA read-only root filesystem does not make mounted volumes read-only. Check whether the application needs caches, PID files, or other writable directories, and provide narrowly scoped mounts.
Restricting System Calls with Seccomp
Seccomp limits which Linux system calls a process may execute. Kubernetes supports RuntimeDefault, Localhost, and Unconfined profiles.
For most application workloads:
spec:
securityContext:
seccompProfile:
type: RuntimeDefaultThe exact filtering depends on the container runtime. Custom Localhost profiles can be more restrictive but must exist on the relevant nodes and be maintained as application and kernel behavior evolves. Start with RuntimeDefault unless a stronger requirement justifies custom profiles.
AppArmor and SELinux
Seccomp filters system calls; Linux Security Modules provide additional mandatory access controls.
AppArmor can constrain filesystem access and other operations. On supported nodes, Kubernetes can request:
spec:
securityContext:
appArmorProfile:
type: RuntimeDefaultSELinux is especially relevant on Red Hat Enterprise Linux and OpenShift. Kubernetes exposes seLinuxOptions, but actual labels and permitted configurations depend on platform policy and admission controls. On OpenShift, prefer platform-managed SELinux labeling unless there is a documented exception.
Enforcing Pod Security Standards
Kubernetes Pod Security Standards (PSS) define three levels:
| Level | Posture | Typical use |
|---|---|---|
| Privileged | Broadly unrestricted | Trusted infrastructure components |
| Baseline | Prevents known privilege escalations | General workloads |
| Restricted | Stronger least-privilege requirements | Compatible production applications |
Pod Security Admission can enforce a level through namespace labels:
apiVersion: v1
kind: Namespace
metadata:
name: production
labels:
pod-security.kubernetes.io/enforce: restricted
pod-security.kubernetes.io/audit: restricted
pod-security.kubernetes.io/warn: restrictedenforce rejects violating pods, audit records violations, and warn displays warnings. For predictable upgrades, consider pinning a tested policy version instead of using latest indefinitely.
OpenShift SCCs Are Separate
OpenShift SCCs govern UID allocation, host access, privileges, capabilities, and volume usage. SCCs and Pod Security Admission coexist but are not interchangeable. A workload admitted by an SCC is not necessarily compliant with every PSS profile. Assess both mechanisms when designing OpenShift security policy.
Production-Oriented Deployment Example
This Deployment assumes the image can run as a non-root user, listens on port 8080, and only needs writable temporary storage under /tmp.
apiVersion: apps/v1
kind: Deployment
metadata:
name: secure-webapp
namespace: production
spec:
replicas: 3
selector:
matchLabels:
app: secure-webapp
template:
metadata:
labels:
app: secure-webapp
spec:
automountServiceAccountToken: false
securityContext:
runAsNonRoot: true
seccompProfile:
type: RuntimeDefault
containers:
- name: webapp
image: registry.example.com/webapp:1.0
ports:
- name: http
containerPort: 8080
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]
resources:
requests:
cpu: 100m
memory: 128Mi
limits:
cpu: "1"
memory: 512Mi
volumeMounts:
- name: tmp
mountPath: /tmp
volumes:
- name: tmp
emptyDir:
sizeLimit: 256MiThis is intended to meet the Linux Restricted Pod Security Standard, subject to cluster policy and image compatibility. Admission success alone does not prove that the application will work: test startup, filesystem permissions, and runtime behavior.
Service Account Tokens
automountServiceAccountToken: false prevents automatic mounting of Kubernetes API credentials when they are not needed. For workloads that require API access, use a dedicated service account with minimal RBAC permissions. For external audiences, consider projected tokens with explicit audiences and bounded lifetimes.
Validating Security Configuration
Inspect actual deployed settings:
kubectl get pods -n production -o json | jq '
.items[] |
{
pod: .metadata.name,
containers: [
.spec.containers[] |
{name: .name, securityContext: .securityContext}
]
}'Find explicitly privileged application containers:
kubectl get pods -A -o json | jq -r '
.items[] as $pod |
$pod.spec.containers[] |
select(.securityContext.privileged == true) |
"\($pod.metadata.namespace)/\($pod.metadata.name):\(.name)"'Find application containers without an explicit read-only root filesystem:
kubectl get pods -A -o json | jq -r '
.items[] as $pod |
$pod.spec.containers[] |
select(.securityContext.readOnlyRootFilesystem != true) |
"\($pod.metadata.namespace)/\($pod.metadata.name):\(.name)"'These are configuration checks, not complete proofs of insecurity. Extend audits to init and ephemeral containers, consider admission defaults, and distinguish legitimate infrastructure exceptions.
Test a manifest against admission controls without persisting it:
kubectl apply --dry-run=server -f secure-deployment.yamlOn OpenShift, use oc apply --dry-run=server and assess SCC behavior as well.
Making Security a Platform Default
Manually configuring each Deployment does not scale. A platform engineering approach should combine:
- Secure application templates: Provide standard manifests, Helm conventions, or internal developer platform components with safe defaults.
- Admission enforcement: Use Pod Security Admission and, where needed, policies with Kyverno or OPA Gatekeeper.
- CI/CD validation: Test manifests early with tools such as Kyverno CLI or Conftest.
- Runtime verification: Audit deployed workloads and periodically review documented exceptions.
The objective is not merely to reject insecure workloads. It is to make secure deployment the easiest, most repeatable path.
Common Implementation Mistakes
- Hardcoded UIDs: These may conflict with OpenShift’s namespace-specific UID ranges.
- Untested capability removal: Some applications rely on capabilities that are not obvious from their manifests.
- Read-only root without writable mounts: Caches, temporary files, and PID files can break startup.
- Treating PSS as complete isolation: PSS does not replace RBAC, network policies, image provenance, or monitoring.
- Using privileged mode to fix deployment failures: This may eliminate critical security boundaries instead of solving image compatibility issues.
- Applying Restricted blindly: Storage, networking, monitoring, and other platform components may require narrowly controlled exceptions.
Recommended Workload Security Baseline
| Control | Recommended baseline |
|---|---|
| Execution identity | runAsNonRoot: true |
| UID | Non-root and platform-compatible |
| Privilege escalation | allowPrivilegeEscalation: false |
| Root filesystem | readOnlyRootFilesystem: true where supported |
| Linux capabilities | drop: ["ALL"] |
| Seccomp | RuntimeDefault |
| Privileged mode | Disabled |
| Service account token | Disable automount unless required |
| Pod Security Standard | Restricted for compatible workloads |
| AppArmor / SELinux | Use supported platform controls |
| Resources | Explicit requests and limits |
This is a baseline, not a universal manifest. Databases, storage drivers, networking components, and platform operators may need carefully scoped exceptions.
Conclusion: Make Least Privilege a Platform Property
Security contexts reduce the attack surface of Kubernetes workloads by restricting execution identities, Linux capabilities, privilege escalation, system calls, and filesystem writes.
Their real value comes from consistent application across environments. Secure defaults should be embedded in templates, enforced through admission policies, tested in CI/CD, and checked against deployed workloads.
For organizations operating Kubernetes and OpenShift at scale, workload hardening is therefore a platform engineering responsibility—not simply a collection of YAML settings.
The goal is to make least-privilege execution a predictable, repeatable property of the platform.


