Kubernetes cookbook · Intermediate
Enforce the restricted Pod Security Standard
Stop anyone from deploying privileged or root containers into application namespaces.
Approach
Label the namespace to enforce restricted (with warn and audit to see violations first), and write pod specs
that comply.
Solution
apiVersion: v1
kind: Namespace
metadata:
name: shop
labels:
pod-security.kubernetes.io/enforce: restricted
pod-security.kubernetes.io/warn: restricted
pod-security.kubernetes.io/audit: restricted
apiVersion: v1
kind: Pod
metadata: {name: compliant}
spec:
securityContext:
runAsNonRoot: true
runAsUser: 10001
seccompProfile: {type: RuntimeDefault}
containers:
- name: app
image: ghcr.io/acme/api:1.4.2
securityContext:
allowPrivilegeEscalation: false
capabilities: {drop: [ALL]}
Pitfalls
- Images that need root or write to
/; fix the image (non-root user, writable volumes). - Enforcing on existing namespaces without a warn period.
Variations
- Pin the policy version (
enforce-version: v1.37) for predictable upgrades. - Kyverno or Gatekeeper for rules beyond the standards (allowed registries, required labels).
Further reading: Pod Security Admission
Reference: https://kubernetes.io/docs/concepts/security/pod-security-admission/
More Kubernetes recipes
- Autoscale a Deployment on CPU and memory
- Debug a distroless pod with an ephemeral container
- Default-deny network policies that keep DNS working
- Expose a service over HTTPS with automatic certificates
- Give a CI pipeline least-privilege deploy access
- Handle SIGTERM in your application for Kubernetes
- Manage dev, staging and prod with Kustomize overlays
- Restart pods automatically when configuration changes