Kubernetes security context defines the privilege and access control settings for individual containers and pods. This configuration layer sits directly within the PodSpec, allowing fine-grained control over how code executes on the cluster. Without a defined context, processes run with unnecessary permissions, increasing the blast radius of a potential compromise. Treating this setting as a first-class citizen in your deployment strategy is fundamental to defense-in-depth.
Understanding the Core Mechanics
The security context is a JSON field that communicates Linux-level security options to the kubelet. It leverages concepts inherited from the underlying operating system, specifically User ID (UID) and Group ID (GID) management. When you deploy a container, the runtime uses these identifiers to enforce file permissions and process capabilities. Misalignment between the user in the container image and the security context often leads to permission errors or, conversely, privilege escalation.
RunAsNonRoot and UID Management
A foundational practice is enforcing the use of non-root users. The runAsNonRoot field instructs the kubelet to reject pods that attempt to start with a UID of 0. This simple rule prevents containers from gaining host-level privileges through known root exploit paths. For maximum safety, you should also explicitly set runAsUser to a specific, dedicated UID that the application inside the image is designed to use.
Capability Boundaries and Process Isolation
Linux capabilities break down the all-powerful root user into distinct units. By default, containers often receive a broad set of these capabilities, which is excessive for most applications. The capabilities field within the security context allows you to drop all inherited rights and add only the specific ones required for network binding or raw socket access. Dropping capabilities like SYS_ADMIN or NET_ADMIN effectively hardens the process against host intrusion.
Immutable Files and ReadOnlyRootFilesystem
Setting readOnlyRootFilesystem: true is a disruptive but highly effective security control. It mounts the container's root layer as read-only, preventing malware or compromised processes from writing persistent changes. When combined with an emptyDir volume for temporary writable directories, this setup ensures that any malicious activity is confined to memory and lost upon pod restart. This approach aligns perfectly with immutable infrastructure principles.
Pod-Level vs. Container-Level Scope
It is important to distinguish between pod-level and container-level security contexts. A pod context applies to the infrastructure surrounding the containers, such as the network namespace and the Service Account token. A container context, however, dictates the runtime identity of the specific binary inside the image. For strict security, you should define both scopes independently, ensuring the pod runs with minimal trust and the container runs with minimal privileges.