Security Contexts and Pod Security

Security Contexts and Pod Security

Security contexts provide the primary mechanism for configuring security settings at both the pod and container level. These settings control user IDs, group IDs, capabilities, and other security-relevant configurations. Properly configured security contexts prevent many common attacks by restricting what containers can do at runtime. However, default Kubernetes configurations often prioritize compatibility over security, requiring explicit hardening.

Running containers as non-root users represents a fundamental security best practice. Root users inside containers can potentially escape to the host system or access sensitive resources. Security contexts enable specifying non-root users through the runAsUser and runAsGroup fields. Additionally, setting runAsNonRoot: true ensures containers cannot run as root even if the image specifies a root user. These simple configurations significantly reduce attack surface.

apiVersion: v1
kind: Pod
metadata:
  name: security-context-demo
  labels:
    app: secure-app
spec:
  securityContext:
    runAsNonRoot: true
    runAsUser: 1000
    runAsGroup: 3000
    fsGroup: 2000
    seccompProfile:
      type: RuntimeDefault
  containers:
  - name: secure-container
    image: nginx:alpine
    securityContext:
      allowPrivilegeEscalation: false
      readOnlyRootFilesystem: true
      capabilities:
        drop:
        - ALL
        add:
        - NET_BIND_SERVICE
    volumeMounts:
    - name: cache-volume
      mountPath: /var/cache/nginx
    - name: run-volume
      mountPath: /var/run
  volumes:
  - name: cache-volume
    emptyDir: {}
  - name: run-volume
    emptyDir: {}

Linux capabilities provide fine-grained control over privileged operations. By default, containers receive several capabilities that may not be necessary for their operation. Dropping all capabilities and adding only those required follows security best practices. Common capabilities like NET_ADMIN or SYS_ADMIN grant significant privileges and should be avoided unless absolutely necessary. The principle of least privilege applies strongly to capability management.