DEV Community

Cover image for Docker Security in Production: Rootless, Secrets & Image Scanning
Shuvo Halder
Shuvo Halder

Posted on

Docker Security in Production: Rootless, Secrets & Image Scanning

Docker makes shipping software feel easy: build an image, run it anywhere. What it does not tell you is that a container is not a virtual machine. Containers share the host's kernel, and by default they run as root, with a daemon that runs as root, pulling images from the public internet. A single mistake — a leaked secret in an image layer, a privileged container, a mounted Docker socket — turns a container problem into a host problem.

This is not a reason to fear Docker. It is a reason to run it properly. Production teams do not rely on one control; they stack them: a non-root user, dropped capabilities, scanned images, secrets that never touch a layer, and a host that is watched. This post covers each layer, with the commands and settings that actually enforce it.

Docker Security in Production infographic — Shuvo Halder

What the Risk Actually Is

A virtual machine gets its own kernel. A container does not — it is a set of isolated processes on the host kernel, separated by namespaces and limited by cgroups. That design is what makes containers fast and light, and it is also the whole threat model:

  • A container escape is a host compromise. If a process breaks out of its namespaces, it is running on the host, not in a sandbox.
  • Root inside is powerful outside. By default, a container runs as root (uid 0), and the Docker daemon itself runs as root. A container that can reach the daemon or the Docker socket effectively has root on the host.
  • Images come from strangers. A public image is someone else's filesystem. If you never scan it, you are running code you never reviewed.

The goal is not to make Docker "secure" in the abstract. It is to make each of these paths hard: the user is not root, the kernel surface is small, the image is known, the secret is not in the layer, and the daemon is not reachable.

1. Stop Running as Root

The single most effective change is also the simplest: do not run containers as root.

# Bad: the default — everything runs as root
FROM node:20
COPY . /app
CMD ["node", "server.js"]

# Good: a dedicated non-root user
FROM node:20
RUN groupadd -r app && useradd -r -g app app
USER app
COPY --chown=app:app . /app
CMD ["node", "server.js"]
Enter fullscreen mode Exit fullscreen mode

The USER instruction is not cosmetic. A process running as uid 1000 inside the container cannot write to host files owned by root, cannot bind privileged ports, and cannot load kernel modules — even if it escapes the container's filesystem view, it is still an unprivileged user on the host.

Two more levels, for when non-root alone is not enough:

  • Rootless Docker runs the daemon itself as an unprivileged user, using user namespaces. If the daemon is compromised, the attacker gets an unprivileged user — not root. This is the right mode for developer machines and for any host where you cannot justify a root daemon.
  • userns-remap maps container uid 0 to an unprivileged host uid. The container still "thinks" it is root, but on the host it is an ordinary user. Existing images work unchanged, which makes it the easiest retrofit for a host you cannot rebuild.

One more flag belongs on every production run: --security-opt=no-new-privileges:true. It stops a process from gaining privileges through a setuid binary — the classic way a non-root container becomes root again.

2. Drop Capabilities, Shrink the Kernel Surface

Linux capabilities split root's power into small pieces. Docker drops some by default, but a default container still keeps capabilities it almost never needs — the ability to change file ownership, to create device nodes, to send raw network packets.

The production pattern is to drop everything and add back only what the application provably needs:

docker run --cap-drop=ALL --cap-add=NET_BIND_SERVICE my-app
Enter fullscreen mode Exit fullscreen mode

Most web applications need nothing added at all. If yours does, add one capability at a time and write down why — a capability added "just in case" is a capability an attacker will use.

On top of capabilities, two kernel-level profiles narrow what a container can even ask the kernel to do:

  • seccomp filters system calls. Docker applies a default seccomp profile that blocks around 44 dangerous syscalls (like mounting filesystems or loading kernel modules). Keep the default on, and only write a custom profile when you can name the syscall you need.
  • AppArmor / SELinux add mandatory access control on top of the container. On Ubuntu, Docker's default AppArmor profile already blocks writing to sensitive paths like /proc and /sys. On RHEL-family systems, SELinux does the same job. Do not disable them to "fix" a permission error — fix the volume mount instead.

Three flags that should never appear in production unless you can defend them in a review: --privileged (disables almost all isolation), --network=host (the container sees the host's network stack), and --pid=host (the container sees every process on the host). Each one removes a wall that the rest of your controls depend on.

3. Scan Every Image, Pin Every Tag

A public image is a snapshot of someone else's filesystem, and most images contain known vulnerabilities the day you pull them. The fix is a pipeline rule, not a one-off habit: every image is scanned in CI, and a build with a critical vulnerability does not ship.

# Scan with Trivy before the image reaches a registry
trivy image --severity HIGH,CRITICAL my-app:1.4.2

# Pin by digest — a tag can move, a digest cannot
docker pull my-app@sha256:9f2c1e7a4b8d3f6e5a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f
Enter fullscreen mode Exit fullscreen mode

The rules that keep this working:

  • Pin by digest in production, not by tag. :latest is a moving target — the image you tested is not necessarily the image you deploy. A digest is the exact bytes you scanned.
  • Start from a minimal base. A distroless image has no shell and no package manager — there is nothing for an attacker to run and far less to patch. Alpine is the lighter compromise when you need a shell for debugging. A full Debian or Ubuntu base drags in hundreds of packages your application never uses, and every one of them is a vulnerability waiting to be disclosed.
  • Use multi-stage builds. Build in one stage with compilers and toolchains, then copy only the compiled binary into a slim runtime stage. Your production image should not contain a compiler, a package manager, or your source code.
  • Fail the build on critical findings, and track the rest. A scan that only prints a report changes nothing. Set the threshold in CI — critical fails the build — and give the team a window to patch high-severity issues. Rebuild base images on a schedule, not only when something breaks: an image that was clean six months ago is not clean today.

Tools for this job: Trivy and Grype are the common open-source scanners, Docker Scout is Docker's own, and Cosign (Sigstore) lets you sign an image so a cluster only runs images your pipeline actually built. Generate an SBOM (software bill of materials) with Syft so that when the next Log4Shell happens, you can answer "are we affected?" in minutes instead of days.

4. Secrets Do Not Belong in Images

This is the mistake that shows up in breach reports again and again: an API key baked into an image layer, pushed to a registry, and readable forever — because every layer of an image is permanent, even layers a later Dockerfile step tries to delete.

# NEVER do this — the secret is in the layer history forever
ENV AWS_SECRET_ACCESS_KEY=AKIAIOSFODNN7EXAMPLE
RUN curl -H "Authorization: $TOKEN" https://internal.example.com

# Do this instead — BuildKit secrets never enter a layer
# docker build --secret id=token,src=token.txt .
RUN --mount=type=secret,id=token \
    curl -H "Authorization: $(cat /run/secrets/token)" https://internal.example.com
Enter fullscreen mode Exit fullscreen mode

The rules are absolute:

  • Never put a secret in an ENV, a COPY, or a build argument. Build arguments are visible in docker history. Environment variables are visible in docker inspect. Both are trivially readable by anyone who can pull the image.
  • Inject secrets at runtime, from a vault. Docker Swarm secrets, Kubernetes Secrets, or an external vault (HashiCorp Vault, AWS Secrets Manager) mounted as a file or environment variable at container start — never baked into the image.
  • Rotate anything that was ever in an image. If a secret touched a layer, assume it is public and rotate it. Deleting the image does not help if the layer was ever pushed to a registry.
  • Scan for secrets too. Tools like TruffleHog and Gitleaks catch keys in Dockerfiles, image layers, and CI logs before they reach production.

5. Protect the Daemon and the Network

The Docker daemon is the most powerful thing on the host — it can start any container, mount any path, and run anything as root. Protecting it is not optional.

  • Never expose the daemon socket over the network without TLS. Port 2375 without TLS is an open door: anyone who can reach it can start a privileged container and own the host. If you need remote access, use TLS with client certificates, or do not expose it at all.
  • Never mount /var/run/docker.sock into a container. A container with the socket can ask the daemon to start a new privileged container with the host filesystem mounted. That is root on the host, handed over in one mount.
  • Use user-defined networks, not the default bridge. Containers on the default bridge can reach each other by IP with no isolation. A user-defined network gives you DNS by container name and lets you segment services — the database network is not the public-facing network.
  • Publish only the ports you need. -p 8080:80 is a deliberate choice; -P (publish all exposed ports) is not. Every published port is an attack surface, and the database port should never be one of them.

6. Harden the Host and Watch the Runtime

Containers inherit the host's security posture. A hardened container on a neglected host is a locked door in a house with no walls.

  • Keep the Docker engine updated. Engine releases regularly fix container-escape vulnerabilities. An engine two years out of date is the easiest target on the host.
  • Run the CIS Docker Benchmark. The docker-bench-security script checks your host and daemon against the CIS benchmark and prints exactly what to fix — it is the fastest audit you will ever run.
  • Set resource limits. --memory, --cpus, and --pids-limit stop one runaway container from starving the host or forking until it falls over. A container with no limits is a denial-of-service waiting for a bug.
  • Run the root filesystem read-only. --read-only with a --tmpfs mount for the paths that genuinely need writes means an attacker who gets in cannot write a backdoor to disk.
  • Log, and read the logs. Ship container logs to a central system, and alert on the events that matter: a container starting with --privileged, an image pull from an unknown registry, a process running as root where it should not be. Runtime security tools (Falco is the common open-source one) watch syscalls in real time and catch the escape attempt, not just the aftermath.

The Mistakes That Cause Breaches

  • Running everything as root, in the container and in the daemon.
  • Using --privileged, --network=host, or --pid=host to "make it work".
  • Secrets in environment variables, build args, or image layers.
  • Pulling :latest from the public internet and never scanning it.
  • Mounting the Docker socket into a container.
  • Exposing the daemon on port 2375 without TLS.
  • A full-fat base image with a shell, a compiler, and hundreds of unused packages.
  • No resource limits — one container can take the whole host down.
  • No image signing, so anything in the registry can run.
  • Logs going nowhere, so the escape is discovered weeks later, not minutes.

The Production Checklist

  • Non-root user in every image (USER), rootless daemon or userns-remap on the host, no-new-privileges on every run.
  • --cap-drop=ALL, add back only what the app provably needs; default seccomp and AppArmor/SELinux left on.
  • No --privileged, no host network/PID, no Docker socket mounts, no exposed daemon without TLS.
  • Minimal base image (distroless or Alpine), multi-stage build, pinned by digest.
  • Trivy or Grype scan in CI, failing on critical; SBOM generated; images signed with Cosign.
  • Secrets injected at runtime from a vault; nothing secret in any layer; old secrets rotated.
  • User-defined networks, only required ports published, database never exposed.
  • Resource limits set, root filesystem read-only, engine updated, CIS benchmark run, runtime monitoring on.

What Hiring Managers Actually Ask

If you are targeting remote DevOps, SRE, or platform roles, Docker security is interview material because it tests whether you understand the threat model, not just the commands:

  • "A container is running as root. Why is that a problem, and what do you change?" (Answer: containers share the host kernel, so root in the container is one escape away from root on the host — set a non-root USER, use rootless Docker or userns-remap, and add no-new-privileges.)
  • "Your image scan reports a critical CVE in the base image. What do you do?" (Answer: check whether the vulnerable package is actually reachable in the running image, rebuild on a patched base, and if the base has no fix yet, switch to a minimal base or pin a different version — and make the scan fail the build so it cannot ship again.)
  • "Where do you put the database password?" (Answer: never in the image — not in ENV, not in a build arg, not in a layer. Inject it at runtime from a vault or a secrets manager, and rotate it if it ever touched an image.)
  • "A developer mounted the Docker socket into a container to make CI work. What is the risk?" (Answer: the socket is the daemon's API — the container can start a privileged container with the host filesystem mounted, which is root on the host. Replace it with a purpose-built CI runner or a limited API proxy.)

The answer they want is never "I run containers." It is the system around it: least privilege, a known image, a secret that never touches a layer, and a daemon nobody can reach.

Key Takeaway

Docker's isolation is a set of defaults, not a guarantee. Run as non-root, drop the capabilities you do not need, scan every image and pin it by digest, keep secrets out of layers, and protect the daemon like the root access it is. Security in production is not one setting — it is the stack of small decisions that makes the easy attack hard.


Your turn: What is the first thing you check when you inherit someone else's Dockerfile — the user, the base image, or the secrets? Tell me in the comments.

Top comments (0)