Introduction

Kubernetes SecurityContext is the per-Pod and per-container settings block that controls runtime privileges, and Pod Security Standards are the three namespace-level profiles that judge those settings at admission time. Together they answer one question: how much power does this workload get after it starts?

Consider an illustrative composite scenario, not a named outage. A platform team labels a production namespace for restricted enforcement on a Friday afternoon. Nothing running breaks, because admission only judges new Pods. On Monday, three routine rollouts stall at once. One Deployment is rejected for missing seccomp settings, another Pod starts and then fails because its image runs as root, and a third crashes writing cache files to a read-only filesystem. Three different failure layers, one missing mental model. This lesson builds that model in the order you will need it during an incident: fields first, profiles second, rollout third.

This is lesson 20 in Module 9 of the Kubernetes Roadmap Series. The previous lesson, Kubernetes RBAC: Roles, Bindings and Least Privilege, covered identity: who may call the API and with which verbs. This lesson covers the other half of Pod security: what a container may do to the kernel, the filesystem, and the host once it is running. RBAC decides who can create the Pod. SecurityContext decides what the Pod can do next. When you finish here, the series moves from security into observability, and you can preview that step in Module 10 of the Kubernetes roadmap.

5-minute takeaway. Most restricted-profile failures come from four missing settings: runAsNonRoot, allowPrivilegeEscalation false, capabilities drop ALL, and a seccompProfile of RuntimeDefault. Add those four, run the container as a numeric non-root user, and give writable paths explicit volumes. The table below maps each control to the failure it prevents and the first place to check when a Pod is rejected or will not start.

Control What it prevents First check when it fails
runAsNonRoot with a numeric runAsUser A compromised container acting as root inside its own filesystem and mounts Image USER value and the kubelet event text
allowPrivilegeEscalation: false Setuid binaries and capability tricks raising privilege after start Container securityContext on every container, including init containers
capabilities drop: ["ALL"] Kernel powers such as NETADMIN or SYSADMIN sitting unused in the container The admission error naming unrestricted capabilities
seccompProfile: RuntimeDefault Escape-prone system calls reaching the kernel unfiltered Pod-level seccompProfile, which covers all containers
readOnlyRootFilesystem: true Malware, webshells, or modified binaries persisting in the image layers Application write paths that need an emptyDir mount

1. Kubernetes SecurityContext vs Pod Security Standards: fields versus profiles

Kubernetes SecurityContext and Pod Security Standards solve different halves of the same problem. SecurityContext is the set of privilege fields written into a Pod spec, while Pod Security Standards are three admission profiles, privileged, baseline, and restricted, that accept or reject Pods based on those fields.

That distinction matters because the two layers fail at different times and report errors through different channels. A missing securityContext field is a manifest problem you fix in Git. A Pod Security Standards violation is an admission decision the API server makes when a controller tries to create a Pod, and the error names the profile and the exact field that broke it. Engineers who merge the two layers in their heads waste time editing images when admission is the blocker, or relabeling namespaces when the image itself runs as root.

Think of it as a driving test. SecurityContext is how the car is configured: seatbelts, speed limiter, locked doors. Pod Security Standards are the test criteria, and Pod Security Admission is the examiner standing at the namespace gate. The examiner does not tune your car for you. It reads the configuration you submitted and applies the criteria for that namespace. If the criteria say restricted, the configuration must already be restricted-shaped before the Pod arrives.

The practical consequence is that hardening work happens in two places. Workload owners set SecurityContext fields in their manifests and images. Platform owners set namespace labels that choose the profile and the enforcement mode. When those two groups coordinate, restricted namespaces feel routine. When they do not, every rollout becomes a negotiation. The rest of this lesson keeps the two jobs separate so you always know which side of the gate a failure sits on.

One more boundary is worth stating early. Pod Security Standards judge Pod spec fields only. They do not scan images, verify signatures, limit resources, or check network policy. A Pod can pass restricted and still run a vulnerable image with an over-privileged service account token. Pod security is one layer in a stack that also includes image hygiene, RBAC from the previous lesson, and secret handling covered in the Kubernetes ConfigMaps and Secrets guide. Treat restricted as a floor for runtime privileges, not as a certificate that a workload is safe.


2. Kubernetes SecurityContext placement: Pod level, container level, and overrides

A Kubernetes SecurityContext can sit at Pod level under spec.securityContext or at container level under each container entry. Pod-level settings apply to every container in the Pod, container-level settings apply to one container, and where a field exists at both levels the container value wins.

Field placement is not arbitrary, and putting a field at the wrong level is a common source of "I set it but nothing changed" reports. Identity and volume-ownership fields live naturally at Pod level: runAsUser, runAsGroup, runAsNonRoot, fsGroup, supplementalGroups, and seccompProfile. Runtime-behavior fields exist only at container level: allowPrivilegeEscalation, capabilities, readOnlyRootFilesystem, and privileged. If you write capabilities under spec.securityContext, the API accepts the object shape you gave it but no container inherits a drop list from there, because capabilities are not a Pod-level field. The Pod then fails restricted admission with an unrestricted capabilities error that looks mysterious until you check where the field actually sits.

The override rule cuts the other way as well. A Pod-level runAsNonRoot of true covers every container, but a container-level runAsUser of 0 still breaks the policy, because the effective user for that container is root. Admission and the kubelet both judge effective values per container, after Pod-level defaults and container-level overrides are combined. When you debug a violation, read the effective configuration container by container, including init containers and ephemeral containers, not just the first entry in the list.

A reliable layout keeps shared identity at Pod level and behavior at container level. Set runAsNonRoot, runAsUser, runAsGroup, fsGroup, and seccompProfile once at Pod level so sidecars and init containers inherit the same baseline. Then set allowPrivilegeEscalation, capabilities, and readOnlyRootFilesystem on every container explicitly, because those fields have no Pod-level home. That split is exactly what the restricted-ready example in section 10 uses, and it is the layout reviewers should expect in a pull request.

There is a subtlety with seccompProfile worth knowing. It can be set at either level, and the Pod-level value applies to all containers unless a container overrides it. Setting it once at Pod level is the shortest path to passing restricted, and it removes the risk that a newly added sidecar forgets the field. The same logic argues for Pod-level runAsNonRoot: one declaration, whole-Pod coverage, no silent gaps when a second container joins the spec.


3. Kubernetes SecurityContext identity: runAsNonRoot, runAsUser, and fsGroup

In a Kubernetes SecurityContext, runAsNonRoot tells the kubelet to refuse any container that would start as UID 0, runAsUser and runAsGroup choose the numeric identity, and fsGroup sets the group ownership applied to mounted volumes so non-root processes can read and write them.

The most misunderstood point in this area is that runAsNonRoot does not change the user. It is a check, not an assignment. The kubelet resolves the effective user from runAsUser if set, otherwise from the image USER value, and fails container creation when that user is root or cannot be verified as non-root. The event text is precise: "container has runAsNonRoot and image will run as root" means the image defaults to UID 0, while a non-numeric image user produces a different message because the kubelet does not read /etc/passwd inside the image to resolve names. A named user without a numeric mapping is unverifiable, and unverifiable fails the check.

The durable fix lives in the image. Build the image with a fixed numeric user, for example USER 10001, and every environment inherits the safe default. The manifest fix, setting runAsUser in the Pod spec, works as an override and is the right short-term move for vendor images you cannot rebuild today. What you should not do is delete runAsNonRoot to make the error go away. That trades a loud startup failure for a silent privilege risk, and restricted admission will reject the Pod anyway.

fsGroup solves the problem that appears right after you stop running as root: volume permissions. When a Pod mounts a volume, Kubernetes can change the group ownership of the volume contents to the fsGroup value and add that group to the container process, so a non-root user can write to a persistent volume that was provisioned root-owned. supplementalGroups adds extra group IDs the process carries, which helps when a volume or device is group-readable by a specific GID. Neither field grants root-like power; they align filesystem ownership with the identity you chose.

Two failure shapes dominate this section in practice. The first is the kubelet refusing to start the container, which shows up as CreateContainerConfigError with the runAsNonRoot message in events. The second is the container starting and then failing with permission denied on a volume path, which points at fsGroup or at image filesystem ownership rather than admission. Section 12 separates those two shapes, because they have different owners: the first is an image or manifest identity fix, the second is a volume ownership fix.


4. Kubernetes SecurityContext escalation controls: allowPrivilegeEscalation and privileged

Within a Kubernetes SecurityContext, allowPrivilegeEscalation false sets the kernel nonewprivs flag so no process can gain more privilege than it started with, while privileged true removes most container isolation and should be treated as host access, not as a debugging shortcut.

allowPrivilegeEscalation is the field that closes the gap runAsNonRoot leaves open. A container can start as UID 10001 and still contain a setuid-root binary. Without nonewprivs, executing that binary raises the process to root privileges inside the container, and a kernel flaw reachable from there becomes far more valuable to an attacker. With allowPrivilegeEscalation set to false, setuid and file-capability elevation are ignored by the kernel: the program runs with the privileges of whoever started it. The restricted profile requires this field to be false explicitly. Leaving it unset fails admission, because the default is not treated as false for policy purposes.

There is an interaction worth remembering. When a container runs as root or holds CAPSYSADMIN, Kubernetes treats privilege escalation as effectively allowed regardless of the flag, because those starting conditions already carry the power the flag would block. This is another reason the restricted profile bundles the requirements together: non-root identity, no escalation, dropped capabilities, and seccomp only deliver their full value as a set. Fixing one field while leaving a container privileged changes the error message, not the risk.

privileged: true deserves blunt language. A privileged container receives all Linux capabilities, access to host devices, and relief from the cgroup device restrictions that normally contain it. In practice it can mount host filesystems and escape to the node. Baseline and restricted both forbid it. Legitimate uses exist at the platform layer: certain CNI and CSI node components, some node agents, and a small set of infrastructure DaemonSets. Those belong in clearly privileged system namespaces with tight RBAC around who can deploy there. An application team asking for privileged to fix a permission error is asking for the wrong tool; the fix is almost always a specific capability, an fsGroup value, or a volume mount change.

When a workload genuinely needs one narrow power, grant that power narrowly. Binding a low port, adjusting file ownership during startup, or sending raw network packets each map to a single capability covered in the next section. Reaching for privileged because it makes every error disappear is how a minor permission bug becomes a node-compromise path. Reviewers should treat any privileged: true outside platform namespaces as a blocking finding.


5. Kubernetes SecurityContext capabilities: drop ALL, then add back with intent

Linux capabilities in a Kubernetes SecurityContext split root power into named kernel permissions, and the restricted pattern is to drop ALL capabilities first, then add back only the specific capability a container demonstrably needs, which under restricted means at most NETBINDSERVICE.

Capabilities are real kernel authority, not metadata. CAPNETADMIN can rewrite networking rules inside the container network namespace. CAPSYSADMIN covers a wide range of mount and namespace operations and is close to root in effect. CAPDACOVERRIDE ignores file permission checks. CAPSYSPTRACE can inspect other processes. A default container runtime grants a subset of capabilities to every container, including some most applications never use. Dropping ALL removes that inherited set so the container holds only what you deliberately grant.

The restricted profile is strict here: capabilities must drop ALL, and the only capability that may be added back is NETBINDSERVICE, which permits binding to ports below 1024. Even that add-back is often unnecessary. Many runtimes and node configurations already allow non-root processes to bind low ports, and the cleaner application-level fix is to listen on a high port such as 8080 and let the Service map port 80 to it. Add NETBINDSERVICE when a binary hardcodes a low port and you cannot change it yet, and record why in the manifest review.

Baseline is looser but not open. It forbids adding capabilities beyond a default allowed set, so requests for powers such as SYSADMIN or NETRAW fail baseline admission too. That gives platform teams a useful middle step: enforce baseline to block the dangerous adds immediately, while teams work through the identity and seccomp changes restricted requires. Section 11 uses exactly that sequence for migration.

In practice, capability debugging is fast when you follow one rule: start from drop ALL with no adds, run the workload, and read the failure. A permission error on binding a low port points at NETBINDSERVICE or a port change. An operation-not-permitted error on a network operation suggests the workload is doing something a normal application should not do, and the answer is usually to move that function to a platform component rather than widen the application container. Capabilities should be granted from evidence, one at a time, with the reason written next to the YAML.


6. Kubernetes SecurityContext filesystem hardening: readOnlyRootFilesystem and scratch volumes

Setting readOnlyRootFilesystem true in a Kubernetes SecurityContext mounts the container image filesystem read-only, so an attacker cannot modify binaries or drop persistence files, while explicit volume mounts such as emptyDir still provide the writable paths the application truly needs during normal operation and after a compromise.

Accuracy matters here: the restricted Pod Security Standard does not require readOnlyRootFilesystem. A Pod can pass restricted with a writable root filesystem. Treat the field as hardening beyond the profile floor, and a very worthwhile one. It converts a whole class of post-compromise moves, replacing a binary, editing application code on disk, writing a webshell into a served directory, into immediate failures. It also catches accidental writes during development, which makes container behavior more predictable across environments.

The cost is real and shows up at startup. Applications write temp files, caches, PID files, and sometimes generated configuration into paths inside the image. With a read-only root filesystem those writes fail, and the application may crash-loop with errors that look unrelated to security. The fix is to inventory the write paths and mount writable volumes exactly there. An emptyDir mounted at /tmp covers temp files. A second emptyDir can cover a cache directory. Configuration that the application rewrites at runtime usually belongs in a ConfigMap rendered correctly at deploy time, or in an init container that writes into a shared emptyDir the main container mounts.

Pair the filesystem change with identity. A writable emptyDir is owned according to the Pod fsGroup and the process group, so set fsGroup deliberately and confirm the non-root user can write where the mount lands. Testing order matters too: enable readOnlyRootFilesystem in a staging namespace with the same mounts production will use, watch the logs for read-only file system errors, and add mounts path by path. Each added mount is a small, reviewable decision. That is the correct granularity for filesystem write access, and it beats discovering missing mounts during a production rollout.

One caution keeps this honest. Read-only root filesystem does not stop an attacker from writing to the writable volumes you granted, and it does not protect data the application legitimately writes to a persistent volume. It narrows the blast radius and removes easy persistence in image layers. Combined with dropped capabilities and no privilege escalation, it makes a compromised container a poor foothold. Alone, it is a speed bump. The fields work as a set, which is the recurring theme of this lesson.


7. Kubernetes SecurityContext syscall filtering: seccomp RuntimeDefault and Localhost

The seccompProfile field in a Kubernetes SecurityContext selects a kernel syscall filter for the container, and the restricted profile requires type RuntimeDefault or Localhost, because an unfiltered container can reach escape-prone system calls that normal applications never need during ordinary production workloads.

Seccomp works at the system call boundary. Every time a process asks the kernel to do something, open a file, create a socket, mount a filesystem, load a module, the filter decides whether that call proceeds. The RuntimeDefault profile shipped by container runtimes such as containerd and CRI-O allows the few hundred calls ordinary processes use and blocks the dangerous remainder, including calls involved in mount manipulation, kernel module loading, and several historical escape primitives. For most applications RuntimeDefault is invisible: nothing breaks, and a layer of kernel attack surface closes.

The restricted profile requires the field to be set explicitly to RuntimeDefault or Localhost. An absent seccompProfile fails restricted admission, and Unconfined, which disables filtering, fails baseline as well. Localhost profiles are custom filters loaded from files on the node, and they suit the rare workload that needs a tighter or slightly different call set than the runtime default. Running a Localhost profile is an operational commitment: the profile file must exist on every node the Pod can land on, and it must be maintained as the application changes. Start with RuntimeDefault unless you have evidence you need more.

Set seccompProfile at Pod level. One declaration covers every container and init container, and a sidecar added later inherits the filter instead of silently running unfiltered. Container-level overrides remain available for the exceptional container that needs a different profile, but the default posture should be uniform across the Pod.

Seccomp sits alongside two related mechanisms that platform teams sometimes configure in the same review. AppArmor profiles constrain file and capability access through a Linux security module, and SELinux labels enforce mandatory access control on files and processes. Pod Security Standards restrict unsafe values for both at baseline level, but neither replaces seccomp, and neither is required explicitly by restricted. Keep the layering clear: seccomp filters system calls, capabilities grant specific kernel powers, identity decides whose authority the process carries, and the filesystem fields decide what can be written. Four different doors, four different locks.


8. Pod Security Standards levels: privileged, baseline, and restricted compared

The Pod Security Standards define three cumulative profiles: privileged imposes no restrictions, baseline blocks known privilege-escalation paths while allowing the default Pod configuration, and restricted adds non-root identity, dropped capabilities, no privilege escalation, and a required seccomp profile for every namespace in the cluster.

Cumulative means each stricter profile includes everything the looser one forbids. A Pod that passes restricted passes baseline automatically. That property makes staged migration natural, because tightening a namespace never asks teams to undo a baseline fix; it asks for additional fields on top of work already done.

Privileged is the absence of policy. It allows privileged containers, host namespaces, hostPath volumes, any capability, and root users. Its legitimate home is platform infrastructure: CNI agents, CSI node plugins, and node-level components that must touch the host to function. Those namespaces should be few, named clearly, and guarded by RBAC so only platform automation can deploy into them. Privileged as a default for application namespaces means the cluster has no Pod-level guardrail at all, which is the state this lesson exists to end.

Baseline targets ease of adoption. It forbids privileged containers, hostNetwork, hostPID, and hostIPC, hostPath volumes, host ports, capabilities beyond a default allowed set, an Unconfined seccomp profile, non-default procMount, unsafe sysctls, and custom SELinux or AppArmor values outside the safe set. It still allows running as root and a writable root filesystem, which is why most existing applications pass baseline with small changes. Baseline is the right first enforcement step for a cluster that has never labeled its namespaces.

Restricted is the hardening target for application namespaces. On top of baseline it requires allowPrivilegeEscalation false, runAsNonRoot true with a non-zero user, capabilities dropping ALL with only NETBINDSERVICE addable, a seccompProfile of RuntimeDefault or Localhost, and an allowlist of volume types: configMap, secret, emptyDir, projected, downwardAPI, persistentVolumeClaim, ephemeral, and csi. Notice what restricted still does not require: readOnlyRootFilesystem, resource limits, image scanning, or network policy. It is a strong floor for runtime privilege, and your platform standards should layer the rest deliberately.

Control area Privileged Baseline Restricted
Privileged containers Allowed Forbidden Forbidden
Host namespaces and hostPath Allowed Forbidden Forbidden
Running as root Allowed Allowed Forbidden, runAsNonRoot required
Capabilities Unrestricted Default set only Drop ALL, NETBINDSERVICE only add-back
Privilege escalation Allowed Partially constrained allowPrivilegeEscalation false required
Seccomp Unrestricted Unconfined forbidden RuntimeDefault or Localhost required
Volume types Unrestricted hostPath forbidden Allowlist only
Typical namespace kube-system style platform namespaces Legacy application namespaces in transition Production application namespaces

Choosing a level per namespace is a platform decision, not a per-team preference. Production application namespaces should target restricted. Namespaces running vendor software that cannot yet run non-root sit at baseline with a dated plan to close the gap. Platform namespaces stay privileged with deployment access restricted. Writing that mapping down, namespace by namespace, turns Pod security from a slogan into an auditable state. The Kubernetes best practices guide covers how this mapping fits into a wider production checklist.


9. Pod Security Admission: namespace labels for enforce, audit, and warn

Pod Security Admission enforces the Pod Security Standards through namespace labels in the form pod-security.kubernetes.io/enforce, audit, and warn, where enforce rejects violating Pods, audit records violations in the API audit log, and warn returns warnings to the client while admitting the Pod.

Pod Security Admission is a built-in admission controller, stable since Kubernetes 1.25, and it replaced PodSecurityPolicy, which was removed in that release. There is no policy object to write and no webhook to install. The entire configuration surface is labels on the namespace, plus optional version pins. That simplicity is deliberate: three fixed profiles, three modes, no custom rules, no mutation. If you need per-workload exceptions or custom checks, you layer a policy engine beside Pod Security Admission rather than bending it into shapes it does not support.

Each mode takes a profile value independently, which is what makes gradual rollout possible. A namespace can enforce baseline today while warning and auditing against restricted, so teams see restricted violations in their deploy output weeks before those violations start blocking releases. The warn mode surfaces messages to kubectl and to controllers through warning headers. The audit mode annotates API audit events, which gives platform teams a queryable record of which workloads would fail a stricter profile. Used together, the three modes turn enforcement into a measured process instead of a flag day.

Version labels pin which revision of a profile applies. A label such as pod-security.kubernetes.io/enforce-version set to a specific minor version keeps the rules fixed across a cluster upgrade until you deliberately move it, while latest follows the cluster and can tighten rules under you during an upgrade. A common pattern pins enforce to the current cluster version and leaves warn and audit on latest, so the next tightening is visible in warnings before it becomes a rejection.

Two behavioral facts prevent most rollout surprises. First, admission judges Pods at creation and update time only. Tightening a namespace label does not evict or restart running Pods; the new rules apply to the next Pod a controller creates. That makes label changes safe to apply to live namespaces, and it also means a namespace can look compliant while old Pods still run with old privileges until they roll. Second, admission also evaluates workload resources such as Deployments in audit and warn modes, so violations surface when the Deployment is applied, not only later when its Pods fail. Read the warning on apply; it is the cheapest feedback loop you get.

bash
kubectl label namespace shop \
  pod-security.kubernetes.io/enforce=baseline \
  pod-security.kubernetes.io/warn=restricted \
  pod-security.kubernetes.io/audit=restricted

That single command is the migration starting point section 11 builds on: baseline blocks the known escalation paths now, while warn and audit collect the restricted gap list without breaking deploys.


10. Kubernetes SecurityContext example: a restricted-ready Deployment

A restricted-ready Kubernetes SecurityContext sets identity and seccomp at Pod level, then sets allowPrivilegeEscalation false, capabilities drop ALL, and readOnlyRootFilesystem true on every container, with writable emptyDir mounts covering every path the application writes to during normal day-to-day runtime operation in production.

The Deployment below is the reference shape reviewers should expect. It runs as UID 10001, carries a matching group and fsGroup, filters syscalls with RuntimeDefault, drops every capability, blocks privilege escalation, keeps the image filesystem read-only, and mounts scratch space at /tmp. It also listens on port 8080, so no NETBINDSERVICE add-back is needed.

yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: shop-api
  namespace: shop
spec:
  replicas: 3
  selector:
    matchLabels:
      app: shop-api
  template:
    metadata:
      labels:
        app: shop-api
    spec:
      securityContext:
        runAsNonRoot: true
        runAsUser: 10001
        runAsGroup: 10001
        fsGroup: 10001
        seccompProfile:
          type: RuntimeDefault
      containers:
        - name: api
          image: registry.example.com/shop-api:1.4.2
          ports:
            - containerPort: 8080
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities:
              drop: ["ALL"]
          volumeMounts:
            - name: tmp
              mountPath: /tmp
      volumes:
        - name: tmp
          emptyDir: {}

Walk the fields against the restricted checklist. runAsNonRoot is true at Pod level and runAsUser is a non-zero numeric ID, so identity passes even if the image default user is root, though building the image with USER 10001 remains the durable fix. seccompProfile is RuntimeDefault at Pod level, covering the container. allowPrivilegeEscalation is false and capabilities drop ALL with no adds, satisfying the escalation and capability rules. The only volume type is emptyDir, which is on the restricted allowlist. readOnlyRootFilesystem goes beyond the profile and is included because it costs one mount and removes a persistence path.

Now check the failure modes this shape still leaves open, because a template is not a guarantee. If the application writes a cache under its working directory instead of /tmp, the container will fail until that path gets a mount. If a sidecar is added later without its own container securityContext, admission will reject the Pod for that container even though the main container is correct; every container, including init containers, is judged. If the image entrypoint tries to chown files or start as root and drop privileges itself, runAsNonRoot will block it, and the entrypoint needs rework rather than a policy exception.

Verify the shape before enforcing it on a namespace. Apply the Deployment to a test namespace labeled warn and audit restricted, confirm no warnings appear, then check the running Pod identity from inside.

bash
kubectl -n shop exec deploy/shop-api -- id
kubectl -n shop get pod -l app=shop-api \
  -o jsonpath='{.items[0].spec.containers[0].securityContext}'

The id output should show uid=10001, and the securityContext output should echo the fields you set. Those two checks confirm the manifest survived admission and the kubelet applied it, which are separate events worth verifying separately.


11. Pod Security Standards migration: audit first, enforce in waves

A safe Pod Security Standards migration labels namespaces warn and audit at the target profile first, fixes the violations those modes surface, and only then raises enforce, namespace by namespace, so no running workload is surprised by a rejection it never saw coming.

Start with discovery, not labels that block. A server-side dry run of the enforce label reports which existing Pods would violate a profile without changing anything, and it works across namespaces in one command.

bash
kubectl label --dry-run=server --overwrite ns --all \
  pod-security.kubernetes.io/enforce=baseline

The warnings list the violating Pods and the fields at fault. That output is your migration backlog, and it is more reliable than any spreadsheet assembled from memory. Group the violations by field: missing seccompProfile, missing runAsNonRoot, unrestricted capabilities, privileged containers, hostPath volumes. Field-level grouping turns hundreds of Pod warnings into a handful of manifest fixes, because most violations repeat across every Deployment that shares a template.

Wave one enforces baseline everywhere it passes, and labels the rest warn and audit baseline with owners assigned. Baseline blocks the escalation paths that matter most, privileged containers and host access, while asking little of application teams. Wave two sets warn and audit to restricted on application namespaces while enforce stays at baseline. Teams fix identity, capabilities, and seccomp in their normal release cadence, guided by warnings on every apply. Wave three raises enforce to restricted per namespace as its warning count reaches zero. Platform namespaces remain privileged throughout, with deployment rights held by platform automation.

Running Pods need one explicit decision. Because admission only judges new Pods, a namespace can enforce restricted while pre-existing Pods keep running with root users and full capabilities until they happen to roll. For most namespaces, natural rollouts close that gap within days. For long-lived Pods, schedule a controlled rollout after enforcement so the running state matches the admitted state. Compliance reporting should count running Pod specs, not just namespace labels, or the dashboard will claim a posture the nodes do not actually have.

Exceptions need a generic, boring mechanism. Pod Security Admission supports cluster-level exemptions for specific namespaces, usernames, and RuntimeClasses, configured by cluster administrators rather than per-Pod annotations. Use exemptions for platform components that structurally cannot comply, keep the list short, and review it on a schedule. For application workloads that need secret material delivered without broad API access, fix the delivery path instead of widening Pod privileges; the External Secrets Operator guide covers that pattern. An exception process that requires a written reason and an expiry date keeps restricted meaningful; an exception process that is a chat message does not.


12. Kubernetes SecurityContext and Pod Security Standards troubleshooting matrix

Most Pod Security Standards failures announce their layer in the error text: admission rejections name the profile and field, kubelet refusals name the identity problem, and application crashes after admission point at filesystem or capability gaps the profile never judged.

Read the error before changing anything. An admission rejection happens before the Pod exists, so kubectl get pod shows nothing and the Deployment reports FailedCreate events with the violation text. A kubelet refusal means the Pod was admitted but the container would not start, so the Pod exists in a waiting state with the reason in events. An application crash means admission and startup both succeeded and the process failed on its own terms, usually a write to a read-only path or a permission error on a volume. Those three shapes have three different fix locations: namespace labels and manifest fields, image identity, and application mounts. The matrix below maps the messages you will actually see.

Symptom or error text Layer Likely cause Fix
violates PodSecurity "restricted": allowPrivilegeEscalation != false Admission Container missing allowPrivilegeEscalation false Set it on every container and init container
unrestricted capabilities, must drop ["ALL"] Admission Capabilities field missing or placed at Pod level Set capabilities drop ALL at container level
runAsNonRoot != true Admission Neither Pod nor container sets runAsNonRoot Set runAsNonRoot true at Pod level
seccompProfile must be RuntimeDefault or Localhost Admission seccompProfile absent or Unconfined Set Pod-level seccompProfile type RuntimeDefault
container has runAsNonRoot and image will run as root Kubelet Image USER is 0 or unset and no runAsUser override Rebuild image with numeric USER, or set runAsUser
image has non-numeric user, cannot verify Kubelet Image USER is a name the kubelet cannot resolve Use a numeric USER in the image or set runAsUser
CreateContainerConfigError after admission Kubelet Identity check or missing config object Read events; separate identity failures from missing Secret or ConfigMap
Read-only file system errors in app logs Application readOnlyRootFilesystem with unmounted write paths Add emptyDir mounts for /tmp and cache paths
Permission denied on a mounted volume Application Volume ownership does not match the non-root user Set fsGroup and confirm group write access
Pod admitted in warn mode but rollout stalls later Admission Enforce raised before warnings were cleared Return to warn and audit, fix warnings, then enforce

Two habits prevent most rows in that matrix. First, treat warn-mode output as a failing test in your pipeline: if an apply prints Pod Security warnings, the change is not done, even though it deployed. Second, verify identity from inside the running container with id, not from the manifest alone, because the manifest shows intent and the process shows truth. The runtime mechanics behind these checks, namespaces, cgroups, and the container runtime boundary, are covered in Kubernetes container internals: namespaces, cgroups and runc.

Hardening checklist for every application workload:

  • [ ] Pod-level runAsNonRoot true with a numeric non-zero runAsUser and runAsGroup
  • [ ] Image built with a numeric USER matching the manifest identity
  • [ ] Pod-level seccompProfile type RuntimeDefault
  • [ ] Every container and init container sets allowPrivilegeEscalation false
  • [ ] Every container drops ALL capabilities; any add-back is NETBINDSERVICE with a written reason
  • [ ] No privileged containers, host namespaces, host ports, or hostPath volumes
  • [ ] readOnlyRootFilesystem true, with emptyDir mounts for each writable path
  • [ ] fsGroup set so the non-root user can write to mounted volumes
  • [ ] Volume types limited to the restricted allowlist
  • [ ] Namespace labels enforce the target profile, with warn and audit watching the next stricter level
  • [ ] Pipeline treats Pod Security warnings as failures
  • [ ] Running Pods rolled after enforcement so live state matches admitted state

That checklist is the lesson in one screen. SecurityContext supplies the fields, Pod Security Standards supply the criteria, and Pod Security Admission supplies the enforcement. RBAC from the previous lesson controls who may deploy; this lesson controls what deployed containers may do. Together they close the two halves of Pod security, and the next module turns to watching the result with metrics, logs, and traces.

Frequently Asked Questions

What is the difference between Kubernetes SecurityContext and Pod Security Standards?

Kubernetes SecurityContext is the set of privilege fields in a Pod spec, such as runAsNonRoot, capabilities, and seccompProfile. Pod Security Standards are three admission profiles, privileged, baseline, and restricted, that judge those fields when a Pod is created. SecurityContext is the configuration; the standards are the criteria applied to it.

How do I set a Kubernetes SecurityContext to pass the restricted Pod Security Standard?

Set runAsNonRoot true with a numeric non-zero user, set allowPrivilegeEscalation false on every container, drop ALL capabilities with at most NETBINDSERVICE added back, set seccompProfile to RuntimeDefault, and use only allowlisted volume types. The Deployment in section 10 is a working reference shape.

Why does runAsNonRoot in a Kubernetes SecurityContext fail with "image will run as root"?

runAsNonRoot is a kubelet check, not an assignment. If the image USER is root or unset and the manifest sets no runAsUser, the kubelet refuses to start the container. Rebuild the image with a numeric non-root USER, or set runAsUser in the Pod spec as an override.

Which capabilities can I add back in a Kubernetes SecurityContext under the restricted profile?

Only NETBINDSERVICE, and only after dropping ALL. Even that add-back is often unnecessary: listening on a high port such as 8080 and mapping it through a Service removes the need for low-port binding entirely. Any other capability requirement means the workload cannot run under restricted as designed.

Does the restricted profile require readOnlyRootFilesystem in a Kubernetes SecurityContext?

No. The restricted profile does not require readOnlyRootFilesystem, so a Pod can pass restricted with a writable root filesystem. Setting it true is still strong practice: it blocks binary tampering and persistence in image layers, at the cost of mounting emptyDir volumes for paths the application writes to.

How do enforce, audit, and warn modes differ in Pod Security Admission?

Enforce rejects Pods that violate the profile. Audit admits the Pod and records the violation as an annotation on the API audit event. Warn admits the Pod and returns a warning to the client, which kubectl prints. Each mode takes its own profile value, so a namespace can enforce baseline while warning against restricted.

What happens to running Pods when I tighten Pod Security Standards labels?

Nothing immediate. Pod Security Admission judges Pods at creation and update time, so running Pods keep their existing privileges until they are recreated. Plan a controlled rollout after raising enforcement so the running state matches the new profile, and audit running Pod specs rather than trusting labels alone.

⚡ KUBERNETES SCENARIO INTERVIEW PREP

Preparing for Senior Platform & SRE Interviews

Practice real-world cluster triage, RBAC debugging, and pod scheduling scenarios in our Kubernetes scenario interview questions hub.

Explore Interview Scenarios →