Lesson 15 of 24Security and supply chain
Container Security in Depth
Learn what actually isolates a container, then strip its privileges: capabilities, read-only roots, numeric UIDs, hardened bases, and file-based secrets.
A security review lands on your team's API service with three findings: the container runs as root, it mounts /var/run/docker.sock so a "deploy helper" can restart siblings, and the database password sits in an environment variable. Your lead asks you to fix all three and explain why each one mattered. To do that well you need a clear picture of what a container really is, because most hardening mistakes come from believing it is a small virtual machine. It is not. In Docker in Production you already switched to a non-root USER, kept secrets out of layers, and picked a slim base. This lesson goes underneath those habits and turns them into a full hardening profile you can defend in a design review.
What actually separates a container from the host
A container is an ordinary Linux process that the kernel shows a restricted view of the world. There is no second kernel. Every syscall your app makes goes straight to the same kernel that runs the host and every other container on it. Isolation is built from several independent kernel features, stacked so that if one fails, the next still holds.
Start with a threat model, because "secure" means nothing until you say against what:
- A compromised app. Someone finds remote code execution in your web framework. What can they do next: read other tenants' data, reach the cloud metadata endpoint, write to the image, pivot to the host?
- Container escape. The attacker uses a kernel bug or a misconfiguration to get out of the container and onto the host, where every other container lives.
- A malicious image. A typosquatted base image or a compromised upstream ships a backdoor before your code even runs. Scanning and signing in the next lesson address this one.
- A leaked secret. The password ends up in logs, a crash dump, or
docker inspectoutput that someone pastes into a ticket.
Hardening is about shrinking what the first threat can do, so it does not turn into the second or fourth.
Namespaces give the process its own view: its own PID 1, its own network stack, its own mount table. They hide things; they do not take away power.
The practical rule follows: you never rely on one layer. You assume the app will be compromised one day and make sure that process holds as few powers as possible when it is.
Capabilities: root is a bundle of powers
On Linux, "root" is not one permission. Since kernel 2.2 it has been split into capabilities: CAP_NET_BIND_SERVICE to bind low ports, CAP_CHOWN to change file owners, CAP_SYS_ADMIN for a huge grab bag of admin operations, and so on. Docker gives every container a default set: AUDIT_WRITE, CHOWN, DAC_OVERRIDE, FOWNER, FSETID, KILL, MKNOD, NET_BIND_SERVICE, NET_RAW, SETFCAP, SETGID, SETPCAP, SETUID and SYS_CHROOT.
A typical web API needs none of them. NET_RAW lets a process craft raw packets (useful for ARP spoofing other containers on the same bridge). DAC_OVERRIDE lets root ignore file permissions. SETUID and SETGID let a process change identity. Drop everything and add back only what you can name a reason for:
docker run --cap-drop ALL --security-opt no-new-privileges --read-only --tmpfs /tmp -p 8000:8000 api:1.4.2no-new-privileges closes the other door. Even with capabilities dropped, a setuid binary (like su or a planted one) could raise privileges when executed. This flag tells the kernel that no exec may ever grant more privileges than the parent had. It costs nothing for a normal app.
Capabilities matter even when you run as a non-root user, because file capabilities and setuid binaries are how a non-root process climbs back up. Non-root plus --cap-drop ALL plus no-new-privileges leaves an attacker with an unprivileged process and no ladder.
The flags that hand over the host
Some options do not weaken one layer; they remove the boundary entirely. Reviewers look for these first.
--privilegedgives the container every capability, access to all host devices, and disables the seccomp and AppArmor/SELinux profiles. A root process in a privileged container can mount the host disk and is, for practical purposes, root on the host.- Mounting
/var/run/docker.sockgives the container the Docker API. Anyone who can talk to that socket can rundocker run -v /:/host --privileged ...and get the host filesystem. The "deploy helper" in the review finding is a root shell on the host waiting to be used. - The
dockergroup is the same thing for humans. Docker's own docs say membership grants root-level privileges. Adding a CI user or a developer to it is handing out root. - Host namespaces:
--pid hostlets the container see and signal every host process, and--network hostputs it on the host's network stack, so it can reach services bound to127.0.0.1that you thought were private. - Broad bind mounts like
-v /:/hostor-v /etc:/etcgive file access to the host directly.
If a tool genuinely needs the Docker API (a CI runner, Traefik reading container labels), put a restricted proxy in front of the socket that only allows the read-only endpoints it uses, or move to a design that does not need it at all.
/var/run/docker.sock read-only (:ro) into a monitoring container, saying the read-only flag makes it safe. Is it safe?Read-only roots and a numeric UID
Read-only root filesystem. With --read-only, an attacker who gets code execution cannot drop a binary into /usr/local/bin, edit your app code, or install tools with apt. Most apps only need to write in a couple of places, so give them those places explicitly with --tmpfs /tmp (memory-backed, gone at stop) or a named volume for real data. When a read-only container crashes at start, the error tells you exactly which path it tried to write, which is a useful inventory of your app's side effects.
A fixed numeric UID. The Dockerfile in Docker in Production used useradd --uid 10001 app and USER app. Prefer USER 10001:10001, the number rather than the name. Kubernetes runAsNonRoot: true makes the kubelet check that the image's user is not 0 before starting it. With a name like app, it cannot resolve the name from outside the image, so it refuses to start the pod with an error that it "cannot verify user is non-root". A numeric UID also makes file ownership on volumes predictable across images.
FROM python:3.13-slim AS runtime
WORKDIR /app
COPY --from=build /app/.venv /app/.venv
COPY app/ ./app/
RUN useradd --uid 10001 --no-create-home --shell /usr/sbin/nologin app
COPY --chown=10001:10001 migrations/ ./migrations/
ENV PATH="/app/.venv/bin:$PATH"
USER 10001:10001
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]Two details here. The app code is copied without --chown, so it stays owned by root and is only readable by the app user. A compromised process cannot rewrite it, even without --read-only. Only files the app genuinely has to own get COPY --chown, which sets ownership in the same layer; a separate RUN chown -R duplicates every file into a new layer and can double the image size.
Low ports. A non-root process traditionally cannot bind ports below 1024. Docker containers since Engine 20.10 set a kernel option that lets any user bind low ports inside the container, but many other runtimes, including Kubernetes by default, do not. The portable answer is to listen on 8000 or 8080 inside the container and let the port mapping, Service, or load balancer present port 80 or 443 outside. Add back NET_BIND_SERVICE only if you truly must listen on a low port.
Rootless engines, user namespaces and sandboxed runtimes
Everything so far limits the process. You can also limit what "root" means.
User namespace remapping (userns-remap in daemon.json) maps UID 0 inside containers to an unprivileged high UID on the host, such as 100000. If a process escapes while root inside, it lands on the host as a nobody. It is a daemon-wide setting and complicates volume permissions, so teams often skip it, which is a mistake on shared build hosts.
Rootless Docker goes further: the daemon itself runs as a normal user inside a user namespace (set up with dockerd-rootless-setuptool.sh install). A daemon bug no longer means host root. Podman is rootless and daemonless by design and reads the same Dockerfiles and images, which is why many Red Hat-based shops use it. Both have limits around networking performance and some kernel features; check the docs for your distribution.
Sandboxed runtimes answer the shared-kernel problem directly. gVisor (runsc) puts a user-space kernel written in Go between the container and the host, so most syscalls never reach the real kernel. Kata Containers run each container inside a lightweight VM with its own kernel. You pay in startup time and syscall-heavy performance. You use them when you run code you did not write: multi-tenant platforms, CI for untrusted pull requests, and AI agent sandboxes that execute model-generated code. As AI Security put it, an agent that runs commands needs a real boundary, and a plain container sharing your kernel is a weak one for hostile code.
Base images beyond slim
The base image decides what an attacker finds after getting in, and how many CVEs your scanner reports. Docker in Production compared full, slim, alpine, distroless and scratch. The newer option is hardened images maintained by vendors who rebuild them continuously to keep CVE counts near zero.
| Option | What you get | Watch out for |
|---|---|---|
Distroless (gcr.io/distroless/...) | Runtime only, no shell, nonroot tags | Few language versions; debugging needs other tools |
| Chainguard images (built on Wolfi) | Minimal, rebuilt daily, signed, SBOMs | The free tier is limited; check which tags are free |
Docker Hardened Images (dhi.io/...) | Minimal Debian or Alpine based images, non-root by default, signed SBOMs and SLSA provenance | Pull from dhi.io after docker login dhi.io; no latest tag |
python:3.13-slim | Debian, shell, apt | More packages, more CVEs, but easiest to work with |
Docker Hardened Images became free under Apache 2.0 in December 2025, with paid tiers for things like FIPS variants and extended support. The pattern with any hardened family is the same: the runtime image has no shell or package manager, so you build in a -dev variant that has them and copy the result into the runtime variant.
FROM dhi.io/python:3.13-dev AS build
WORKDIR /app
COPY requirements.txt .
RUN python -m venv /app/venv && /app/venv/bin/pip install -r requirements.txt
COPY app/ ./app/
FROM dhi.io/python:3.13
WORKDIR /app
COPY --from=build /app /app
ENV PATH="/app/venv/bin:$PATH"
CMD ["python", "-m", "uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]Check the catalog for exact tags; they follow the upstream version and distro. The trade-off is real: no shell means no docker exec -it api sh. You debug by attaching a separate toolbox container to the same namespaces, which is worth practicing before the first incident rather than during it.
Runtime secrets: files beat environment variables
Docker in Production said runtime secrets come from the platform. How they arrive matters. Environment variables are the most common choice and the leakiest:
docker inspectprints every env var in plain text to anyone with Docker access.- Every child process inherits them, including a shell spawned by an attacker or a subprocess you did not write.
- Crash reporters, debug pages and "print the config at startup" log lines love to dump them.
- On Linux,
/proc/<pid>/environexposes them to anything that can read that process's proc files.
A mounted file is narrower: one path, readable by one UID, not inherited, not shown by inspect. Compose secrets: mounts each secret at /run/secrets/<name>. Many official images follow the _FILE convention: set POSTGRES_PASSWORD_FILE=/run/secrets/db_password instead of POSTGRES_PASSWORD, and the entrypoint reads the file. Do the same in your own code:
import os
from pathlib import Path
def secret(name: str) -> str:
path = os.environ.get(f"{name}_FILE")
if path:
return Path(path).read_text().strip()
return os.environ[name] # local dev fallback
DATABASE_PASSWORD = secret("DATABASE_PASSWORD")Kubernetes Secrets work the same way: mount them as a volume rather than env, and you also get updates without restarting the pod.
The same controls in Compose and Kubernetes
Nobody types docker run flags in production. These settings live in your Compose file or pod spec, where they are reviewed like code.
services:
api:
image: ghcr.io/acme/api:sha-7f3c2a1
user: "10001:10001"
read_only: true
tmpfs:
- /tmp
cap_drop: [ALL]
security_opt:
- no-new-privileges:true
pids_limit: 200
environment:
DATABASE_PASSWORD_FILE: /run/secrets/db_password
secrets:
- db_password
secrets:
db_password:
file: ./secrets/db_password.txtspec:
securityContext:
runAsNonRoot: true
runAsUser: 10001
seccompProfile:
type: RuntimeDefault
containers:
- name: api
image: ghcr.io/acme/api@sha256:4c1e...
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]allowPrivilegeEscalation: false is the Kubernetes name for no-new-privileges. Kubernetes runs pods without a seccomp profile unless you ask, so seccompProfile: RuntimeDefault matters more there than in Docker, where the default profile is on. The Pod Security Standards restricted level, enforced per namespace with the label pod-security.kubernetes.io/enforce: restricted, requires runAsNonRoot, allowPrivilegeEscalation: false, dropping ALL capabilities (only NET_BIND_SERVICE may be added back) and a RuntimeDefault or Localhost seccomp profile. It does not require readOnlyRootFilesystem, so add that yourself.
Match each Docker or Compose setting to its Kubernetes equivalent.
Checking your work
Turn the profile into checks rather than memory. The CIS Docker Benchmark is the standard checklist auditors use, covering host, daemon and container settings. docker scout quickview gives a fast summary of an image's CVEs and whether a better base exists. In CI, policy tools can fail a pull request whose Compose file or pod spec drops one of these settings.
Here is the core of such a check. It flags the problems from the security review at the top of this lesson, then checks the fixed service.
Press Run (⌘ Enter) to see what happens.Notice that DB_PASSWORD_FILE passes: the variable holds a path, not the secret. Try adding "privileged": True to the "after" service and run it again.
What does this print?
svc = {"user": "app", "cap_drop": ["ALL"], "read_only": True}
checks = {
"numeric uid": str(svc.get("user", "0")).isdigit(),
"cap_drop ALL": "ALL" in svc.get("cap_drop", []),
"no-new-privileges": "no-new-privileges:true" in svc.get("security_opt", []),
"read_only": svc.get("read_only", False),
}
failed = [name for name, ok in checks.items() if not ok]
print(len(failed), failed)You inherit a service that runs as root with default settings. Order the hardening work from first to last, safest changes first.
- Tap the steps below in the right order.
- capability
- One slice of root's power, such as
NET_BIND_SERVICEorSYS_ADMIN. Containers get a default set you should mostly drop. - seccomp
- A kernel filter on which syscalls a process may make. Docker's default profile blocks around 44 of them.
- no-new-privileges
- A flag that stops any later
execfrom gaining privileges, so setuid binaries cannot raise them. - user namespace
- A mapping that makes UID 0 inside the container an unprivileged UID on the host.
- rootless mode
- Running the container engine itself as a normal user, so an engine bug does not mean host root.
- gVisor
- A sandboxed runtime that intercepts syscalls in a user-space kernel, for running untrusted code.
- Pod Security Standards
- Kubernetes' built-in privileged, baseline and restricted profiles, enforced per namespace by label.