Course contentsShow
← Security
Lesson 1674 of 3,05233. Container SecurityFree lesson

Security Contexts and Capability Management

Configuring securityContext to run containers as non-root, drop capabilities, and set read-only root filesystems.

Security Contexts and Capability Management

You'll learn how to configure Kubernetes security contexts to enforce least-privilege container execution through non-root users, capability drops, and read-only filesystems.


What Is a Security Context?

A security context in Kubernetes defines privilege and access controls at the pod or container level. Think of it as a permission slip that tells the container runtime exactly what powers your container gets—and more importantly, what it doesn't get.

By default, containers often run as root (UID 0) with broad capabilities, creating unnecessary risk. Security contexts let you lock this down.

Three Core Hardening Techniques

1. Run as Non-Root User

Instead of running processes as root inside the container, specify a non-privileged user ID:

securityContext:
  runAsNonRoot: true
  runAsUser: 1000

This prevents attackers from gaining root-level control even if they compromise the container process.

2. Drop Linux Capabilities

Capabilities break root's powers into granular units (like NET_ADMIN or SYS_ADMIN). Drop all by default, then add only what's truly needed:

securityContext:
  capabilities:
    drop:
      - ALL

This follows the principle of least privilege—containers start with zero special powers.

3. Read-Only Root Filesystem

Make the container's root filesystem immutable to prevent runtime tampering:

securityContext:
  readOnlyRootFilesystem: true

If your app needs to write temporary data, mount an explicit tmpfs volume for /tmp.

Why This Matters

An attacker who exploits a vulnerability in your app faces three barriers: they can't escalate to root, they can't abuse powerful system capabilities, and they can't modify binaries or configurations on disk.

Key Takeaway:
Security contexts enforce defense-in-depth by ensuring containers run as non-root users, with minimal capabilities, and immutable filesystems—turning containers into hardened, least-privilege execution environments.