Skip to main content

Implementing Kubernetes Pod Security Standards and securityContext

Secure Kubernetes pods using Pod Security Standards, securityContext settings, and runtime controls that prevent privilege escalation and container breakout attacks.

52 Terms

Overview and What You Will Learn

In this guide you will learn how to lock down Kubernetes pods at the runtime level using securityContext settings and Pod Security Standards (PSS). You will understand what each security setting does, how to apply security policies at the namespace level, and how to audit your cluster for insecure pods. By the end you will be able to harden any workload against the most common container escape and privilege escalation attacks.

Why This Matters in Production

A container running as root with no security restrictions is one kernel exploit away from compromising the entire node. At Razorpay or PhonePe handling financial transactions, a single compromised container that can escalate to root and access the host filesystem means customer data exposure. Pod Security Standards and securityContext settings are the specific Kubernetes controls that prevent this.

Core Principles

◈ DIAGRAM
+------------------------------------------+
| Pod Security Standards (PSS) | <- Namespace-level enforcement
| Applied via namespace labels | Three levels available
+------------------------------------------+
|
v
+------------------------------------------+
| Privileged | <- No restrictions at all
| Baseline | <- Blocks known privilege escalation
| Restricted | <- Hardened — most secure
+------------------------------------------+
|
v
+------------------------------------------+
| securityContext | <- Pod/container-level controls
| runAsNonRoot, readOnlyRootFilesystem | Fine-grained security settings
| allowPrivilegeEscalation: false |
+------------------------------------------+

Detailed Step-by-Step Practical Lab

Step 1: Applying Pod Security Standards to a Namespace

Pod Security Standards are enforced by adding labels to namespaces. Kubernetes then automatically checks every pod created in that namespace against the chosen profile.

Bash
kubectl label namespace production \
pod-security.kubernetes.io/enforce=restricted \
pod-security.kubernetes.io/enforce-version=latest \
pod-security.kubernetes.io/warn=restricted \
pod-security.kubernetes.io/audit=restricted
YAML
# Or define it in the namespace manifest for GitOps workflows
apiVersion: v1
kind: Namespace
metadata:
name: production
labels:
pod-security.kubernetes.io/enforce: restricted # Blocks non-compliant pods
pod-security.kubernetes.io/warn: restricted # Shows warning in kubectl output
pod-security.kubernetes.io/audit: restricted # Logs violations to audit log
Bash
# Check which PSS level is applied to a namespace
kubectl get namespace production -o yaml | grep pod-security
# Test if a pod would be allowed in the namespace without actually deploying it
kubectl apply --dry-run=server -f deployment.yaml -n production
# If the pod violates PSS, you see the error before it hits the cluster
Step 2: Securing a Container with securityContext
YAML
# deployment.yaml — production-hardened pod spec for a payments API
apiVersion: apps/v1
kind: Deployment
metadata:
name: payments-api
namespace: production
spec:
template:
spec:
# Pod-level securityContext — applies to ALL containers
securityContext:
runAsNonRoot: true # Prevent running as root user
runAsUser: 1000 # Run as UID 1000 (non-root)
runAsGroup: 1000 # Run as GID 1000
fsGroup: 2000 # Files written to volumes use GID 2000
seccompProfile:
type: RuntimeDefault # Apply default seccomp filter
# Blocks dangerous syscalls
containers:
- name: payments-api
image: registry.razorpay.in/payments-api:v3.1.0
# Container-level securityContext — overrides pod level for this container
securityContext:
allowPrivilegeEscalation: false # Cannot gain more privileges than parent
readOnlyRootFilesystem: true # Container filesystem is read-only
# Prevents writing malware to disk
capabilities:
drop:
- ALL # Drop ALL Linux capabilities
add:
- NET_BIND_SERVICE # Only add back what is actually needed
# (allows binding to port 80 as non-root)
volumeMounts:
- name: tmp-dir
mountPath: /tmp # Mount writable /tmp since root fs is read-only
- name: cache-dir
mountPath: /app/cache
volumes:
- name: tmp-dir
emptyDir: {} # Temporary writable directory
- name: cache-dir
emptyDir: {}
Step 3: What Each securityContext Setting Does
Bash
+------------------------------------------+
| runAsNonRoot: true | <- Kubernetes rejects the pod if the
| | container image runs as UID 0 (root)
+------------------------------------------+
+------------------------------------------+
| readOnlyRootFilesystem: true | <- Container cannot write to its own
| | filesystem — malware cannot be written
| | even if the container is compromised
+------------------------------------------+
+------------------------------------------+
| allowPrivilegeEscalation: false | <- setuid binaries cannot gain root
| | even if they exist in the image
| | (blocks sudo, su, passwd etc)
+------------------------------------------+
+------------------------------------------+
| capabilities.drop: [ALL] | <- Removes all Linux capabilities
| | like NET_ADMIN, SYS_ADMIN etc
| | Limits what a compromised container
| | can do on the host
+------------------------------------------+
+------------------------------------------+
| seccompProfile: RuntimeDefault | <- Applies a syscall filter that blocks
| | dangerous kernel calls like
| | ptrace, keyctl, mount
+------------------------------------------+
Step 4: Auditing Existing Pods for Security Violations
Bash
# Find all pods running as root in the cluster
kubectl get pods -A -o json | \
jq '.items[] | select(
.spec.containers[].securityContext.runAsUser == 0 or
.spec.securityContext.runAsUser == 0 or
(.spec.containers[].securityContext.runAsNonRoot == false)
) | .metadata.name + " in " + .metadata.namespace'
# Find all pods with allowPrivilegeEscalation not explicitly set to false
kubectl get pods -A -o json | \
jq '.items[] | select(
.spec.containers[].securityContext.allowPrivilegeEscalation != false
) | .metadata.name'
# Use kubectl-score to get a security score for all workloads
# Install: https://kube-score.com
kubectl score deployment payments-api -n production
# Simulate PSS enforcement without blocking pods — use warn mode first
kubectl label namespace production \
pod-security.kubernetes.io/warn=restricted
# Now deploy and watch kubectl output for PSS warnings
# Fix violations before switching from warn to enforce
Step 5: Fixing Common PSS Violation Errors
Bash
# Error: "pods violates PodSecurity 'restricted': allowPrivilegeEscalation != false"
# Fix: add to container securityContext:
securityContext:
allowPrivilegeEscalation: false
# Error: "pods violates PodSecurity 'restricted': unrestricted capabilities"
# Fix: drop all capabilities
securityContext:
capabilities:
drop: [ALL]
# Error: "pods violates PodSecurity 'restricted': runAsNonRoot != true"
# Fix: add to pod securityContext:
securityContext:
runAsNonRoot: true
runAsUser: 1000
# Error: "pods violates PodSecurity 'restricted': seccompProfile"
# Fix: add to pod securityContext:
securityContext:
seccompProfile:
type: RuntimeDefault

Production Best Practices & Common Pitfalls

  • Apply warn mode to all namespaces first, then fix violations, then switch to enforce. Switching directly to enforce on a live namespace without auditing first can block critical production pods immediately.
  • Use readOnlyRootFilesystem: true on every container and mount explicit emptyDir volumes for directories the app needs to write to (logs, temp files, cache). This is a minor inconvenience to configure but provides strong protection against post-exploitation persistence.
Common Mistake

Setting runAsNonRoot: true at the pod level without verifying the container image actually supports running as non-root. Many official images like nginx default to running as root. The pod will be rejected at admission with a cryptic error. Always test with docker run --user 1000 <image> locally before setting runAsNonRoot in production.

Quick Reference & Troubleshooting Commands

Command Purpose
kubectl label namespace <ns> pod-security.kubernetes.io/enforce=restricted Apply Restricted PSS
kubectl get namespace <ns> -o yaml | grep pod-security Check PSS labels on namespace
kubectl apply --dry-run=server -f pod.yaml Test PSS compliance without deploying
kubectl get pods -A -o json | jq '...' Audit pods for security violations

Resources

Velero vs etcd Snapshot: Not a Real Choice

Velero vs etcd Snapshot: Not a Real Choice

Velero and etcd snapshots protect different layers of a cluster, not the same thing. Here's what each covers and why production DR needs both.

5 min read•Aug 2026
Istio Ambient vs Linkerd in 2026

Istio Ambient vs Linkerd in 2026

Istio Ambient killed the sidecar-tax argument. The real 2026 decision is waypoint topology and Buoyant's licensing shift, not features vs simplicity.

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

Nginx Ingress vs Traefik vs Gateway API in 2026

Ingress-nginx retired in March 2026. Here's how Traefik and the Gateway API actually compare as replacements — and why "just swap it" is the wrong frame.

5 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 maturity, operational overhead, and which policy engine fits your cluster.

5 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 compared for EKS in 2026 - provisioning speed, bin-packing, cloud support, and when each is the right default.

5 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 in 2026

K3s vs K8s vs MicroK8s in 2026

K3s, full Kubernetes, and MicroK8s compared for 2026 - resource footprint, production readiness, and which fits edge, homelab, or cloud workloads.

5 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 in minutes — a hands-on guide to canary deployments with Argo Rollouts and Flagger on Kubernetes.

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

OpenTelemetry Explained: Metrics, Logs, Traces

OpenTelemetry unifies metrics, logs, and traces under one open standard — how it works, what it replaces, and how to instrument a service in 20 minutes.

5 min read•Jun 2026
Kubernetes Cost Optimization Without Breaking SLOs

Kubernetes Cost Optimization Without Breaking SLOs

Average Kubernetes CPU utilization across production clusters is 8%. Here is the complete 2026 playbook for cutting cloud spend without touching your SLOs.

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

ArgoCD vs FluxCD: GitOps for Kubernetes in 2026

ArgoCD and FluxCD are the two dominant GitOps engines for Kubernetes in 2026 — this breakdown tells you exactly which one to pick and why.

10 min read•Jun 2026

Explore More in Kubernetes Networking and Traffic Management

All 6 Topics

Frequently Asked Questions

Is Implementing Kubernetes Pod Security Standards and securityContext 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 and securityContext topic cover?

Secure Kubernetes pods using Pod Security Standards, securityContext settings, and runtime controls that prevent privilege escalation and container breakout attacks.