Containers made deployment repeatable and security review harder at the same time. An image is a stack of layers pulled from a public registry, run by a shared kernel, usually as root, with secrets sometimes baked in by accident â and it ships to production faster than anyone reviews it. Container security is the practice of shrinking that attack surface at each stage: build images that expose little, scan them before they can be promoted, enforce policy at admission so non-compliant workloads never schedule, isolate them from each other on the network, and watch for behavior that no static check could have predicted. Skipping any stage simply moves the failure somewhere later.
What an attacker actually gains from a container
The prize is the kernel. Containers share the host kernel and differ from ordinary processes mainly in how little they can see. That means a container escape does not need a virtualization flaw â misconfigured capabilities, a privileged container, a writable Docker socket, or a kernel vulnerability will do. Understanding this reframes every hardening decision: you are not protecting a mini-server, you are constraining a process so that if it is compromised the blast radius stops at one filesystem and one set of network rules.
| Misconfiguration | What it hands over | Enforcement point |
|---|---|---|
| Running as root | Trivial path to wider host access | Dockerfile USER, Kubernetes securityContext |
| Privileged flag | Nearly full host kernel access | Admission policy, blocked by default |
| Writable Docker socket | Root on the host via the daemon API | Never mount it into application containers |
| Excessive Linux capabilities | Kernel features beyond the workload's need | Drop ALL, add back only what is required |
| Secrets in image layers | Permanent, visible to anyone who pulls the image | Runtime secret mounts, external managers |
| Flat pod network | Lateral movement to any other service | Default-deny NetworkPolicy |
Treat the right-hand column as controls that must be provable. An admission controller that rejects non-compliant pods gives you evidence; a wiki page saying "please do not run privileged" gives you a wish.
A Dockerfile that gives an attacker nothing to use
Base image choice dominates image security. A distribution-less runtime image contains no shell, no package manager, and often no known-vulnerable packages, which removes entire classes of findings rather than triaging them. Beyond that, run as a non-root user, copy only what the application needs, and drop the set of privileges to exactly what the process requires.
# Build stage: never leak the toolchain into the runtime image
FROM node:22-alpine AS build
WORKDIR /src
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
RUN npm run build
# Runtime stage: minimal base, non-root, read-only application files
FROM gcr.io/distroless/nodejs22-debian12:nonroot
WORKDIR /app
COPY --from=build /src/dist ./dist
COPY --from=build /src/node_modules ./node_modules
USER nonroot:nonroot
EXPOSE 8080
ENTRYPOINT ["node", "dist/server.js"]
# Build with content trust enabled so unsigned images cannot be pulled
# export DOCKER_CONTENT_TRUST=1
Distroless images eliminate shell-based lateral movement inside the container, but they complicate debugging â pair them with an ephemeral debug sidecar or an exec substitute rather than shipping a shell "just in case." Secrets deserve the same treatment: build arguments and environment variables end up in layer history and process listings, so inject credentials at runtime from a mounted secret or an external manager, and rotate them on a schedule independent of deploys.
Scanning images before they can be promoted
A scanner that runs after deployment produces backlog; the same scanner in the pipeline produces a gate. The practical design is to scan on every push, fail the build on defects above an agreed severity, and record the result so auditors can see it. The commands below scan an image, filter to the vulnerability classes that matter for that service, and print a machine-readable result the pipeline can act on.
# Full image scan with table output for humans
trivy image --severity HIGH,CRITICAL --exit-code 1 registry.example.com/payments-api:1.4.2
# Scan only the packages that are actively reachable in the image
trivy image --scanners vuln,secret,misconfig \
--format json -o scan-results.json \
registry.example.com/payments-api:1.4.2
# Fail the pipeline when a CRITICAL finding is exploitable right now
jq -e '[.Results[].Vulnerabilities[]? | select(.Severity=="CRITICAL")] | length == 0' \
scan-results.json
# Catch secrets accidentally committed into layers
trivy image --scanners secret registry.example.com/payments-api:1.4.2
Two traps recur. First, scanning only the final image misses vulnerabilities introduced by a parent layer, so scan every stage you push. Second, a gate with no exceptions process gets bypassed within a month; maintain a documented, time-limited waiver list with an owner and an expiry date for findings that cannot be fixed immediately, such as a library fix that does not exist yet.
Kubernetes admission: policy that blocks rather than advises
Pod Security Admission replaced the removed PodSecurityPolicy resource and enforces the Pod Security Standards at the namespace level through labels. Three profiles exist â privileged, baseline, and restricted â and most workloads should land on restricted, which forbids privileged containers, host namespaces, and almost all added capabilities. The labels below put a namespace into enforcement mode so a non-compliant pod is rejected at scheduling time with a clear message.
apiVersion: v1
kind: Namespace
metadata:
name: payments
labels:
pod-security.kubernetes.io/enforce: restricted
pod-security.kubernetes.io/enforce-version: latest
pod-security.kubernetes.io/audit: restricted
pod-security.kubernetes.io/warn: restricted
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: payments-api
spec:
template:
spec:
automountServiceAccountToken: false
securityContext:
runAsNonRoot: true
seccompProfile:
type: RuntimeDefault
containers:
- name: api
image: registry.example.com/payments-api:1.4.2
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]
resources:
requests: { cpu: "100m", memory: "128Mi" }
limits: { cpu: "500m", memory: "512Mi" }
Enforce in warning mode first and read the audit log, because a namespace that already runs a DaemonSet needing host access will block on day one. automountServiceAccountToken: false deserves special attention: a pod that never calls the Kubernetes API should not hold a token that can be stolen from its filesystem.
Default-deny network policy as a habit
Kubernetes allows all pod-to-pod traffic until you say otherwise, which means a compromised front-end can reach the database directly. A default-deny policy inverts that: nothing flows until an explicit rule permits it, and each rule maps to a documented dependency. The pair below denies everything, then reopens only the paths the application genuinely needs.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny-all
namespace: payments
spec:
podSelector: {}
policyTypes: [Ingress, Egress]
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-api-to-db-and-dns
namespace: payments
spec:
podSelector:
matchLabels:
app: payments-api
policyTypes: [Egress]
egress:
- to:
- podSelector:
matchLabels:
app: postgres
ports:
- protocol: TCP
port: 5432
- to:
- namespaceSelector: {}
ports:
- protocol: UDP
port: 53
Note the DNS rule: egress policies that forget DNS break name resolution in confusing ways, and teams respond by widening the whole policy. Validate each policy in a test namespace before rollout, and confirm enforcement with a negative test â an application pod that cannot reach a service it should not reach is evidence the policy works.
Runtime detection for the things static checks cannot see
Everything so far assumes you can predict the abuse. Runtime detection covers the rest: a process spawning a shell in a distroless container, a binary reading /etc/shadow, unexpected outbound connections, or a cryptocurrency miner appearing in a list of running processes. Falco evaluates syscall events against rules and emits alerts that your existing alert pipeline can consume.
- rule: Unexpected shell in container
desc: Detect interactive shells spawned by application containers
condition: >
spawned_process and container and
container.name != "debug-sidecar" and
proc.name in (sh, bash, dash, zsh) and
not user.name in (root)
output: >
Shell spawned (user=%user.name container=%container.name
image=%container.image.repository command=%proc.cmdline)
priority: WARNING
tags: [container, process, mitre_execution]
- rule: Cryptocurrency miner execution
desc: Detect known mining binaries inside any container
condition: >
spawned_process and container and
proc.name in (xmrig, minerd, cpuminer, kdevtmpfsi)
output: >
Miner detected (container=%container.name command=%proc.cmdline)
priority: CRITICAL
Feed these alerts into the same queue your on-call analyst watches, and rehearse the response: which pod is evicted, which image is quarantined, and how the node is checked for escape. Detection without a runbook simply converts one alert into a second problem.
â ī¸The Docker socket is a host takeover
/var/run/docker.sock into a container is equivalent to granting root on the host, because the daemon API can start a privileged container with the host filesystem mounted. Treat any workload holding that socket as a break-glass case requiring explicit approval.Common Mistakes
Shipping a full operating system inside every application image
Fix: Build on distroless or alpine bases and add a package only when the application demonstrably needs it.
Scanning images after they are already running in production
Fix: Run the scanner as a pipeline gate on every push, with a documented and expiring exception process.
Deploying Pod Security in enforce mode without an audit pass first
Fix: Enable audit and warn modes, review violations, fix workloads, then switch a namespace to enforce.
Forgetting DNS when writing egress network policies
Fix: Allow explicit DNS egress per namespace so teams do not respond by widening the policy to all destinations.
Storing secrets as environment variables or build arguments
Fix: Inject secrets at runtime from a mounted volume or external manager, and rotate them independently of deploys.
Best Practices
- Run as non-root with a read-only root filesystem, all capabilities dropped, and privilege escalation disabled.
- Scan every image stage for vulnerabilities and secrets, and fail the build above an agreed severity.
- Apply default-deny network policy in every namespace and prove it with a negative connectivity test.
- Automount service account tokens only for pods that actually call the Kubernetes API.
- Pair prevention with runtime detection, and rehearse the eviction and quarantine runbook before you need it.
Key Takeaways
- Container compromise targets the shared kernel, so privileges and capabilities matter more than image cosmetics.
- A distroless, non-root image removes shell-based lateral movement and eliminates whole classes of scanner findings.
- Admission policy converts hardening guidance into something Kubernetes can enforce at scheduling time.
- Default-deny networking limits blast radius even when an application vulnerability cannot be fixed immediately.
- Runtime detection covers the behavior no static analysis predicts â and it only helps if a runbook exists.