Hardening Containers in Docker and Kubernetes
Suppose the worst happens: a bug lets an attacker run code inside the Tiffin API container. What happens next depends on settings you chose months ago. If the container runs as root with every privilege, the attacker has a strong foothold. If it is locked down, they are stuck in a small, read-only box that can talk to almost nothing.
The rule
A container may do its job and nothing else.
Start in the Dockerfile:
- Run as a non-root user (
USER 10001). Many images default to root. - Keep secrets out of the image; inject them at runtime.
- Use a minimal, pinned base, as in the previous lesson.
Then enforce the rest in Kubernetes with a securityContext:
spec:
containers:
- name: tiffin-api
image: registry.example/tiffin@sha256:<digest>
securityContext:
runAsNonRoot: true
readOnlyRootFilesystem: true
allowPrivilegeEscalation: false
capabilities:
drop: ["ALL"]
seccompProfile:
type: RuntimeDefault
resources:
limits: { cpu: "500m", memory: "256Mi" }What each line stops:
runAsNonRoot: refuses to start the container as root.readOnlyRootFilesystem: the attacker cannot drop tools or edit the app. Mount a small writable volume only where the app truly writes.allowPrivilegeEscalation: falseand dropping all capabilities: removes kernel powers that help escape the container.seccompProfile: RuntimeDefault: blocks rarely needed system calls.- limits: a hijacked pod cannot starve the node, for example with a crypto-miner.
Two cluster-level controls finish the box. Network policies allow the API to reach only the database and the payment provider. Admission control (built-in Pod Security Admission, or a policy engine) rejects privileged pods and, ideally, any image that is not signed by Tiffin's pipeline. Never mount the container runtime socket into a pod: that hands over the whole node.
The shortcut
Imagine the attacker is already inside and ask four questions: Who am I? What can I write? What powers do I have? Whom can I reach? Every answer should be "almost nothing".
Who am I?
User 10001, not root.
runAsNonRootguarantees it.
Drills
Answer fast — trust the rule.
What does readOnlyRootFilesystem: true prevent?
Which setting is the most dangerous to allow in a Tiffin pod?
What does a Kubernetes network policy add for the Tiffin API?
Where should the non-root user be set?
Remember
- A container may do its job and nothing else.
- Inside the box ask: who am I, what can I write, what powers do I have, whom can I reach?
- Non-root, read-only, no capabilities, limits, network policies, admission control.
