Skip to content
Rahul Shishodiaon GitHub LinkedIn profile

Security Contexts

Scope

LevelPathPrecedence
Podspec.securityContextApplies to all containers
Containerspec.containers[].securityContextOverrides pod-level for that container
  • Not a separate resource: fields on Pod/Deployment template

Key fields

FieldScopeEffect
runAsNonRoot: truePod & ContainerFail if image runs as root (0)
runAsUser: 1001Pod & ContainerRun as specific UID
runAsGroupPod & ContainerGroup for process
fsGroupPodvolume ownership
allowPrivilegeEscalation: falseContainerBlock privilege escalation
privileged: falseContainerNo host-level privileges
readOnlyRootFilesystem: trueContainerRoot FS read-only (Notice smallcase for system)
capabilities.add / capabilities.dropContainerLinux capabilities (e.g. drop: [ALL]), Can only be configured at container level
# Pod Configuration
spec:
  securityContext:
    runAsNonRoot: true
    fsGroup: 2000
  containers:
  - name: app
    securityContext:
      allowPrivilegeEscalation: false
      capabilities:
        drop: [ALL]
      readOnlyRootFilesystem: true

Restricted Pod pattern

spec:
  securityContext:
    runAsNonRoot: true
    runAsUser: 1001
    runAsGroup: 3001
    fsGroup: 2001
  containers:
  - name: app
    image: nginx:1.25
    securityContext:
      allowPrivilegeEscalation: false
      capabilities:
        drop: [ALL]
      readOnlyRootFilesystem: true
    volumeMounts:
    - name: tmp
      mountPath: /tmp
  volumes:
  - name: tmp
    emptyDir: {}

Docker equivalents

  • Docker --userrunAsUser
  • --cap-dropcapabilities.drop
  • --privilegedprivileged: true (avoid in production)

Exam tips

  • runAsNonRoot: true + nginx image → CreateContainerConfigError (runs as root)
  • Use non-root images (e.g. bitnami/nginx) or set runAsUser
  • Container-level wins over pod-level for same attribute
  • readOnlyRootFilesystem: true often needs writable emptyDir mounts for /tmp, cache, or runtime dirs