Skip to main content
Course/Security & Scale/SecurityContext β€” Pod & Container Hardening
6/860 min
Security & Scale

SecurityContext β€” Pod & Container Hardening

Run containers as non-root, drop Linux capabilities, enforce read-only filesystems, and prevent privilege escalation.

intermediate60 minRead β†’ Lab β†’ Quiz β†’ Practice
🧠 Brain Warm-Up
🧠 Brain Warm-Up: By default, containers run as root (UID 0). If an attacker breaks out of the container, they have root on the host. What fields would you set in a securityContext to minimize this risk?

Pod vs Container securityContext

spec:
  securityContext:          # ← pod-level: applies to all containers
    runAsUser: 1000
    runAsGroup: 3000
    fsGroup: 2000
  containers:
  - name: app
    securityContext:        # ← container-level: overrides pod-level
      allowPrivilegeEscalation: false
      capabilities:
        drop: ["ALL"]

Pod-level applies to all containers and init containers.

Container-level overrides pod-level for that specific container.

Key Fields

FieldLevelEffect
runAsUserpod/containerSets UID for process
runAsGrouppod/containerSets GID for process
runAsNonRootpod/containerRejects UID 0
fsGrouppodVolume files owned by this GID
readOnlyRootFilesystemcontainerPrevents writes to container FS
allowPrivilegeEscalationcontainerPrevents sudo/setUID
capabilities.dropcontainerRemove Linux capabilities
capabilities.addcontainerAdd specific capabilities
privilegedcontainerFull host access (avoid!)

Linux Capabilities

Instead of root vs non-root, Linux capabilities give fine-grained privileges:

  • NET_BIND_SERVICE β€” bind ports < 1024
  • SYS_ADMIN β€” various admin operations (powerful, avoid)
  • CHOWN β€” change file ownership

Best practice: drop: ["ALL"] then add: ["NET_BIND_SERVICE"] if needed.

The Hardened Baseline

securityContext:
  runAsNonRoot: true
  runAsUser: 1000
  allowPrivilegeEscalation: false
  readOnlyRootFilesystem: true
  capabilities:
    drop: ["ALL"]

This is the minimum you should apply to every production container.