Kubernetes
AKS
MustRunAsNonRoot
SecurityPolicy
ContainerSecurity

How to enforce MustRunAsNonRoot policy in K8S cluster in AKS

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Introduction

Running containers as non-root is a baseline Kubernetes security control that reduces privilege exposure. In AKS, enforcement is typically done with Pod Security Admission labels and optionally Azure Policy for centralized governance. The practical goal is to block pods that run as root unless explicitly exempted.

Understand Current Kubernetes Policy Model

Older PodSecurityPolicy mechanisms are deprecated and removed in modern Kubernetes releases. Current clusters commonly use:

  • Pod Security Admission namespace labels,
  • Gatekeeper or Azure Policy constraints for policy-as-code.

For non-root enforcement, focus on pod and container security context fields such as runAsNonRoot and runAsUser.

Enforce with Pod Security Admission in AKS

Label namespaces with a Pod Security level that enforces non-root requirements. The restricted profile is the strictest built-in baseline.

bash
1kubectl label namespace apps \
2  pod-security.kubernetes.io/enforce=restricted \
3  pod-security.kubernetes.io/audit=restricted \
4  pod-security.kubernetes.io/warn=restricted

This causes non-compliant pods to be denied in that namespace.

Example compliant deployment snippet:

yaml
1apiVersion: apps/v1
2kind: Deployment
3metadata:
4  name: web
5  namespace: apps
6spec:
7  replicas: 1
8  selector:
9    matchLabels:
10      app: web
11  template:
12    metadata:
13      labels:
14        app: web
15    spec:
16      securityContext:
17        runAsNonRoot: true
18        runAsUser: 10001
19      containers:
20        - name: web
21          image: nginx:1.27
22          securityContext:
23            allowPrivilegeEscalation: false
24            readOnlyRootFilesystem: true

Image must support that user ID. If image hardcodes root-only behavior, pod admission may fail.

Add Azure Policy for Cluster-Wide Governance

In AKS, Azure Policy can audit or deny workloads that violate rules. This is useful when managing many namespaces and teams.

High-level flow:

  1. enable Azure Policy add-on for AKS,
  2. assign built-in or custom policies for non-root enforcement,
  3. monitor compliance and remediation in Azure Policy dashboards.

Policy assignment via Azure CLI is typically done at subscription or resource group scope.

bash
1az aks enable-addons \
2  --addons azure-policy \
3  --name <aks-name> \
4  --resource-group <rg>

Then assign a policy initiative that includes non-root constraints for Kubernetes workloads.

Validate Enforcement with Test Pods

Use a root pod manifest to verify deny behavior.

yaml
1apiVersion: v1
2kind: Pod
3metadata:
4  name: root-test
5  namespace: apps
6spec:
7  containers:
8    - name: root-test
9      image: busybox
10      command: ["sh", "-c", "sleep 3600"]
11      securityContext:
12        runAsUser: 0

Apply it:

bash
kubectl apply -f root-test.yaml

A correctly enforced namespace or policy should reject this pod.

Now test a compliant version with non-root UID and verify admission succeeds.

CI and Manifest Guardrails

Add checks in CI so violations are caught before deployment. Tools such as kubectl --dry-run=server, conftest, or policy engines can validate manifests pre-merge.

This prevents policy surprise during release and keeps developer feedback loops short.

Handle Exceptions with Controlled Namespaces

Some legacy workloads may need temporary exceptions. Instead of weakening cluster-wide policy, isolate them in dedicated namespaces and document sunset timelines.

Operational pattern:

  • strict enforcement in default workload namespaces,
  • explicit exception namespace with stronger monitoring,
  • regular review to remove exception workload debt.

This keeps overall posture strong while allowing controlled migration.

Common Pitfalls

A common mistake is setting runAsNonRoot: true without using an image that has a valid non-root user path. The pod still fails at runtime or admission due to user mismatch.

Another issue is applying strict namespace labels to system namespaces unintentionally. Keep platform namespaces separated and label only intended workload namespaces.

Developers also rely only on audit mode and assume enforcement. Audit and warn modes do not block workloads. Use enforce mode where required.

Summary

  • Enforce non-root execution in AKS with Pod Security Admission and governance policies.
  • Use namespace labels such as enforce=restricted for built-in admission checks.
  • Configure pod and container security contexts explicitly for non-root operation.
  • Validate with both failing and compliant test manifests.
  • Add CI policy checks to catch security context issues before deployment.

Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.