Overview and What You Will Learn
Pod Security Standards (PSS) are three predefined security profiles, Privileged, Baseline, and Restricted, and the built-in Pod Security Admission (PSA) controller enforces them per namespace using labels. In this lab, you will roll out the Restricted profile safely, watch a non-compliant pod get rejected, harden a real workload with securityContext, and audit existing namespaces before turning enforcement on.
Why This Matters in Production
A container running as root with no restrictions is one kernel exploit away from compromising the whole node. At a payments company like Razorpay, a compromised container that can escalate to root and read the host filesystem exposes every other workload on that node, including the ones handling card data. Pod Security Standards and securityContext are the built-in Kubernetes controls that close that path.
Core Principles
Pod Security Admission checks every Pod at creation time against the profile named in its namespace's labels. Each label picks a mode: enforce rejects the pod, warn prints a warning to the user, and audit records the violation in the audit log. PSA replaced PodSecurityPolicy, which was removed in Kubernetes 1.25, and it is on by default in current EKS, GKE, and AKS clusters.
reads namespace labels] B --> C{Violates
the profile?} C -->|Compliant| D([Pod admitted]) C -->|Enforce| E([Pod rejected]) C -->|Warn or audit| F([Admitted, warning
or audit entry]) classDef step fill:#326CE5,color:#FFFFFF classDef decision fill:#F59E0B,color:#111827 classDef good fill:#10B981,color:#FFFFFF classDef bad fill:#EF4444,color:#FFFFFF classDef note fill:#F97316,color:#FFFFFF class A,B step class C decision class D good class E bad class F note
| Profile | Intended for | What it blocks |
|---|---|---|
| Privileged | System and infrastructure workloads | Nothing |
| Baseline | Most ordinary applications | Known escalations such as privileged containers, hostNetwork, and hostPath |
| Restricted | Security-sensitive applications | Everything in Baseline, plus root users, privilege escalation, extra capabilities, and a missing seccomp profile |
The Restricted profile requires four securityContext settings, and a fifth is strongly recommended:
runAsNonRoot: truestops the container from running as UID 0.allowPrivilegeEscalation: falsestops setuid binaries from gaining more privileges than the parent process.capabilities.drop: ["ALL"]removes every Linux capability, such asNET_ADMINandSYS_ADMIN.seccompProfile.type: RuntimeDefaultapplies the container runtime's syscall filter.readOnlyRootFilesystem: truestops a compromised process from writing malware to disk.
RememberThe Restricted profile does not require
readOnlyRootFilesystem. It is extra hardening that you add yourself, together withemptyDirvolumes for paths the app must write to.
Detailed Step-by-Step Practical Lab
How to Start a Namespace in Warn and Audit Mode
Never begin with enforce on a live namespace. Create a lab namespace that only warns and audits, so nothing is blocked while you learn what would break.
kubectl create namespace pss-lab kubectl label namespace pss-lab \ pod-security.kubernetes.io/warn=restricted \ pod-security.kubernetes.io/audit=restrictedHow to See a PSS Violation Warning Without Blocking
Run a plain nginx pod. The official nginx image runs as root, so the pod is created but kubectl prints exactly what would be rejected.
kubectl run root-pod --image=nginx:1.27 -n pss-labWarning: would violate PodSecurity "restricted:latest": allowPrivilegeEscalation != false (container "root-pod" must set securityContext.allowPrivilegeEscalation=false), unrestricted capabilities (container "root-pod" must set securityContext.capabilities.drop=["ALL"]), runAsNonRoot != true (pod or container "root-pod" must set securityContext.runAsNonRoot=true), seccompProfile (pod or container "root-pod" must set securityContext.seccompProfile.type to "RuntimeDefault" or "Localhost")pod/root-pod createdHow to Audit Existing Namespaces Before Enforcing
A server-side dry run of the label shows which pods in every namespace would violate the profile, without changing anything.
kubectl label --dry-run=server --overwrite namespace --all \ pod-security.kubernetes.io/enforce=restrictedSecurityAlways include
--dry-run=serveron this command. Without it, you applyenforce=restrictedto every namespace, includingkube-system, and can stop system pods from being recreated. Leave infrastructure namespaces on Privileged.
How to Enforce the Restricted Profile
Switch the lab namespace to enforce. Existing pods keep running, because enforcement only checks new and updated pods, but the next non-compliant pod is rejected.
kubectl label --overwrite namespace pss-lab \ pod-security.kubernetes.io/enforce=restricted \ pod-security.kubernetes.io/enforce-version=latest kubectl run root-pod-2 --image=nginx:1.27 -n pss-lab # violates PodSecurity "restricted:latest": ...TipIn production, pin the version, for example
enforce-version=v1.34, instead oflatest. A cluster upgrade can then never tighten the rules underneath you without a deliberate label change.
How to Write a Restricted-Compliant Deployment
This Deployment uses nginxinc/nginx-unprivileged, an image built to run as a non-root user on port 8080. It mounts an emptyDir at /tmp because the root filesystem is read-only.
# payments-api.yamlapiVersion: apps/v1kind: Deploymentmetadata: name: payments-api namespace: pss-labspec: replicas: 2 selector: matchLabels: app: payments-api template: metadata: labels: app: payments-api spec: # Pod-level settings apply to every container in the pod securityContext: runAsNonRoot: true # Reject the container if it would run as UID 0 runAsUser: 101 # The unprivileged nginx user runAsGroup: 101 fsGroup: 101 # Group ownership for mounted volumes seccompProfile: type: RuntimeDefault # Apply the runtime's default syscall filter containers: - name: payments-api image: nginxinc/nginx-unprivileged:1.27-alpine ports: - containerPort: 8080 # Non-root cannot bind to ports below 1024 by default # Container-level settings apply to this container only securityContext: allowPrivilegeEscalation: false # setuid binaries cannot gain root readOnlyRootFilesystem: true # Nothing can be written to the image capabilities: drop: - ALL # Remove every Linux capability volumeMounts: - name: tmp mountPath: /tmp # Writable scratch space for nginx volumes: - name: tmp emptyDir: {}kubectl apply -f payments-api.yamlkubectl rollout status deployment/payments-api -n pss-labHow to Verify the Hardening Inside the Running Pod
Check that the process is not root and that the filesystem really is read-only.
POD=$(kubectl get pod -n pss-lab -l app=payments-api -o name | head -n 1) kubectl exec -n pss-lab $POD -- id# Expected: uid=101 gid=101 kubectl exec -n pss-lab $POD -- touch /app-test# Expected: touch: /app-test: Read-only file system kubectl exec -n pss-lab $POD -- touch /tmp/ok && echo "/tmp is writable"How Deployments Behave When Their Pods Are Rejected
PSA checks pods, not Deployments. If you apply a Deployment whose template violates the profile, the Deployment itself is accepted, but its ReplicaSet cannot create pods. Warn mode prints the problem when you apply, and the failure is recorded as events.
kubectl get events -n pss-lab --field-selector reason=FailedCreatekubectl describe replicaset -n pss-labHow to Find Containers That May Run as Root
This query lists containers that do not set runAsNonRoot: true at the container or pod level. It can include containers whose image already uses a non-root user, so treat it as a list to review.
kubectl get pods -A -o json | jq -r ' .items[] | . as $p | .spec.containers[] | select((.securityContext.runAsNonRoot // $p.spec.securityContext.runAsNonRoot // false) != true) | "\($p.metadata.namespace)/\($p.metadata.name) container=\(.name)"'How to Clean Up
kubectl delete namespace pss-labProduction Best Practices & Common Pitfalls
Common MistakeSetting
runAsNonRoot: trueon an image that runs as root, such as the official nginx image. The pod is admitted, then fails at container start withCreateContainerConfigErrorand a message that the image will run as root. Test withdocker run --rm --user 1000 <image>first, or switch to an unprivileged variant of the image.
TipTo score manifests against security best practices before they reach the cluster, run
kube-score score payments-api.yamlin CI. It flags missingsecurityContextsettings and other risky defaults.
- Roll out in three stages. Start with
warnandaudit, fix the violations the warnings show, then switch toenforce. Going straight toenforcecan block critical pods on their next restart. - Mount
emptyDirvolumes for writable paths. A read-only root filesystem is a small configuration cost that stops attackers from persisting files after a break-in. - Prefer unprivileged ports. Listen on 8080 instead of 80 so you do not need to add back the
NET_BIND_SERVICEcapability. - Keep infrastructure namespaces on Privileged. CNI plugins, CSI drivers, and monitoring agents often need host access, so exempt them deliberately instead of weakening the profile for everyone.
- Use cluster-wide defaults and exemptions. An AdmissionConfiguration on the API server can set a default profile and exempt specific users or namespaces, which is how platform teams apply a baseline to every new namespace.
Quick Reference & Troubleshooting Commands
| Command | Description |
|---|---|
kubectl label namespace NS pod-security.kubernetes.io/enforce=restricted |
Apply the Restricted profile |
kubectl label --dry-run=server --overwrite namespace --all pod-security.kubernetes.io/enforce=restricted |
Audit every namespace without changing it |
kubectl get namespace NS --show-labels |
Check the PSS labels on a namespace |
kubectl get events -n NS --field-selector reason=FailedCreate |
Find pods a ReplicaSet could not create |
kubectl apply --dry-run=server -f pod.yaml |
Test a manifest against the namespace profile |