Skip to main content

Implementing Kubernetes Pod Security Standards

Enforce Kubernetes Pod Security Standards with namespace labels, harden pods with securityContext, and audit existing workloads before enforcing.

52 Terms

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.

flowchart TD A([Pod create request]) --> B[Pod Security Admission
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:

  1. runAsNonRoot: true stops the container from running as UID 0.
  2. allowPrivilegeEscalation: false stops setuid binaries from gaining more privileges than the parent process.
  3. capabilities.drop: ["ALL"] removes every Linux capability, such as NET_ADMIN and SYS_ADMIN.
  4. seccompProfile.type: RuntimeDefault applies the container runtime's syscall filter.
  5. readOnlyRootFilesystem: true stops a compromised process from writing malware to disk.
Remember

The Restricted profile does not require readOnlyRootFilesystem. It is extra hardening that you add yourself, together with emptyDir volumes 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.

Bash
kubectl create namespace pss-lab
kubectl label namespace pss-lab \
pod-security.kubernetes.io/warn=restricted \
pod-security.kubernetes.io/audit=restricted
How 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.

Bash
kubectl run root-pod --image=nginx:1.27 -n pss-lab
TEXT
Warning: 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 created
How 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.

Bash
kubectl label --dry-run=server --overwrite namespace --all \
pod-security.kubernetes.io/enforce=restricted
Security

Always include --dry-run=server on this command. Without it, you apply enforce=restricted to every namespace, including kube-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.

Bash
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": ...
Tip

In production, pin the version, for example enforce-version=v1.34, instead of latest. 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.

YAML
# payments-api.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: payments-api
namespace: pss-lab
spec:
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: {}
Bash
kubectl apply -f payments-api.yaml
kubectl rollout status deployment/payments-api -n pss-lab
How to Verify the Hardening Inside the Running Pod

Check that the process is not root and that the filesystem really is read-only.

Bash
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.

Bash
kubectl get events -n pss-lab --field-selector reason=FailedCreate
kubectl describe replicaset -n pss-lab
How 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.

Bash
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
Bash
kubectl delete namespace pss-lab

Production Best Practices & Common Pitfalls

Common Mistake

Setting runAsNonRoot: true on an image that runs as root, such as the official nginx image. The pod is admitted, then fails at container start with CreateContainerConfigError and a message that the image will run as root. Test with docker run --rm --user 1000 <image> first, or switch to an unprivileged variant of the image.

Tip

To score manifests against security best practices before they reach the cluster, run kube-score score payments-api.yaml in CI. It flags missing securityContext settings and other risky defaults.

  • Roll out in three stages. Start with warn and audit, fix the violations the warnings show, then switch to enforce. Going straight to enforce can block critical pods on their next restart.
  • Mount emptyDir volumes 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_SERVICE capability.
  • 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

Resources

Velero vs etcd Snapshot: Which Do You Need?

Velero vs etcd Snapshot: Which Do You Need?

Velero and etcd snapshots protect different layers of a Kubernetes cluster. See what each backs up, what each misses, and why most DR needs both.

11 min read•Aug 2026
Istio Ambient vs Linkerd in 2026: Which Mesh?

Istio Ambient vs Linkerd in 2026: Which Mesh?

Istio Ambient cuts the sidecar tax at L4, but L7 adds waypoint hops, and Linkerd stable builds now come from Buoyant. Choose with tests.

11 min read•Aug 2026
Nginx Ingress vs Traefik vs Gateway API in 2026

Nginx Ingress vs Traefik vs Gateway API in 2026

Ingress-NGINX is retired. Compare Traefik and Gateway API controllers as replacements, plus a safe migration plan that avoids outages.

10 min read•Aug 2026
OPA Gatekeeper vs Kyverno: Policy Engine in 2026

OPA Gatekeeper vs Kyverno: Policy Engine in 2026

OPA Gatekeeper vs Kyverno compared for 2026: Rego vs YAML, mutation, reporting, and operations, plus how to pick a Kubernetes policy engine.

10 min read•Aug 2026
Helm vs Kustomize in 2026: Templating vs Patching

Helm vs Kustomize in 2026: Templating vs Patching

Helm vs Kustomize compared for 2026 - templating vs patching, Helm 4's new features, and why most production teams end up running both.

5 min read•Aug 2026
Prometheus vs Datadog vs New Relic: Real Costs

Prometheus vs Datadog vs New Relic: Real Costs

Prometheus, Datadog, and New Relic compared for 2026 - real pricing at scale, hidden cost drivers, and which fits a Kubernetes-heavy stack.

5 min read•Aug 2026
Cluster Autoscaler vs Karpenter for EKS in 2026

Cluster Autoscaler vs Karpenter for EKS in 2026

Cluster Autoscaler vs Karpenter on EKS: scale-up speed, bin-packing, Spot handling, Auto Mode limits and a safe migration path, with v1 NodePool YAML.

11 min read•Aug 2026
GKE vs EKS vs AKS in 2026: Which Fits Your Team?

GKE vs EKS vs AKS in 2026: Which Fits Your Team?

GKE, EKS, and AKS compared for 2026 - control plane pricing, Autopilot vs Karpenter vs Node Auto Provisioning, and which platform actually fits your team.

5 min read•Aug 2026
K3s vs K8s vs MicroK8s: Which Distro in 2026?

K3s vs K8s vs MicroK8s: Which Distro in 2026?

Compare K3s, upstream Kubernetes and MicroK8s on footprint, datastores, HA and updates, and pick the right fit for edge, dev or production.

10 min read•Aug 2026
Canary Deployments with Argo Rollouts & Flagger

Canary Deployments with Argo Rollouts & Flagger

Ship to 5% of users first and auto-rollback on bad metrics: canary deployments on Kubernetes with Argo Rollouts, Flagger, and Gateway API.

11 min read•Jun 2026
OpenTelemetry Explained: Metrics, Logs, Traces

OpenTelemetry Explained: Metrics, Logs, Traces

OpenTelemetry in practice: instrument a Node.js service, run a production Collector, sample traces and link metrics, logs and traces in Grafana.

11 min read•Jun 2026
Kubernetes Cost Optimization Without SLO Risk

Kubernetes Cost Optimization Without SLO Risk

Kubernetes clusters average about 8% CPU use. Cut waste safely with request rightsizing, autoscaling, spot, and OpenCost, keeping SLOs.

11 min read•Jun 2026
ArgoCD vs FluxCD: GitOps for Kubernetes in 2026

ArgoCD vs FluxCD: GitOps for Kubernetes in 2026

ArgoCD vs FluxCD compared for 2026: UI, multi-tenancy, Helm, image automation and pruning risks, with a clear guide to picking your GitOps engine.

10 min read•Jun 2026

Explore More in Kubernetes Security and Access Control

All 3 Topics

Frequently Asked Questions

Is Implementing Kubernetes Pod Security Standards free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Implementing Kubernetes Pod Security Standards topic cover?

Enforce Kubernetes Pod Security Standards with namespace labels, harden pods with securityContext, and audit existing workloads before enforcing.

Found a mistake, an outdated step or a broken link?