How to Run Kubernetes Pod as Non-Root User
To run a Kubernetes pod as a non-root user, set the
securityContext.runAsUser field in the pod or container spec to a non-zero user ID. Also, ensure the container image supports that user and adjust file permissions if needed.Syntax
The securityContext field in a pod or container spec controls security settings. Use runAsUser to specify the user ID the container runs as. Setting it to a non-zero value runs the container as a non-root user.
Example fields:
securityContext.runAsUser: Numeric user ID to run the container.securityContext.runAsGroup: Numeric group ID (optional).securityContext.fsGroup: Group ID for mounted volumes (optional).
yaml
apiVersion: v1
kind: Pod
metadata:
name: non-root-pod
spec:
securityContext:
runAsUser: 1000
runAsGroup: 3000
fsGroup: 2000
containers:
- name: app
image: busybox
command: ["sh", "-c", "sleep 3600"]Example
This example creates a pod that runs the container as user ID 1000 instead of root (0). It uses the busybox image and sleeps for an hour to keep the pod running.
This demonstrates how to specify runAsUser in the pod's securityContext.
yaml
apiVersion: v1
kind: Pod
metadata:
name: non-root-example
spec:
securityContext:
runAsUser: 1000
containers:
- name: busybox
image: busybox
command: ["sh", "-c", "id && sleep 3600"]Output
uid=1000 gid=0 groups=0
Common Pitfalls
Common mistakes when running pods as non-root include:
- Using an image that only supports root user, causing permission errors.
- Not setting
runAsUseror setting it to 0 (root) unintentionally. - File or volume permissions not allowing the non-root user to access needed files.
- Forgetting to set
fsGroupwhen using persistent volumes, which can block access.
Always verify the container image supports the user ID and adjust permissions accordingly.
yaml
apiVersion: v1
kind: Pod
metadata:
name: wrong-non-root
spec:
securityContext:
runAsUser: 1000
containers:
- name: app
image: alpine
command: ["sh", "-c", "touch /root/testfile"]
# This will fail because user 1000 cannot write to /root directory.Quick Reference
Tips for running pods as non-root:
- Set
securityContext.runAsUserto a non-zero UID. - Use
runAsGroupandfsGroupfor group permissions. - Ensure container image supports the specified user.
- Adjust file and volume permissions to allow access.
- Test with
idcommand inside container to confirm user.
Key Takeaways
Always set securityContext.runAsUser to a non-zero user ID to avoid running as root.
Verify your container image supports the specified non-root user.
Adjust file and volume permissions to allow access for the non-root user.
Use fsGroup to set group ownership on mounted volumes for proper access.
Test your pod by running commands like 'id' inside the container to confirm the user.