Q&A-2Harden a typical Kubernetes web application pod.
Answer
What I'd say first (90 seconds)
Assume a first-party image I can rebuild, a CNI that actually enforces NetworkPolicy (Calico, Cilium, Antrea: plain flannel accepts the object and ignores it), and a namespace I can label. I harden in layers, each assuming the previous one held:
- Identity.
automountServiceAccountToken: falseunless the app calls the API server. The mounted token is a bearer credential readable at/var/run/secrets/kubernetes.io/serviceaccount/tokenby anything that gets code execution in the process. - Image. Pin by digest.
web:1.4is a mutable pointer; the digest is the content. - Process.
runAsNonRoot: truewith an explicitrunAsUser,allowPrivilegeEscalation: false,capabilities.drop: ["ALL"],seccompProfile: RuntimeDefault. - Filesystem.
readOnlyRootFilesystem: trueplus explicitemptyDirmounts for the paths the app writes. - Blast radius. Default-deny NetworkPolicy, then allow DNS and named backends.
- Detection. Audit logs, runtime alerts, and the exit codes below.
spec:
automountServiceAccountToken: false
securityContext:
runAsNonRoot: true
runAsUser: 10001
runAsGroup: 10001
fsGroup: 10001
seccompProfile: {type: RuntimeDefault}
containers:
- name: web
image: registry.example.com/web@sha256:<digest>
ports: [{containerPort: 8080}]
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities: {drop: ["ALL"]}
resources:
requests: {cpu: 100m, memory: 128Mi}
limits: {memory: 256Mi} # no CPU limit
volumeMounts:
- {name: tmp, mountPath: /tmp}
- {name: cache, mountPath: /var/cache/nginx}
readinessProbe: {httpGet: {path: /healthz, port: 8080}, periodSeconds: 5}
livenessProbe: {httpGet: {path: /livez, port: 8080}, periodSeconds: 10, failureThreshold: 3}
volumes:
- {name: tmp, emptyDir: {sizeLimit: 64Mi}}
- {name: cache, emptyDir: {sizeLimit: 256Mi}}runAsUser is explicit because runAsNonRoot alone makes the kubelet inspect the image's USER; if the image has none, the pod fails with CreateContainerConfigError before it ever starts. Kubernetes sets net.ipv4.ip_unprivileged_port_start=0 in containers by default (since 1.22), so a non-root process can bind :80 without NET_BIND_SERVICE. Pod Security Admission's restricted profile enforces most of the above at the namespace level: run warn and audit first, then enforce.
What each control actually buys, and what it costs
| control | blocks | first thing that breaks |
|---|---|---|
runAsNonRoot + runAsUser | uid 0 in the container | image with USER root → CreateContainerConfigError |
allowPrivilegeEscalation: false | setuid binaries, file capabilities | entrypoints that sudo or exec a setuid helper |
drop: ["ALL"] | CAP_NET_RAW, CAP_CHOWN, CAP_SYS_ADMIN | images that chown their data dir at startup |
readOnlyRootFilesystem | writes to image layers | anything writing /tmp, /var/run, a pid file → EROFS |
seccompProfile: RuntimeDefault | ~44 syscalls incl. ptrace, bpf, mount, kexec_load | debuggers and some JITs → EPERM |
automountServiceAccountToken: false | API credential in the pod | in-cluster API calls → 401 |
| default-deny NetworkPolicy | lateral movement, metadata service | DNS resolution, if egress to kube-dns isn't allowed |
Failure modes and how I spot them
readOnlyRootFilesystemtoo tight.CrashLoopBackOff,EROFSinkubectl logs --previous. Fix by adding theemptyDir, not by turning the flag off.- Memory limit too low. Exit code 137,
kubectl describe podshowsLast State: Terminated, Reason: OOMKilled. Watchcontainer_memory_working_set_bytesagainst the limit. - CPU limit too low. No crash: p99 latency climbs and
container_cpu_cfs_throttled_seconds_totalrises. This is why I set a memory limit and leave CPU unlimited. - Liveness probe that checks a dependency. One slow backend restarts every replica at once and takes the service down. Readiness should check dependencies; liveness should check only the process.
- NetworkPolicy that isn't enforced. The object exists,
kubectl get netpollooks right, and a test pod still reaches the backend: the CNI doesn't implement it. Verify with an actual connection attempt, not withkubectl get.
When I'd relax it
If the image is third-party and I can't rebuild it, readOnlyRootFilesystem and drop: ["ALL"] will break it. Then I isolate it in its own namespace with a permissive Pod Security label, keep the network policy and runtime detection, and treat the missing controls as accepted risk rather than pretending they're on. seccompProfile: Localhost is stricter than RuntimeDefault but you own the syscall list per kernel version: worth it only for a workload you can test against every node image you run.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.