Course contentsShow
← Docker, Kubernetes & CI/CD
Lesson 528 of 8028. Security and ObservabilityFree lesson

Implementing Non-Root User Execution Policies

Learners will enforce security best practices by ensuring containers run as non-privileged users within the Kubernetes environment.

In this lesson, you will learn how to enforce security by ensuring your containers run as non-privileged users, preventing potential attackers from gaining full system control.

Why Run as Non-Root?

By default, many container images run processes as the root user (UID 0). If a vulnerability exists in your application, an attacker who manages to break out of the container or execute arbitrary code will gain root privileges on the container runtime. This significantly increases the blast radius of an exploit. Implementing a non-root execution policy forces the container to run as a specific, restricted user, ensuring that even if the application is compromised, the attacker lacks the permissions to modify system files or install malicious binaries.

Enforcing Non-Root Execution in Pods

You can enforce this security best practice directly within your Kubernetes Pod manifest using the securityContext field. You can define this at the Pod level (applying it to all containers) or at the individual container level.

To require that your container runs as a non-root user, use the runAsNonRoot: true flag. If the container image is configured to start as root, Kubernetes will prevent the Pod from starting.

apiVersion: v1
kind: Pod
metadata:
  name: secure-app
spec:
  securityContext:
    runAsNonRoot: true
    runAsUser: 1000
    runAsGroup: 3000
  containers:
  - name: web-app
    image: my-secure-app:latest

In the example above, runAsNonRoot: true acts as a safety gate. We also explicitly set runAsUser: 1000 to ensure the process runs with a specific, predictable, non-privileged UID.

Best Practices for CI/CD

While Kubernetes can enforce these settings, it is best practice to bake the non-root requirement into your Dockerfile as well. By using the USER instruction in your Dockerfile (e.g., USER 1000), you ensure the image is built securely from the start. This allows your CI/CD pipeline to test the application in a non-root state before it even reaches the Kubernetes cluster, creating a "security by design" workflow.

Key Takeaway: Running containers as a non-root user is a critical layer of defense that limits the impact of potential exploits by restricting the permissions available to the application process.