🔐 Run Containers as Non-Root User
Containers run as root by default. Security context runs as non-root. Less privilege, better security.
📝 Security Context
apiVersion: v1
kind: Pod
metadata:
name: secure-pod
spec:
securityContext:
runAsUser: 1000
runAsGroup: 3000
fsGroup: 2000
containers:
- name: myapp
image: myapp:latest
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]
add: ["NET_ADMIN"]
🎯 Best Practices
- runAsNonRoot: true (container user not root) - readOnlyRootFilesystem: true (prevent writing to root fs) - allowPrivilegeEscalation: false (prevent gaining more privileges) - Drop all capabilities, add only needed ones - Set specific user and group IDs
💡 Commands
- kubectl describe pod secure-pod
- Check user: kubectl exec pod-name — id
- Security context at pod level (applies to all containers)
- Security context at container level (overrides pod level)
“Security audit found containers running as root. Added securityContext: runAsNonRoot: true. Now run as user 1000. Simple change, big security win.”
