Harden Pods with a Security Context
Run as non-root, disable privilege escalation, drop capabilities, use a read-only root filesystem, and set seccomp so a container breakout is much harder.
Task
Apply a restrictive pod security context instead of running containers as root with default privileges.
When to use this
Containers run as root with all capabilities and a writable filesystem, so a single exploit can escalate inside the node.
Prerequisites
- A Kubernetes cluster
- An understanding of what the app needs to write
Steps
1. Set runAsNonRoot and a specific runAsUser and runAsGroup.
Expected output: The process does not run as root.
2. Set allowPrivilegeEscalation false and drop all capabilities, adding back only needed ones.
Expected output: Privilege escalation paths are closed.
3. Set readOnlyRootFilesystem and mount writable emptyDir where needed.
Expected output: The image filesystem cannot be modified.
4. Set a seccomp profile to RuntimeDefault.
kubectl get pod app -o jsonpath='{.spec.containers[0].securityContext}'Expected output: The syscall surface is reduced.
Troubleshooting
Problem
App cannot write temp files
Solution
Mount a writable emptyDir for the paths it uses; do not reopen the whole root filesystem.
Problem
Image assumes root
Solution
Fix the image to run as a non-root user, or set a numeric runAsUser the app can use.
Limitations
- Strict security contexts can break images that expect root or write to their own filesystem.
- They reduce but do not eliminate container escape risk; kernel and runtime vulnerabilities still matter.
Context
Apply a restrictive pod security context instead of running containers as root with default privileges. Containers run as root with all capabilities and a writable filesystem, so a single exploit can escalate inside the node.
Steps
- Set runAsNonRoot and a specific runAsUser and runAsGroup. Expected: The process does not run as root.
- Set allowPrivilegeEscalation false and drop all capabilities, adding back only needed ones. Expected: Privilege escalation paths are closed.
- Set readOnlyRootFilesystem and mount writable emptyDir where needed. Expected: The image filesystem cannot be modified.
- Set a seccomp profile to RuntimeDefault. Expected: The syscall surface is reduced.
securityContext:
runAsNonRoot: true
runAsUser: 10001
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities: { drop: ["ALL"] }
seccompProfile: { type: RuntimeDefault }
Verify
- The process does not run as root.
- Privilege escalation paths are closed.
- The image filesystem cannot be modified.
- The syscall surface is reduced.
Limits
- Strict security contexts can break images that expect root or write to their own filesystem.
- They reduce but do not eliminate container escape risk; kernel and runtime vulnerabilities still matter.