404human Experience Projects Writing Build logs Learning Books Progress
Rust · Zola
zsh · 404human@dev:~ Tab complete · ↑↓ history · type help

Docker security best practices for production (with real verify checks)

Practical Docker security best practices: non-root users, minimal multi-stage images, capability dropping, secret hygiene, and exact commands to verify every container.

Published
Read time
5 min read
Kind
guide
Topics

Most Dockerfiles start life as a quick five-line snippet copied from a tutorial: FROM node:latest, COPY . ., CMD ["node", "server.js"]. It builds, it runs, and six months later it is serving production traffic as UID 0 (root), carrying curl, bash, gcc, a cached .env file, full Linux capabilities, and an unpinned :latest tag.

A Docker container is not a virtual machine—it is a Linux process wrapped in namespaces and cgroups sharing the host kernel. Treating containers like magical security boxes is how a routine application bug turns into a host compromise.

Here are the eight Docker security practices that eliminate the vast majority of real production risks—paired with exact commands to verify your running container actually enforces them.

Quick production checklist

ControlDefault Docker behaviorProduction target
Process userRuns as root (UID 0)Explicit non-root USER (e.g. 10001:10001)
Base imageFull Debian/Ubuntu with shells & compilersMulti-stage build → distroless or pinned alpine/slim
Image tagsMutable :latestPinned version + @sha256:... digest
Root filesystemWritable everywhere--read-only + tiny tmpfs for /tmp
Linux capabilities~14 default capabilities granted--cap-drop=ALL (add back only what you prove you need)
Privilege escalationsetuid binaries allowed--security-opt=no-new-privileges:true
Docker socketSometimes mounted for convenienceNever mount /var/run/docker.sock inside app containers
Resource limitsUnbounded CPU, RAM, and PIDsExplicit --memory, --cpus, and --pids-limit

1. Multi-stage builds + minimal runtime images

Compilers, package managers (apt, npm, cargo), curl, and interactive shells are fantastic during the build stage and a gift to attackers during the runtime stage.

Split build and runtime cleanly—and pin the base image digest so an upstream tag rewrite cannot silently change your production binary:

# Stage 1: Build (has toolchain, discarded from final image)
FROM rust:1.85-slim-bookworm@sha256:REPLACE_WITH_REAL_DIGEST AS builder
WORKDIR /app
COPY Cargo.toml Cargo.lock ./
COPY src ./src
RUN cargo build --release

# Stage 2: Minimal non-root runtime (no shell, no apt, no curl)
FROM gcr.io/distroless/cc-debian12:nonroot@sha256:REPLACE_WITH_REAL_DIGEST
WORKDIR /app
COPY --from=builder /app/target/release/app /app/app
USER 65532:65532
EXPOSE 8080
ENTRYPOINT ["/app/app"]

For Node or Python apps where you need a small OS base, create a dedicated UID/GID (adduser --disabled-password --uid 10001 appuser) and switch to USER 10001:10001 before ENTRYPOINT.

2. Never bake secrets into image layers or ARG

Three ways teams accidentally leak API keys inside Docker images:

  1. Missing .dockerignore: COPY . . silently sweeps .env, .git/, and ~/.ssh/ straight into the image layer. Always start .dockerignore with .env*, .git, *.pem, *.key, and local DB files.
  2. Using ARG for build tokens: ARG NPM_TOKEN values are recorded in plain text inside docker history.
  3. Deleting a file in a later RUN: Earlier immutable layers still contain the deleted secret.

When a build genuinely needs a private registry token, use BuildKit secret mounts—the secret is mounted only during that single RUN command and never written to any layer:

RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm ci --omit=dev

3. Drop capabilities, lock the filesystem, block setuid

Even if an attacker gets remote code execution inside your app container, runtime flags drastically shrink what they can do next:

docker run -d \
  --name my-api \
  --user 10001:10001 \
  --read-only \
  --tmpfs /tmp:rw,noexec,nosuid,size=64m \
  --cap-drop=ALL \
  --security-opt=no-new-privileges:true \
  --pids-limit=256 \
  --memory=512m \
  --cpus=1.0 \
  my-api@sha256:...

What each flag stops:

  • --read-only: stops an attacker from dropping malware binaries or modifying app scripts on disk.
  • --tmpfs /tmp:rw,noexec,nosuid,size=64m: gives the app a bounded scratch folder that cannot execute binaries or fill the host disk.
  • --cap-drop=ALL: removes raw socket creation (CAP_NET_RAW), chown, and kernel surface area that web apps never need.
  • --security-opt=no-new-privileges:true: blocks privilege escalation through setuid/setgid binaries.
  • --pids-limit=256 & --memory=512m: stops fork bombs and runaway OOM leaks from starving neighboring containers on the host.

4. Never mount /var/run/docker.sock into an app container

Mounting the Docker daemon socket (-v /var/run/docker.sock:/var/run/docker.sock) inside a container is effectively giving that container root on the host. Any process that can talk to docker.sock can launch a new privileged container mounting the host’s / filesystem in one HTTP request.

If an observability agent or reverse proxy genuinely needs container metadata, put a read-only socket proxy in front of it—or avoid Docker-socket discovery entirely (on a single VPS, running services under hardened systemd units behind Caddy avoids the Docker daemon attack surface altogether; see self-hosting web apps on one VPS).

5. Watch Docker’s iptables bypass trap

One surprise that catches almost every Linux operator once: Docker publishes ports (-p 8080:8080) by manipulating iptables directly, which bypasses ufw firewall rules by default!

If you run -p 5432:5432 for Postgres or -p 8080:8080 for an internal app thinking ufw deny 8080 protects it, the port is often exposed straight to the public internet anyway.

Fix: Always bind internal ports explicitly to loopback:

-p 127.0.0.1:8080:8080

Only your reverse proxy (Caddy/Nginx) should bind public ports 80 and 443.

6. Verify your running container in CI (don’t just hope)

Never trust a Dockerfile by eyeball—assert the runtime properties automatically with docker inspect (and scan your built image with trivy image --severity HIGH,CRITICAL):

# Confirm non-root user, read-only rootfs, dropped caps, no-new-privileges, and PID limit
docker inspect my-api | jq '.[0] | {
  user: .Config.User,
  readonly_rootfs: .HostConfig.ReadonlyRootfs,
  cap_drop: .HostConfig.CapDrop,
  security_opt: .HostConfig.SecurityOpt,
  pids_limit: .HostConfig.PidsLimit,
  memory_bytes: .HostConfig.Memory
}'

Expected output for a hardened container:

{
  "user": "10001:10001",
  "readonly_rootfs": true,
  "cap_drop": ["ALL"],
  "security_opt": ["no-new-privileges:true"],
  "pids_limit": 256,
  "memory_bytes": 536870912
}

If User is blank (root) or ReadonlyRootfs is false, fail the deployment check before traffic ever touches it.

Frequently asked questions

Why is running a Docker container as root dangerous? Inside a container, UID 0 is still root in the container’s user namespace—and without user-namespace remapping, it maps to UID 0 on the host kernel. If an attacker exploits a vulnerability in your app plus a misconfigured mount or kernel bug, running as root makes container escape and host file tampering dramatically easier.

Does deleting a secret in a later Dockerfile RUN step remove it from the image? No. Docker images are built from immutable layers. If you COPY a .env file or pass a secret in a RUN layer and rm it in the next RUN command, anyone with the image can still extract the secret from the earlier layer. Use BuildKit secret mounts (--mount=type=secret) or runtime environment injection instead.

Are Docker containers a security sandbox for untrusted code? No. Standard Docker containers share the host Linux kernel and are process isolation, not a hard VM boundary. For running untrusted user code or AI-generated scripts, add stronger isolation such as gVisor, Kata Containers, Firecracker microVMs, or a capability-bounded runtime.

Related reading