Skip to main content

TRG 4.03 - Non-root container

StatusCreatedPost-History
Active04-Jan-2024Adjust user ids
Active29-Dec-2022Initial Release
Draft14-Sept-2022Draft

Why

Normally containers do not need root permission but if a container image runs as root, a compromised container has potentially root permissions on the underlying node.

For security reasons this is must be followed.

Description

Implementation

The container's Dockerfile and the Pod resource file (yaml) has to be modified to be able to run as a non-root user.

  • First it is recommended to check how the base image is built to see if it might already have a non-root user defined and used. In this case it is enough to specify that user in the Dockerfile with the USER instruction.
  • Otherwise modify the image's Dockerfile with a RUN command that adds a non-root user and a USER command that specifies which user runs the container on startup. The example below can be modified for specific needs/requirements.
#Pull the base image as Ubuntu
FROM ubuntu:latest

#Add a user with userid 1000 and name nonroot
RUN useradd −u 1000 nonroot

#Run Container as nonroot
USER nonroot
  • Modify the Pod's or Deployment's configuration by adding runAsUser field for both the pod's and container's securityContext section. Also set the allowPrivilegeEscalation to false on the container's securityContext. See the example below:
apiVersion: v1
kind: Pod
metadata:
name: example-pod
spec:
securityContext:
runAsUser: 1000 # SPECIFY USER ID HERE
containers:
- name: example-container
image: gcr.io/google-samples/node-hello:1.0
securityContext:
allowPrivilegeEscalation: false # SET THIS TO FALSE