A container that needs too much access can put its node at risk. A Kubernetes security context sets security-related permissions in a Pod specification, either for the Pod or for an individual container. Most applications use it to restrict access; a workload doing node-level administration may need elevated permissions instead. section 12.3
Choose settings to match the workload:
- For an ordinary application, set runAsNonRoot: true and runAsUser to a nonzero user ID. Set allowPrivilegeEscalation: false and drop ALL capabilities to limit what the container can do. section 12.3 section 12.4
- Use privileged: true only when the workload needs node-level access. A privileged container can mount the node’s host filesystem; the same mount fails without that privilege. Running as root inside a container is distinct from having root access on the node. section 12.3
Listing 12.12 Chapter12/12.5_PodSecurityAdmission/nonroot_pod.yaml
apiVersion: v1
kind: Pod
metadata:
name: timeserver-pod
spec:
securityContext:
seccompProfile:
type: RuntimeDefault
containers:
- name: timeserver-container
image: docker.io/wdenniss/timeserver:7
securityContext: #1
runAsNonRoot: true #1
allowPrivilegeEscalation: false #1
runAsUser: 1001 #1
capabilities: #1
drop: #1
- ALL #1
#1 Security context required by the restricted profile
Compare the Pod-level seccompProfile with the container-level user, escalation, and capability settings. This Pod is configured to satisfy a Restricted admission policy. section 12.5.1
Making a service run without root
Setting runAsNonRoot: true alone can prevent a container from starting if its image would run as root. Set runAsUser: 1001 in the security context or USER 1001 in the Dockerfile; the Kubernetes setting takes priority when both are present. Then check the application: the example service cannot bind to port 80 as a non-root user, so it listens on 8080 while its Service exposes port 80 and forwards to 8080. Its log directory also needs writable permissions. section 12.4
Cluster policy can require these settings. Pod Security admission rejects a Pod that violates a namespace’s Restricted policy; a compliant security context allows admission. If a Deployment is created but its Pods do not appear, inspect its ReplicaSet events for admission errors. Test a newer policy version before enforcing it in production. section 12.5.1



