Lesson 8 of 9 · 11 min · Securing containers

Minimal base images and running as non-root

Covers: Docker Engine 29 on Ubuntu 24.04; debian 12, python 3.12-slim/alpine, alpine 3.20, distroless static. Updated 13 Nov 2026. Part of the DevOps Engineer roadmap.

What you will learn

  • Why a container is not a security boundary by default
  • How to choose a minimal base image
  • Creating and using a non-root user
  • Runtime hardening flags: read-only root, --cap-drop, no-new-privileges
  • What these protect against

In simple words

A container is not a safe box by default. If the program inside runs as the administrator and someone breaks into it, they have a head start towards the whole machine. Two habits reduce that risk: keep the image small, with nothing extra inside, and run the program as an ordinary user.

Words to know

  • Base image: the starting image you build on. The smaller it is, the less there is to attack.
  • root: the administrator user. Many containers run as root unless you change it.
  • Non-root user: an ordinary user with limited rights. It is safer for running your application.
  • Capabilities: pieces of administrator power that can be removed from a container one by one.

A container is not a sandbox by default

All containers share the host's kernel. A process in a container that runs as root is root inside its namespaces and, if an attacker escapes through a kernel flaw, a misconfiguration (a mounted Docker socket, --privileged, a writable host mount) or abuses Linux capabilities, it can be root on the host. You reduce risk with defence in depth: less in the image, less privilege at run time.

Threats to keep in mind: a vulnerable library in your image gets exploited; the attacker finds a shell and uses tools in the image (package managers, curl, compilers); a root process modifies files it should not; secrets are stolen from the environment.

1. Choose a small base image

Every package in an image is code that can have vulnerabilities and tools an attacker can use. Fewer packages, fewer problems. Real sizes from our machine:

Base Size Notes
debian:12 185 MB full Debian userland
python:3.12-slim 180 MB Debian slim plus Python; good default
python:3.12-alpine 74.8 MB Alpine (musl libc, BusyBox); smaller, can break some compiled packages
alpine:3.20 12.2 MB tiny general-purpose base
busybox:1.36 6.8 MB a few dozen tools
gcr.io/distroless/static-debian12 6.2 MB no shell, no package manager; just certificates, timezone data and the minimum
scratch 0 completely empty; for static binaries (Go, Rust)

Options in practice:

  • Slim variants (-slim) are the safe default for Python, Node and Java: still glibc, so wheels and native modules work.
  • Alpine is small and popular, but uses musl libc; Python packages with C extensions may need to compile or behave differently, and DNS behaviour differs slightly. Test before standardising.
  • Distroless images contain only the runtime (Java, Python, Node and static variants exist), so there is no shell to run commands in. Debugging uses ephemeral debug containers, which is the modern way anyway.
  • Scratch with a static binary gives the smallest and most locked-down image, as in our multi-stage Go example (6.87 MB).
  • Official or verified images (Docker Official Images, vendor images) from trusted publishers, pinned by version, and rebuilt regularly to receive security fixes.

Fewer packages means fewer findings. Scanning (next lesson) showed it clearly.

2. Do not run as root

By default, the process in a container runs as root (uid 0). Our test app printed as uid 0. If the application is compromised, the attacker is root inside the container: they can install tools, modify any file in the container, bind low ports, and exploit more kernel features. Run as an unprivileged user instead.

Create a user in the Dockerfile and switch to it:

FROM python:3.12-slim
RUN groupadd --system --gid 10001 app \
 && useradd --system --uid 10001 --gid app --no-create-home --shell /usr/sbin/nologin app
COPY --chown=app:app app.py /app/app.py
USER app
WORKDIR /app
CMD ["python", "app.py"]

Running the same application built both ways:

sec-root -> hello from b3c82f764711 as uid 0
sec-user -> hello from e5646b820c75 as uid 10001

and docker exec showed uid=10001(app) gid=10001(app) for the second. Points to get right:

  • Use a numeric UID (USER 10001). Kubernetes runAsNonRoot checks need a number; names cannot be verified.
  • Copy files with the right owner (COPY --chown) and make writable directories (/app/data, caches) owned by that user before USER.
  • Ports below 1024 need privilege on classic setups. Listen on 8080 and map it (-p 80:8080). (Docker and Kubernetes allow unprivileged low ports by sysctl, but do not rely on it.)
  • Many official images already provide a user: nginx-unprivileged, postgres (switches to postgres after init), USER node in Node images.
  • docker run --user 10001:10001 image enforces it at run time even if the Dockerfile forgot; Kubernetes uses securityContext.
  • In rootless setups (rootless Docker, Podman), even the daemon and container root map to an unprivileged host user, a stronger layer.

3. Reduce what the process can do at run time

Combine these flags (or their Compose / Kubernetes equivalents) for a hardened container:

docker run --rm \
  --user 10001:10001 \
  --read-only --tmpfs /tmp \
  --cap-drop ALL \
  --security-opt no-new-privileges \
  alpine:3.20 sh -c 'id; touch /x; touch /tmp/ok && echo "tmp writable"; grep -E "CapEff|NoNewPrivs" /proc/self/status'

Our output:

uid=10001 gid=10001 groups=10001
touch: /x: Read-only file system
tmp writable
CapEff:	0000000000000000
NoNewPrivs:	1

Each flag:

  • --read-only: the root filesystem is read-only. An attacker cannot drop tools or modify code in the container. Give the app writable tmpfs/volumes only where needed (/tmp, a data directory).
  • --cap-drop ALL: Linux capabilities split root's powers into pieces (bind low ports, change file ownership, raw sockets, mount, load modules). Docker gives containers a default subset. Drop them all and add back only what the app needs (--cap-add NET_BIND_SERVICE). Our CapEff of all zeros shows nothing is left.
  • no-new-privileges: the process and its children cannot gain privileges through setuid binaries (NoNewPrivs: 1).
  • --pids-limit, --memory, --cpus: stop fork bombs and resource exhaustion from taking down the host.
  • Default seccomp and AppArmor/SELinux profiles stay on. Never use --security-opt seccomp=unconfined casually.

Things that undo all of this

  • --privileged: gives the container nearly full access to the host's devices and kernel features. Avoid it; if a tool "needs" it, find the specific capability or device instead.
  • Mounting the Docker socket (-v /var/run/docker.sock:/var/run/docker.sock): anything in that container can start privileged containers and own the host. Equivalent to root on the host.
  • --network host, --pid host and writable mounts of host paths like /etc or /.
  • Running a shell as root "just for debugging" in production images.

In Compose and Kubernetes

Compose:

services:
  api:
    image: shop-api:1.4.2
    user: "10001:10001"
    read_only: true
    tmpfs: [/tmp]
    cap_drop: [ALL]
    security_opt: ["no-new-privileges:true"]

Kubernetes securityContext has runAsNonRoot: true, runAsUser, readOnlyRootFilesystem: true, allowPrivilegeEscalation: false, capabilities: {drop: ["ALL"]} (the Kubernetes course returns to this), and Pod Security Standards can enforce it cluster-wide.

A hardening checklist

  1. Small, pinned, trusted base (slim, distroless or scratch where possible).
  2. Multi-stage build; no compilers or package managers in the final image.
  3. Non-root numeric USER; files owned correctly.
  4. Read-only root filesystem with explicit writable mounts.
  5. Drop all capabilities, add back only what is needed; no-new-privileges.
  6. Resource limits.
  7. No --privileged, no Docker socket, no host namespaces.
  8. Rebuild and redeploy images regularly to pick up base-image fixes.

Common mistakes

  • Running everything as root because it "just works".
  • A non-root USER while the app needs to write to a root-owned directory, then "fixing" it with chmod 777 or going back to root.
  • Assuming Alpine is always better.
  • Never updating the base image, so known vulnerabilities pile up.
  • Using --privileged or the Docker socket to avoid understanding a permissions error.

Try it yourself

  1. Build the same small app with a root and a non-root Dockerfile and compare the output of id inside each.
  2. Run it with --read-only; fix the errors by adding exactly the tmpfs or volume mounts the app needs.
  3. Run with --cap-drop ALL and find out which capability, if any, your application needs.
  4. Compare the sizes of python:3.12, -slim and -alpine for your app.

Check yourself

Why is running as root in a container risky even though it is isolated?

Containers share the host kernel and isolation can be weakened by misconfiguration or kernel bugs. A root process has more capabilities and can modify the whole container filesystem, and if it breaks out it is root on the host.

What do distroless and scratch images give you compared with a normal base?

Almost nothing besides the application and its minimal runtime: no shell or package manager, so a smaller attack surface, fewer vulnerabilities to patch and fewer tools for an attacker, at the cost of harder interactive debugging.

What does --cap-drop ALL do?

Removes all Linux capabilities from the container's processes, so they cannot do privileged operations like binding low ports or changing ownership. Add back individual capabilities only if needed.

Why use a numeric UID in USER?

Orchestrators such as Kubernetes can verify a numeric non-zero UID (runAsNonRoot); a user name cannot be checked without looking inside the image.

Interview questions

How would you harden a container image and its runtime configuration?

Minimal pinned base, multi-stage build, non-root numeric user, read-only root filesystem with tmpfs for writable paths, drop all capabilities, no-new-privileges, resource limits, no privileged mode or host mounts, regular rebuilds and scans.

Why is mounting /var/run/docker.sock into a container dangerous?

Access to the Docker API allows creating containers with arbitrary mounts and privileges, so it is equivalent to root access on the host.

Alpine or Debian slim for a Python service?

Slim is the safer default because it uses glibc and most wheels work; Alpine saves size but uses musl and may require compiling dependencies or hit compatibility issues. Choose based on testing and the team's needs.

Summary

  • A container is not a sandbox: reduce risk with a minimal image and minimal privilege.
  • Pick slim, alpine, distroless or scratch bases deliberately; pin and rebuild them.
  • Use a numeric non-root USER, a read-only root filesystem, --cap-drop ALL and no-new-privileges.
  • Avoid --privileged, the Docker socket and host namespaces.

Going deeper

See how much of this you can explain

A free mock interview asks you new questions on Docker and containers for DevOps Engineer and scores every answer, with what to fix.