Container Security
Containers isolate processes, but they are not a security silver bullet. They share the host kernel, they often run as root by default, and images collect vulnerable packages over time. Security comes from layers of small, cheap measures. This lesson covers the most important ones: non-root users, minimal images, secrets handling, scanning and runtime hardening.
1. Don't run as root
Covered in the EXPOSE and USER lesson; it bears repeating. Add a user in the Dockerfile and switch to it, or start containers with --user. Combine with a read-only root filesystem where possible:
docker run -d --user 10001:10001 --read-only --tmpfs /tmp \
--cap-drop ALL --security-opt no-new-privileges shop-api:1.4| Option | Effect |
|---|---|
--user 10001:10001 |
the process runs without root privileges |
--read-only + --tmpfs /tmp |
nobody can modify the image's files at run time; only /tmp is writable |
--cap-drop ALL |
removes Linux capabilities such as changing file ownership or binding raw sockets; add back only what is needed with --cap-add |
--security-opt no-new-privileges |
setuid binaries (like sudo) can't gain privileges |
never --privileged |
gives the container almost full access to the host |
never -v /var/run/docker.sock:... casually |
access to the Docker socket is root on the host |
2. Minimal images
Every package in an image is potential attack surface and a source of CVEs (published vulnerabilities). A distroless or -slim image might have a few dozen packages; a full Debian-based image has hundreds. The model compares vulnerability counts for the same app on different bases (numbers illustrative, but proportional to package count as scanners report):
bases = {
"python:3.12": {"packages": 431, "cves": {"critical": 2, "high": 19, "medium": 64, "low": 140}},
"python:3.12-slim": {"packages": 104, "cves": {"critical": 0, "high": 3, "medium": 12, "low": 38}},
"gcr.io/distroless/python3": {"packages": 24, "cves": {"critical": 0, "high": 0, "medium": 3, "low": 9}},
}
def risk_score(cves):
weights = {"critical": 10, "high": 5, "medium": 2, "low": 0.5}
return sum(weights[s] * n for s, n in cves.items())
print(f"{'base':<28}{'pkgs':>5}{'C':>4}{'H':>4}{'M':>4}{'L':>5}{'score':>8}")
for name, info in bases.items():
c = info["cves"]
print(f"{name:<28}{info['packages']:>5}{c['critical']:>4}{c['high']:>4}{c['medium']:>4}{c['low']:>5}{risk_score(c):>8.1f}")base pkgs C H M L score
python:3.12 431 2 19 64 140 313.0
python:3.12-slim 104 0 3 12 38 58.0
gcr.io/distroless/python3 24 0 0 3 9 10.5
3. Keep secrets out of images
Anything in a layer can be extracted by whoever can pull the image, and ARG/ENV values are visible in docker history and docker inspect. Common leaks and their fixes:
| Leak | Fix |
|---|---|
COPY . . picks up .env or SSH keys |
.dockerignore |
ARG NPM_TOKEN / ENV API_KEY=... |
BuildKit build secret: RUN --mount=type=secret,id=npm_token ... |
password in environment: |
Compose/Swarm/Kubernetes secrets mounted as files |
deleted in a later step (RUN rm id_rsa) |
the file is still in the earlier layer: never copy it in at all |
A build secret is mounted only while one RUN step executes and never lands in a layer:
# syntax=docker/dockerfile:1
RUN --mount=type=secret,id=npm_token,env=NPM_TOKEN \
npm cidocker build --secret id=npm_token,env=NPM_TOKEN -t web .A simple secret scanner, of the kind CI runs over a Dockerfile and build context, catches the obvious mistakes:
import re
RULES = [
(r"(?i)^\s*(ARG|ENV)\s+\w*(PASSWORD|SECRET|TOKEN|API_KEY)\w*", "secret passed via ARG/ENV is stored in image metadata"),
(r"(?i)^\s*(COPY|ADD)\s+.*(\.env\b|id_rsa|\.pem\b)", "copies a credentials file into a layer"),
(r"AKIA[0-9A-Z]{16}", "looks like an AWS access key id"),
(r"(?i)^\s*USER\s+(root|0)\s*quot;, "explicitly runs as root"),
(r"--privileged", "privileged mode requested"),
]
DOCKERFILE = """\
FROM node:22-alpine
ARG NPM_TOKEN
ENV AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE
COPY .env /app/.env
COPY id_rsa /root/.ssh/id_rsa
RUN --mount=type=secret,id=npm_token,env=NPM_TOKEN npm ci
USER root
"""
findings = 0
for number, line in enumerate(DOCKERFILE.splitlines(), start=1):
for pattern, message in RULES:
if re.search(pattern, line):
findings += 1
print(f"line {number}: {message}\n {line}")
print(f"{findings} finding(s)")line 2: secret passed via ARG/ENV is stored in image metadata
ARG NPM_TOKEN
line 3: looks like an AWS access key id
ENV AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE
line 4: copies a credentials file into a layer
COPY .env /app/.env
line 5: copies a credentials file into a layer
COPY id_rsa /root/.ssh/id_rsa
line 7: explicitly runs as root
USER root
5 finding(s)
Line 6, the correct build-secret pattern, raises no finding.
4. Scan images and keep them patched
Scanners compare the packages in an image against vulnerability databases:
docker scout cves shop-api:1.4
trivy image shop-api:1.4
grype shop-api:1.4Sample output (trivy, abridged):
shop-api:1.4 (debian 12.11)
Total: 3 (HIGH: 3, CRITICAL: 0)
┌───────────┬────────────────┬──────────┬───────────────────┬───────────────┐
│ Library │ Vulnerability │ Severity │ Installed Version │ Fixed Version │
├───────────┼────────────────┼──────────┼───────────────────┼───────────────┤
│ libssl3 │ CVE-2025-xxxxx │ HIGH │ 3.0.15-1~deb12u1 │ 3.0.16-1 │Scan in CI and fail the build on critical findings, but also rebuild regularly (weekly, or when the base image updates): an image that was clean at release accumulates CVEs as new ones are published. Tools like Dependabot or Renovate can open pull requests when a new base image digest appears.
5. Trust what you run
- Prefer official or verified publisher images, and pin by version (or digest).
- Sign your images (
cosign sign, Docker Content Trust) and verify signatures before deploying. - Generate an SBOM (software bill of materials):
docker buildx build --sbom=true --provenance=true ...attaches one to the image.
Go further: Dockerfile and Image Hardening scans two Dockerfiles and shows why "deleted" secrets survive in images, and Container Escape Classes covers what breaks isolation.
Test yourself
Why is ARG NPM_TOKEN a bad way to pass a token to a build?
- ARG can't hold strings
- Build args are recorded in the image metadata and history
- Tokens expire
- ARG only works with Alpine
Which docker run option removes all Linux capabilities from the container?
- --privileged
- --cap-drop ALL
- --read-only
- --user 0
An image had zero known vulnerabilities when it was built six months ago. Why might a scan show many today?
- Images change over time
- New CVEs are published for packages it already contains; rebuild on a patched base
- Scanners are random
- Docker adds packages automatically