A non-root container runs its processes as a user other than the operating-system root user. This adds a layer of defense: if a container escape bypasses Linux container isolation, the attacker still lacks root privileges on the node. section 12.4
Apply the technique across the image, workload, and application:
- Set runAsNonRoot: true in the container securityContext so Kubernetes rejects images that would run as root. section 12.4
- Use a Dockerfile USER instruction or specify runAsUser: 1001 to select the non-root identity explicitly. section 12.4
- Adapt the application to non-privileged operation: listen on port 8080 instead of port 80 and make the logs directory writable. section 12.4
Fixing a timeserver deployment
A deployment configured with runAsNonRoot: true fails when its image still runs as root. After assigning user 1001, the server cannot bind to port 80, so it moves to port 8080; the Service continues exposing port 80 through targetPort: 8080. The image also grants group write access to the logs directory. section 12.4
Listing 12.6 Chapter12/12.4_NonRootContainers/1_permission_error/deploy.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: timeserver
spec:
replicas: 1
selector:
matchLabels:
pod: timeserver-pod
template:
metadata:
labels:
pod: timeserver-pod
spec:
containers:
- name: timeserver-container
image: docker.io/wdenniss/timeserver:6
securityContext: #1
runAsNonRoot: true #1
#1 Prevent running this container as the root user.
Shows the Kubernetes Deployment setting that prevents the container from running as root. section 12.4
