CNCFKubernetesApplication DevelopmentIntermediate22 min read

What Does Pod Security Context Mean?

Also known as: Pod Security Context, Kubernetes security context, CKAD exam security context, Pod security Kubernetes, runAsNonRoot

Reviewed byJohnson Ajibi· Senior Network & Security Engineer · MSc IT Security
On This Page

Quick Definition

A Pod Security Context is a set of rules you apply to a Pod in Kubernetes. It controls what the Pod and its containers are allowed to do on the host system, like which user they run as, whether they can access the host filesystem, or if they can gain extra privileges. This helps keep the cluster secure by limiting what processes inside containers can do outside their boundaries.

Must Know for Exams

The CKAD exam (Certified Kubernetes Application Developer) tests Pod Security Context as part of the “Pod Design” and “Configuration” domains. According to the CNCF exam curriculum, candidates must be able to “understand and define Pod Security Contexts” and “configure security settings for Pods and containers.” This includes setting `runAsUser`, `runAsGroup`, `fsGroup`, `capabilities`, `privileged`, and `readOnlyRootFilesystem`.

Exam questions often present a scenario where an application is failing to start or is behaving unexpectedly. The candidate must examine the Pod manifest, identify a missing or misconfigured security context, and fix it. For example, a container that needs to read a ConfigMap mounted as a volume might fail because `fsGroup` is not set, so the container’s process cannot read the files due to permission issues.

Another common exam objective is modifying an existing Deployment to run as a non-root user. The candidate must add a `securityContext` block with `runAsUser: 1000` and `runAsNonRoot: true`. The exam may also ask to restrict the container from escalating privileges by setting `allowPrivilegeEscalation: false`.

The CKA exam (Certified Kubernetes Administrator) also touches on security context, but from an administrator’s perspective. Candidates may need to enable the Pod Security Admission controller or create Pod Security Standards to enforce security contexts across the cluster.

For the CKAD, the key is to practice writing YAML manifests with security contexts and to understand how different settings interact. For example, setting `runAsUser: 0` (root) will override `runAsNonRoot: true` because the container will still run as root, causing startup failure. Knowing that the container-level security context overrides the Pod-level context is also frequently tested.

The exam does not require deep Linux kernel knowledge, but candidates must know which fields exist and their typical values. Time management is important: a question that asks to add a security context to a Pod takes only a few lines of YAML, but misconfiguring it can waste time debugging.

Simple Meaning

Think of a Pod Security Context as a set of permission badges for a package delivery worker inside a large office building. In this analogy, the building is the Kubernetes node (the server), and each delivery worker is a container running inside a Pod. Without any security context, every worker would have the master key to every room, could open any door, and could even change the building’s thermostat or security system. That would be a huge risk if one worker made a mistake or turned out to be malicious.

A Pod Security Context gives each worker a specific badge. One badge might say the worker can only enter the loading dock and delivery rooms, and must use a specific employee ID number (the user ID). Another badge might forbid the worker from becoming a security guard (no privilege escalation). Another badge might prevent the worker from seeing any mail that is not addressed to them (restricting system calls).

You can set the security context at two levels: the entire Pod (all workers in that team) or individually for each container (each worker separately). The Pod-level settings apply to every container in the Pod, but container-level settings can override them for a specific container. For example, you might set a Pod-level rule that tells all containers to run as a non-root user, and then for one container that needs special hardware access, you give it an extra permission like access to a network device.

This concept is important because containers share the host kernel. If a container runs as root or with too many capabilities, a security breach in that container could let an attacker take over the entire host. The security context is a fine-grained tool to reduce that risk without breaking legitimate application needs.

Full Technical Definition

A Pod Security Context is a Kubernetes API object (part of the PodSpec) that configures security-related settings for a Pod and its containers. It is defined under the `securityContext` field in the Pod manifest, either at the Pod level or the container level. The Pod-level security context applies to all containers in the Pod, while the container-level security context can override or extend it for a specific container.

The key fields in a Pod Security Context include:

`runAsUser`: Specifies the user ID (UID) that the container processes will run as. If not set, the container may default to root (UID 0), which is a security risk. Setting this to a non-zero UID is a best practice.

`runAsGroup`: Specifies the group ID (GID) for the container processes. This controls which files and resources the process can access based on group permissions.

`fsGroup`: Specifies a group ID that applies to all volumes mounted into the Pod. Any files created on those volumes will have this group ownership, enabling multiple containers to share data.

`runAsNonRoot`: A boolean that, when set to true, prevents the container from running as root. If the container image tries to start as root, the Pod will fail to start. This is enforced by the container runtime.

`privileged`: A boolean that, when true, gives the container nearly all capabilities of the host, equivalent to running as root on the host. This should be used very rarely and only for trusted workloads.

`capabilities`: Allows adding or removing Linux capabilities (e.g., CAP_NET_ADMIN, CAP_SYS_TIME). Instead of running the container as privileged, you can grant only specific capabilities it needs. This follows the principle of least privilege.

`readOnlyRootFilesystem`: Forces the container’s root filesystem to be read-only. This prevents the container from writing to its own filesystem, which reduces the attack surface for malware that tries to modify binaries.

`seLinuxOptions`: Configures SELinux labels for the container, providing mandatory access control on systems with SELinux enabled.

`seccompProfile`: Specifies a seccomp profile to restrict system calls the container can make. This is a powerful way to reduce kernel attack surface.

In real IT environments, Platform Engineering teams or cluster administrators define Pod Security Standards, such as the Kubernetes built-in restricted, baseline, and privileged policies. These are enforced using admission controllers like Pod Security Admission or third-party tools like OPA/Gatekeeper. Developers then configure their Pod Security Context to comply with these policies.

The security context is part of the Pod spec and is evaluated at Pod creation time. If the settings violate an admission policy, the Pod is rejected. Understanding Pod Security Context is critical for the CKAD exam, especially in questions about running containers securely and debugging Pod startup failures caused by security restrictions.

Real-Life Example

Imagine a library with many departments: a children’s section, a reference room, a rare book vault, and a staff-only archives room. Each department has different levels of access. A library visitor (a container) gets a library card (the security context) that defines exactly what they can do.

For the children’s section, the card might say: you can enter this room, but you cannot take books off the shelf (read-only root filesystem). You must be accompanied by a parent (runAsNonRoot is false, but capabilities are limited). You cannot go into the staff-only area (no privilege escalation).

For a librarian (a container that needs to update the catalog), the card grants access to the reference room and the catalog computer, but still forbids entering the rare book vault (no CAP_SYS_ADMIN). The librarian also runs as user ID 500 (runAsUser: 500) and group ID 100 (runAsGroup: 100), so they can only modify files owned by that group.

For the rare book curator, the card grants access to the vault, but only during certain hours (similar to fsGroup for volume access). The curator also has a special key to open display cases (added capabilities like CAP_DAC_OVERRIDE).

The library’s security policy (Pod Security Admission) checks every card at the entrance. If a visitor tries to use a card that claims to be a curator but lacks the proper permissions, the entry system blocks them. This is exactly how Pod Security Context works: it defines the permissions for each container, and the cluster enforces those limits to protect the shared host resources.

Why This Term Matters

Pod Security Context matters because it is a fundamental layer of defense in Kubernetes security. In a shared cluster, many Pods run on the same node, sharing the same kernel. If one container escapes its isolation or gains root access, it can compromise other workloads, steal data, or even take over the entire node. The security context reduces this risk by enforcing the principle of least privilege.

For real IT work, consider a company running a multi-tenant Kubernetes cluster where teams deploy their own applications. Without Pod Security Context, a developer might accidentally deploy a container that runs as root, exposes a vulnerable service, and allows an attacker to pivot to the host. By setting `runAsNonRoot: true` and `readOnlyRootFilesystem: true`, the platform team can prevent many common attack vectors.

In cybersecurity, the security context is also a compliance requirement. Standards like PCI-DSS, HIPAA, and SOC2 often require that containers do not run as root and that sensitive workloads have restricted capabilities. The security context provides the mechanism to meet these requirements at the Pod level.

For system administrators, misconfigured security contexts are a common source of Pod failures. A container that tries to write to its root filesystem will crash if `readOnlyRootFilesystem: true` is set without a volume mount for writable data. A container that needs to bind to a low port (like port 80) will fail if it cannot run as root. Understanding security context helps administrators quickly diagnose these issues.

In cloud infrastructure, the security context also interacts with other security features like NetworkPolicies, RBAC, and PodSecurityPolicies (deprecated in favor of Pod Security Admission). A well-designed security posture layers these controls, with the security context being the innermost layer that controls what a container can do inside its own sandbox.

How It Appears in Exam Questions

In certification exams, Pod Security Context appears in several question formats:

Scenario questions: You are given a Pod manifest that fails to start. The error message indicates a permission issue, or the container shows a CrashLoopBackOff. You must read the manifest, spot the missing `runAsUser` or `fsGroup` setting, and fix it. For example, a Pod that mounts a PersistentVolumeClaim may need `fsGroup: 2000` to allow the container to write to the volume.

Configuration questions: The question provides a specification (e.g., “Run the container as user 1001, ensure it cannot escalate privileges, and make the root filesystem read-only”). You must write or modify a Pod YAML to include the correct `securityContext` block. These questions test your ability to translate requirements into YAML syntax.

Troubleshooting questions: The question shows `kubectl describe pod` output where the container is failing with “permission denied” or “Operation not permitted.” You must deduce which security context setting is missing or incorrect. For instance, if a container needs to change system time, it requires `CAP_SYS_TIME` capability. The question might ask you to add only that capability without making the container privileged.

Architecture questions: You might be asked to compare two Pod specs and choose the more secure one. This tests your understanding of which settings reduce the attack surface. For example, a Pod with `privileged: true` is less secure than one with specific capabilities added.

Multiple-choice questions: Less common in CKAD (which is performance-based), but in the CKA or other theoretical exams, you may see questions like “Which field in the Pod Security Context ensures a container cannot run as root?” The answer is `runAsNonRoot`.

A concrete example: The question states, “You have a Pod that needs to bind to port 80. It currently runs as user 1000. The Pod is failing. Modify the Pod to allow it to bind to the port without running as root.” The solution is to add `capabilities: add: [ “NET_BIND_SERVICE” ]` to the container security context. This demonstrates understanding of fine-grained permission management.

Study cncf-ckad

Test your understanding with exam-style practice questions.

Practise

Example Scenario

Situation: A company called FinSave runs a Kubernetes cluster for its payment processing application. The application runs in a Pod called `payment-processor`. The security team requires that all containers must run as non-root, must not have any unnecessary kernel capabilities, and must have a read-only root filesystem. The application needs to write logs to a mounted volume at /var/log/app.

The developer creates a Pod manifest with `runAsNonRoot: true` and `readOnlyRootFilesystem: true` at the container level. They also set `runAsUser: 1001`. However, they forget to set `fsGroup` for the mounted volume. When the Pod starts, the container cannot write to /var/log/app because the directory is owned by root and the container runs as user 1001. The log file creation fails, and the application crashes.

How the concept applies: The security context `fsGroup` is needed to set the group ownership of the mounted volume to a specific GID that the container can access. The developer should add `fsGroup: 3000` to the Pod-level security context, and ensure the container’s process is in group 3000. Alternatively, they could create the log directory with proper permissions in a Dockerfile, but in a dynamic environment, `fsGroup` is the standard approach. This example shows how security context settings must be carefully coordinated with volume mounts and application requirements.

Common Mistakes

Setting runAsNonRoot: true but not specifying runAsUser, assuming the container will automatically pick a non-root user.

If the container image does not have a defined USER directive, it defaults to root (UID 0). Setting runAsNonRoot: true without runAsUser will cause the Pod to fail because the container still tries to run as root, violating the policy.

Always combine runAsNonRoot: true with an explicit runAsUser set to a non-zero UID (e.g., runAsUser: 1001) or ensure the container image defines a non-root user in its Dockerfile.

Setting privileged: true when only a single Linux capability is needed.

Using privileged: true grants the container all capabilities, including dangerous ones like CAP_SYS_ADMIN and CAP_NET_ADMIN. This violates the principle of least privilege and massively increases the attack surface.

Identify the specific capability the container needs (e.g., CAP_NET_RAW for ping) and add only that capability using the capabilities.add field, avoiding privileged mode.

Setting readOnlyRootFilesystem: true but not providing a writable volume for temporary files or logs.

Many applications need to write temporary files (e.g., in /tmp) or logs. With a read-only root filesystem, these writes fail, causing application crashes or startup failures.

Add an emptyDir volume mounted at the writable path (e.g., /tmp) or a PersistentVolumeClaim at the log location. Ensure the security context's fsGroup matches the volume permissions.

Forgetting that container-level securityContext overrides Pod-level securityContext, leading to unexpected behaviour.

If the Pod-level securityContext sets runAsUser: 1000, but a specific container sets runAsUser: 0, that container will run as root, bypassing the Pod-level restriction. The Pod-level settings are not enforced on that container.

Remove the container-level securityContext if the Pod-level settings are sufficient, or ensure container-level settings are at least as restrictive as the Pod-level settings for security-sensitive fields.

Using fsGroup without considering that it only works for volumes that support ownership management (e.g., not for hostPath or emptyDir in some configurations).

fsGroup sets the group ownership for volumes, but not all volume types are affected. For hostPath volumes, the ownership is controlled by the host filesystem. Relying solely on fsGroup for security on hostPath volumes may not work as expected.

Use PersistentVolumeClaims or CSI-backed volumes for consistent security context behavior. For hostPath, manage permissions on the host or use securityContext.runAsUser to match the host directory ownership.

Exam Trap — Don't Get Fooled

Setting runAsUser: 0 (root) and runAsNonRoot: true in the same Pod manifest will still allow the container to run as root because runAsUser: 0 overrides runAsNonRoot. Remember that runAsNonRoot: true forces the container to run as a non-root user by causing a startup error if the specified user is root. If you also set runAsUser: 0, the container will be considered root and the Pod will fail.

The only safe combination is runAsNonRoot: true with a non-zero runAsUser, or omit runAsUser but ensure the container image’s USER is non-root.

Commonly Confused With

Pod Security ContextvsPod Security Policy (PSP)

A Pod Security Context is a per-Pod setting you configure in the Pod manifest to control its own permissions. A Pod Security Policy was a cluster-level resource that enforced default security contexts across all Pods in a namespace. PSP has been deprecated in Kubernetes 1.25 and replaced with Pod Security Admission and Pod Security Standards.

You use securityContext in a Pod YAML to say “this Pod runs as user 1000.” A Pod Security Policy would be a separate YAML that says “all Pods in this namespace must run as a user between 1000 and 2000.”

Pod Security ContextvsSecurityContext for containers in Docker or containerd

Pod Security Context is a Kubernetes abstraction that translates to lower-level runtime security settings (like user namespaces, capabilities, and seccomp profiles). The container runtime (Docker, containerd, CRI-O) implements these settings at the kernel level, but the securityContext in Kubernetes provides a unified way to configure them without dealing with runtime-specific details.

In a Docker run command, you use --user 1000 and --cap-drop=ALL. In Kubernetes, you set securityContext.runAsUser: 1000 and capabilities.drop: ["ALL"] in the Pod YAML.

Pod Security ContextvsPodDisruptionBudget

PodDisruptionBudget (PDB) is about ensuring availability by limiting the number of Pods that can be voluntarily disrupted at a time. It has nothing to do with security permissions. A Pod Security Context controls what a container can do, while a PDB controls whether a Pod can be evicted during maintenance.

A securityContext says “do not run as root.” A PDB says “keep at least 2 replicas running during node updates.” They address completely different concerns.

Step-by-Step Breakdown

1

Identify the minimum privileges required

Before writing the securityContext, analyse what the container process actually needs. Does it need full root access, or only a few capabilities like the ability to bind to a low port? Does it need to write to its own filesystem, or can a separate volume handle writes? This step ensures you follow least privilege.

2

Set the user and group IDs

Use runAsUser and runAsGroup to specify the UID and GID for the container process. For security, always use a non-zero UID. If the application expects to write to mounted volumes, also set fsGroup so the volumes have the correct group ownership.

3

Enable runAsNonRoot

Set runAsNonRoot: true to enforce that the container does not run as root. This is a cluster policy in many organizations. Note that this will cause the Pod to fail if runAsUser is 0 or if the container image’s USER is root without an explicit runAsUser set to a non-zero value.

4

Configure the root filesystem as read-only

Set readOnlyRootFilesystem: true to prevent the container from modifying its own binaries or configuration files. This limits the damage a compromised container can do. If the application needs writable space, mount an emptyDir or PVC at the required path.

5

Add or drop Linux capabilities

Use capabilities.add and capabilities.drop to fine-tune what kernel-level operations the container can perform. Start by dropping all capabilities (drop: ["ALL"]) and then add back only the needed ones. For example, add "NET_BIND_SERVICE" for binding to ports under 1024 without root.

6

Disable privilege escalation

Set allowPrivilegeEscalation: false to prevent the container from gaining more privileges than its parent process. This blocks attacks that use SUID binaries or other mechanisms to become root. This is a critical security hardening step.

7

Review and test the configuration

Create or update the Pod and check if it starts correctly. Use kubectl describe pod to see any security-related errors. Verify that the container runs with the expected user (e.g., kubectl exec pod -- id). Adjust settings if the application fails due to missing permissions, but always prefer the most restrictive options that still allow the app to function.

Practical Mini-Lesson

Pod Security Context is one of the most practical tools a Kubernetes developer uses to secure applications. In real production clusters, you rarely see privileged containers except for very specific system software like monitoring agents or network plugins. The vast majority of application Pods should run as a non-root user with a read-only root filesystem and only the capabilities they explicitly need.

To configure a Pod Security Context in practice, you add a securityContext field either at the Pod level (under spec) or at the container level (under spec.containers[].securityContext). If you set it at the Pod level, it applies to all containers in the Pod. If you set it at the container level, it overrides the Pod-level settings for that container. This is important when you have sidecar containers that need different permissions than the main application. For example, a logging sidecar might need to write to a shared log volume, while the main application runs as a read-only process.

A common mistake in production is that developers forget to set fsGroup when using PersistentVolumeClaims. The fsGroup field tells Kubernetes to change the group ownership of the mounted volume to a specific GID. Without it, the volume may be owned by root, and a non-root container cannot write to it. You can check the ownership with kubectl exec into the Pod and run ls -l on the mount path. If the directory is owned by root and the container runs as user 1001, you need to either add fsGroup: 1001 or set the volume with the correct permissions in the storage class.

Another practical issue involves capabilities. Developers often request privileged mode because the container needs to run iptables or bind to a low port. Instead, you should research which capabilities cover those needs. For iptables, the required capability is CAP_NET_ADMIN. For binding to a port under 1024, it is CAP_NET_BIND_SERVICE. Using capabilities.drop: ["ALL"] and then adding back only the necessary ones is the gold standard. This reduces the attack surface dramatically.

When troubleshooting a Pod that fails due to security context, start by checking the events with kubectl describe pod. The error message might say “container has runAsNonRoot and image will run as root” or “permission denied.” If it is a permission error on a volume, verify the fsGroup matches the container’s group. If it is a capability error, check the application logs for messages like “operation not permitted.”

Pod Security Context also integrates with Pod Security Admission (PSA), which is the built-in admission controller that enforces Pod Security Standards. The three standards are privileged (no restrictions), baseline (minimum restrictions for typical workloads), and restricted (maximum restrictions for security-sensitive workloads). When you deploy to a namespace with a restricted PSA policy, your Pod must have a securityContext that complies, such as runAsNonRoot: true, readOnlyRootFilesystem: true, and allowPrivilegeEscalation: false. Understanding how to satisfy these policies is essential for real-world deployments.

Finally, remember that Pod Security Context is about the container’s view of the kernel. It does not replace network policies, RBAC, or Pod-to-Pod encryption. It is one layer in a defense-in-depth strategy. Always combine security context with other controls.

Memory Tip

Remember the acronym “RUN CAPS”: runAsUser, runAsNonRoot, readOnlyRootFilesystem, allowPrivilegeEscalation (false), capabilities (drop all, add only needed), and fsGroup (for volumes). This covers the six most important fields for a secure Pod.

Covered in These Exams

Related Glossary Terms

Frequently Asked Questions

What happens if I don't set any securityContext on my Pod?

By default, the container runs as root (UID 0) inside the container, with all capabilities that the container runtime allows. This is not recommended for production because it gives the container too much access to the host kernel.

Can I set both Pod-level and container-level securityContext?

Yes. The Pod-level securityContext applies to all containers in the Pod as a default. The container-level securityContext overrides specific settings for that container. Fields like runAsUser and capabilities can be different per container.

What is the difference between runAsUser and fsGroup?

runAsUser sets the user ID that the container process runs as. fsGroup sets the group ID that is applied to volumes mounted into the Pod, so that processes in the container can access those volumes based on group permissions.

Does readOnlyRootFilesystem affect all directories inside the container?

It makes the container's root filesystem read-only, but volumes mounted into the container (like emptyDir or PersistentVolumeClaim) remain writable. The container can write only to those mounted volumes.

What is the most restrictive securityContext for a typical web application?

Set runAsNonRoot: true, runAsUser: 1001, readOnlyRootFilesystem: true, allowPrivilegeEscalation: false, and drop all capabilities, adding only CAP_NET_BIND_SERVICE if needed. Also set fsGroup if using volumes.

How does Pod Security Context relate to Pod Security Admission?

Pod Security Admission is a cluster-level policy that enforces Pod Security Standards. Your Pod's securityContext must comply with the policy for the namespace. For example, a restricted namespace requires runAsNonRoot: true and other specific settings.

Summary

Pod Security Context is a critical Kubernetes feature that controls the security permissions of containers within a Pod. It allows you to specify which user and group the container runs as, whether it can escalate privileges, which kernel capabilities it has, and whether its root filesystem is read-only. By using security context, you apply the principle of least privilege, reducing the attack surface of your applications.

In the CKAD exam, you must be able to write and modify Pod manifests with securityContext fields, and troubleshoot common misconfigurations. In production, security context works together with Pod Security Admission, network policies, and RBAC to create a layered defense. The key to mastering this topic is practice: write YAML, test with actual Pods, and learn from the errors.

Remember that container-level settings override Pod-level settings, and that the most secure configuration always starts with dropping all capabilities and adding back only what is essential. This approach not only prepares you for certification but also for building secure, production-ready Kubernetes applications.