Kubernetes Security Context: Configuration and Best Practices

Kubernetes security context main takeaways:
  • Kubernetes security contexts allow you to enforce the principle of least privilege and tighten runtime controls for both pods and containers.

  • Common misconfigurations include running as root, writable root filesystems, and excessive privileges that can create significant security risks.

  • Enforce security best practices by setting up non-root users, dropping unnecessary kernel capabilities, making root filesystems read-only, and disabling privilege escalation.

A Kubernetes security context defines the runtime privileges and access controls for pods and containers, making it one of the most critical levers for enforcing least privilege and reducing attack surface. By carefully configuring security contexts, you can increase the security posture of your workloads, mitigate potential threats, and simplify compliance.

The benefits of implementing security contexts

By implementing security contexts, teams gain fine-grained controls at both the pod and container levels. This practice helps them mitigate common vulnerabilities and enforce least privilege policies via settings like runAsNonRoot, readOnlyRootFilesystem, and scoped Linux capabilities. It also strengthens cluster-level defenses by leveraging SELinux options and AppArmor profiles.

Here are some key advantages of leveraging Kubernetes security contexts:

Enhanced security posture

Security contexts provide strict, runtime-level controls over containers and pods, including running processes as non-root users, restricting access to the root filesystem, and limiting Linux capabilities. These security measures limit privilege escalation and lateral movement, even if attackers compromise some individual containers.

Dica profissional

Set readOnlyRootFilesystem: true to prevent unauthorized write operations, which blocks attackers from modifying app files or installing malicious tools.

Reduced attack surface within Kubernetes clusters

Containers often run with more permissions than they require, providing attackers with additional avenues to exploit. To address this vulnerability, security contexts employ the principle of least privilege, ensuring container workloads run only with the permissions necessary for their specific tasks.

Dica profissional

Drop unnecessary kernel capabilities and set allowPrivilegeEscalation: false in your pod security policies to prevent containers from gaining elevated privileges or overriding the privilege level of their parent process.

Improved compliance and audit readiness

Regulated industries must maintain strict standards for protecting and storing consumer data. Security contexts help organizations comply with these requirements by enforcing security limitations during the container runtime. By combining these security context settings with admission controllers like Wiz, PSA, or OPA, you can ensure consistent enforcement across all workloads and automatically block pods with noncompliant security configurations.

Kubernetes Security Context Best Practices [Cheat Sheet]

A comprehensive guide to configuring security contexts for pods and containers in Kubernetes.

Types of security contexts

You can use security contexts in Kubernetes at two distinct levels: pod and container. Here’s how they work and the security controls they offer:

Pod security contexts

Pod security contexts apply to all containers within a pod, and you can set these in the pod specification file. Common options include the following:

  • SELinux options: Isolate pod processes from each other and the host to increase process separation.

  • fsGroup: Set the group ID (GID) for volumes to manage shared storage access within the pod.

  • runAsUser and runAsGroup: Specify user IDs and GIDs for your containers and ensure that workloads don't run as root.

Here’s an example of a minimal pod-level security context:

apiVersion: v1
kind: Pod
metadata:
  name: secure-pod
spec:
  securityContext:
    runAsUser: 1000
  containers:
  - name: app
    image: nginx

This configuration ensures that only users with the UID 1000 can run workloads in this pod.

Container security contexts

Container security contexts offer better granular control because you can define security settings for individual containers. Use these features to override pod-level security metadata:

  • Capability management: Control which Linux kernel capabilities to add or drop to maintain your ideal system footprint.

  • readOnlyRootFilesystem: Make the root filesystem read-only to prevent system modifications and limit breach impacts.

  • allowPrivilegeEscalation: Define if a process can obtain more privileges than its parent to contain privileged containers.

It’s critical to remember that container-level settings override pod-level security contexts. By combining pod-level and container-level security metadata in Kubernetes, you can tailor your security posture to meet the specific requirements of your applications while minimizing risk. Unsafe use of these settings may unintentionally introduce security risks in your workloads.

Common security context misconfigurations

Security context misconfigurations can lead to severe security issues for your Kubernetes resources, especially when deploying workloads with default security permissions, leaving them vulnerable to attacks. Watch out for the following key misconfigurations:

Running containers as root

Containers running with root user permissions grant application processes full admin rights. This practice is risky because it allows attackers to escape the container runtime, modify system files, or even compromise the underlying host node. 

🛠️Action step: Configure your workloads to run as non-root users by setting runAsNonRoot: true in the securityContext metadata field.

Not setting readOnlyRootFilesystem

Using readOnlyRootFilesystem: true prevents your processes from writing to the root filesystem, making it harder for attackers to tamper with system files, store malicious binaries, or gain persistence. 

🛠️Action step: Set the root filesystem as read-only to contain security attacks and enforce immutability for applications that don’t require root privileges at runtime.

Using privileged containers

Setting privileged: true in your securityContext metadata grants containers root access within the containers as well as the host node. These containers can directly interact with host hardware, volume mounts, and kernel parameters, opening the door to system compromise. 

🛠️Action step: Avoid using privileged containers by ensuring that privileged: true is not set in your securityContext, and regularly review workloads to remove unnecessary privileges.

Allowing privilege escalation

Configuring allowPrivilegeEscalation: false prevents container processes from gaining more privileges than their parent process. This field is true by default, making your workloads vulnerable to exploit chains where an attacker can elevate access after compromising a pod. 

🛠️Action step: Set this field to false to prevent privilege escalation.

Granting excessive Linux capabilities

Granting containers unnecessary Linux capabilities is another common security misconfiguration. Capabilities like CAP_SYS_ADMIN provide more functionality than most workloads require. By overprovisioning these, you risk privilege escalation and extend the impact of a compromise. 

🛠️Action step: Drop all unnecessary system capabilities and apply the principle of least privilege to your containers.

5 best practices for Kubernetes security contexts

Next, let’s look at five actionable best practices and the impact they have on your cluster's security:

1. Define security contexts at both pod and container levels

Applying security contexts at both the pod and container levels allows you to enforce granular security controls across all workloads. Here's how you can leverage security contexts to enhance protection at each layer:

  • Pod-level security contexts

Apply baseline security controls across all containers in a pod. These include using SELinux options, configuring file system groups (fsGroup), and specifying default user or group IDs (runAsUser, runAsGroup).

apiVersion: v1
kind: Pod
metadata:
  name: example-pod
spec:
  securityContext:
    runAsUser: 1000
    fsGroup: 2000
  containers:
  - name: example-container
    image: example/image

This YAML definition provides a non-root user (UID 1000) and associates a file system group (GID 2000) for all containers in the pod.

  • Container-level security contexts 

Use container-level security contexts to override pod metadata for specific workloads. For example, you can assign different Linux capabilities, user privileges, or file system restrictions to each container based on its role or function.

spec:
  containers:
  - name: example-container
    image: example/image
    securityContext:
      allowPrivilegeEscalation: false
      readOnlyRootFilesystem: true

This definition prevents container processes from gaining additional privileges by setting allowPrivilegeEscalation: false and makes the root filesystem read-only by using readOnlyRootFilesystem: true.

Pod-level security context also supports:

  • SELinux/AppArmor profiles: Configure seLinuxOptions in the pod securityContext to specify SELinux labels for enforcing mandatory access controls. Use pod annotations to assign AppArmor profiles for syscall filtering and process confinement.

  • fsGroup: Set fsGroup to define the group ID for all files shared by your containers, ensuring proper permissions for shared volumes.

  • seccomp profiles: Enable seccomp by applying profiles via seccompProfile and restrict which system calls are available to containers.

These features collectively provide layered isolation and increase security for all containers in the pod.

Container-level security context settings override pod-level settings. If you're not careful when overriding these contexts in the container metadata, you can unintentionally disable or weaken important pod-level security policies. 

For example, you might set strict security defaults, such as disabling privilege escalation and making filesystems read-only across the application pod. But what if you have a logging sidecar that needs write access for logs? In this case, override the security context only for that sidecar while keeping the application pod restricted.

Granular per-container controls are also valuable for passing audits and maintaining compliance with standards like PCI DSS or HIPAA, as they allow you to precisely map security controls to the regulatory requirements of each workload.

However, inconsistent container security settings (configuration drift) can weaken protections over time. Utilize policy enforcement tools like OPA Gatekeeper or PSA, or integrate CI checks during deployment to ensure consistent security context across workloads. You can then feed the metrics, logs, and policy violation reports from these platforms directly to your observability stack for detailed visualization of security context use and real-time alerts for violations.

2. Leverage readOnlyRootFilesystem for immutable containers

Attackers routinely target mutable containers because they can exploit them to upload web shells or persist after malware attacks. To prevent containers from writing to their root filesystem, set readOnlyRootFilesystem: true in your YAML’s security context field. Doing this blocks attackers from modifying application files, storing malicious executables, or maintaining persistent access in the event of a compromise.

securityContext:
  readOnlyRootFilesystem: true

If your applications require writing data to these filesystems, use mounted volumes with access control instead. Ensure apps only write to volume mounts by taking the following steps:

  • Defining and mounting volumes with correct access in your Pod spec

  • Updating app configs to use these volumes for all writes

  • Mounting volumes on the necessary paths for legacy apps that rely on a writable root, and refactoring when possible

Utilize tools like kube-bench and security scanners in CI/CD pipelines to verify compliance. You can also configure them to output structured JSON alerts, then forward them via webhooks or APIs to your SIEM platform to receive violation alerts as part of your SOC workflows.

To further strengthen your container defenses, combine read-only filesystems with additional security controls like process whitelisting, container image signing, and immutability enforcement within your CI/CD pipeline. This layered approach provides stronger protection against container attacks and unauthorized changes.

3. Enforce the use of non-root containers

Running containers as non-root users limits the potential impact of a compromise, as attackers will gain only restricted permissions to the containers. You can achieve this by setting the runAsUserfield in your security context to specify a non-root user ID.

securityContext:
  runAsUser: 1000

If you don't specify a non-root UID, most containers will default to running as root (UID 0), unless the image itself defines a different user. Consider adding `runAsNonRoot: true' to ensure container processes can't run as root, even if the image's default entry point attempts to do so.

Since most public container images try to run as root, using image scanning tools like Trivy, Grype, or Snyk can detect these images and assign non-root users. Selecting images that require only non-root users is another way of mitigating this issue.

Standards and guidelines like the CIS Kubernetes Benchmark also advise against using root in production (policy essentials). Audit your workloads for root users by setting up CI checks or deploying monitoring agents to adhere to these recommendations proactively.

Container Security Best Practices [Cheat Sheet]

Learn to secure containers end-to-end with zero trust, intrusion detection, and the right tools for Kubernetes, Docker, and cloud-native environments.

4. Disable privilege escalation

For attackers, privilege escalation from a compromised container to a more critical container or the host system is the ultimate target. By default, some containers may allow child processes to gain elevated root privileges at runtime. 

You can address this issue by setting allowPrivilegeEscalation: false in your container's security context. This field uses the no_new_privs flag of the Linux kernel to prohibit privilege escalation of child processes through the setuid or setgid binaries.

securityContext:
  allowPrivilegeEscalation: false
  privileged: false

You should also set privileged: false in your pod specs to prevent containers from gaining unrestricted access to the host. This security context field is more permissive than allowPrivilegeEscalation, as it grants unrestricted root access to the host machine running all your containers.

Recent container breakout and privilege escalation CVEs demonstrate why these settings are critical:

  • CVE-2024-21626: A vulnerability led to container breakout via file descriptor leaks, enabling privilege escalation and access to the host. 

  • CVE-2023-2640 and CVE-2023-32629: Attackers chained these vulnerabilities together to gain root access from within a non-root container by privilege escalation.

Setting privileged: false will block these attack vectors from gaining full kernel access to the host. You may also leverage admission policy tools like Pod Security Admission (PSA), Open Policy Agent (OPA), or custom webhooks to make this step non-optional across your Kubernetes clusters.

  • Pod Security Admission (PSA): Enable a cluster-wide "restricted" policy profile to enforce both allowPrivilegeEscalation: false and privileged: false by default for all containers.

  • OPA Gatekeeper: Deploy custom policies (ConstraintTemplates) to deny all pods with allowPrivilegeEscalation: true or privileged: true.

  • Admission webhooks: Implement webhooks that inspect pod specs on creation or update and reject any workload requesting privilege escalation.

If a container requests allowPrivilegeEscalation: true in violation of these policies, the policy tool or webhook can deny the workload at deployment.

5. Manage Linux capabilities with drop and add

Controlling Linux capabilities is crucial for minimizing container privileges to only those necessary for your workload. Use the capabilities field in your container's security context to explicitly drop unnecessary permissions, such as CAP_SYS_ADMIN, and only add those that are necessary.

securityContext:
  capabilities:
    drop:
    - ALL
    add:
    - NET_BIND_SERVICE

Some other high-risk Linux capabilities you should look out for include:

  • CAP_NET_ADMIN: Change network configurations

  • CAP_SYS_MODULE: Load/unload kernel modules

  • CAP_SYS_PTRACE: Enable process tracing and debugging

  • CAP_SYS_RAWIO: Perform raw I/O operations

Common Linux capabilities that are usually safe and often needed include:

  • CAP_CHOWN: Change file ownership

  • CAP_SETUID: Set user IDs

  • CAP_SETGID: Set group IDs

  • CAP_NET_BIND_SERVICE: Bind to ports below 1024

You can define a clear set of required capabilities for each container by iterative testing, app profiling, and leveraging vendor-specific security documentation.

  • Iterative testing: Start by dropping all capabilities (drop: ["ALL"]) and incrementally adding only those the app can't run without.

  • Application profiling: Use tools like strace or auditd to monitor syscalls and detect which capabilities your workloads request at runtime.

Granting excessive Linux capabilities increases the attack surface and makes it easy for attackers to move laterally for further compromise. For instance, an intruder with excessive kernel capabilities can remount critical filesystems like /proc as writable to escape container boundaries. Similarly, CAP_NET_ADMIN enables attackers to intercept or redirect network traffic within the cluster, which can lead to data exfiltration or man-in-the-middle attacks.

To protect your clusters against these scenarios, leverage capability checks in your CI/CD pipelines or use tools like kube-bench to detect excessive Linux capabilities. Policy enforcement tools like PSA and OPA Gatekeeper can also automate these checks across clusters.

Security context and compliance standards

Kubernetes security context helps organizations enforce key security controls that contribute to compliance with standards like PCI DSS, HIPAA, and GDPR. It does this by providing:

  • Access control: Security contexts help implement least privilege principles by running containers as non-root users, dropping unnecessary capabilities, and preventing privilege escalation.

  • Data protection: Settings like readOnlyRootFilesystem prevent unauthorized filesystem modifications and protect against data leakage from sensitive containers.

  • Auditability: Consistent securityContext policies simplify audit processes by enforcing compliance requirements through controlled, well-defined security baselines.

However, while Kubernetes security contexts help enforce container-level security, complete compliance requires a broader set of controls. To achieve this, you need to:

  • Implement RBAC to control user permissions

  • Deploy network policies to limit pod communication

  • Enable audit logging for traceability

  • Use tools like Wiz, PSA, or OPA to automate policy enforcement

Combining these Kubernetes best practices with security contexts creates a layered defense that complies with industry regulations and keeps your business audit-ready. The following table outlines which security context control helps with which compliance frameworks.

ControlPCI DSSCISNIST
Non-root user/runAsUser
Drop unsafe capabilities
readOnlyRootFilesystem

Security context and pod security admission

Pod Security Admission (PSA) implements security policies at the Kubernetes namespace level by validating pod specifications, including security context settings, before deploying them. PSA uses predefined policy levels (privileged, baseline, and restricted) to control which security settings to permit.

For example, the “restricted” policy requires containers to run as non-root users, turns off privileged mode, and limits kernel capabilities. If a pod’s securityContext field doesn’t meet these requirements, PSA can block its deployment, issue a warning, or log the violation, depending on the configured mode.

The following pod security admission configuration enforces the 'restricted' security profile cluster-wide by default, rejecting any pods that don’t comply, except for the kube-system namespace, which is exempt from these restrictions.

apiVersion: apiserver.config.k8s.io/v1
kind: AdmissionConfiguration
plugins:
  - name: PodSecurity
    configuration:
      apiVersion: pod-security.admission.config.k8s.io/v1
      kind: PodSecurityConfiguration
      defaults:
        enforce: restricted
      exemptions:
        usernames: []
        runtimeClasses: []
        namespaces:
          - kube-system

Wiz: A full-stack Kubernetes security platform

Kubernetes misconfigurations, such as running containers as root, using privileged mode, or granting excessive Linux capabilities, can quietly weaken cluster defenses. Earlier, we showed how these mistakes create risks, ranging from filesystem tampering to full node compromise.

Wiz directly addresses these pain points by:

  • Detecting misconfigurations before deployment: Wiz scans your Kubernetes manifests, Helm charts, and IaC templates to detect risky securityContext settings (like writable filesystems or containers running as root) before deployment.

  • Enforcing best practices at admission: With the Wiz Admission Controller, you can block pods that request privilege escalation or override restricted profiles.

  • Maintaining compliance posture: Wiz maps security context settings to PCI DSS, HIPAA, and CIS benchmarks, giving you out-of-the-box visibility into audit readiness.

  • Continuous runtime monitoring: Even if workloads drift from policy post-deployment, Wiz detects changes (like added capabilities) and alerts your team in real time.

Want to enforce Kubernetes security best practices and detect misconfigurations in real time? Wiz automates security posture management and integrates with your CI/CD pipeline. Schedule a demo to see how. Or, for an immediate, practical guide, download our Kubernetes Security Contexts Cheat Sheet and start implementing best practices today.