What is a non-root container, and how is it different from rootless Docker?

A non-root container runs its main process under an unprivileged UID, set with the USER instruction in the Dockerfile or overridden at run time with --user. The Docker daemon may still run as root. Under rootful Docker without user namespace remapping, UIDs are not translated: UID 0 in the container is UID 0 on the host. Dropping to a non-root UID limits the process inside the container. It cannot bind privileged ports by default, write root-owned files, or use most capabilities. If the process escapes the container, it lands on the host as an ordinary user.

Rootless Docker solves a different problem. It runs the daemon and the containers under an unprivileged host account and uses a user namespace to remap UIDs. The container can still see UID 0, but that UID maps to the invoking host user. Other container UIDs map into that user's subordinate range, which is defined in /etc/subuid. This reduces the damage if the daemon or the runtime is compromised.

The two approaches are complementary. Rootless Docker protects the host from the engine. A non-root user protects against a compromised application process and also protects data within the container. You can combine them. This checklist covers the first approach: images that run as a docker non-root user.

UID mapping in both models

The example assumes the following inputs: the host user is UID 1000, the subordinate range starts at 100000, and the app user is UID 10001.

Model Daemon runs as User namespace Container process UID UID seen on host
Rootful, root container host root (0) none 0 0
Rootful, non-root container host root (0) none 10001 10001
Rootless, root container host user (1000) yes 0 1000
Rootless, non-root container host user (1000) yes 10001 110000
 ROOTFUL (no userns-remap)           ROOTLESS (user namespace)
+---------------------------+        +---------------------------+
| host root (UID 0)         |        | host user (UID 1000)      |
| dockerd runs as UID 0     |        | dockerd runs as UID 1000  |
+-------------+-------------+        +-------------+-------------+
              |                                    |
              v                                    v
+---------------------------+        +---------------------------+
| no user namespace         |        | user namespace (subuid)   |
| container UID = host UID  |        | ctr 0     -> host 1000    |
|                           |        | ctr 1..   -> host 100000..|
+-------------+-------------+        +-------------+-------------+
              |                                    |
              v                                    v
+---------------------------+        +---------------------------+
| root container:  UID 0    |        | root container:  UID 0    |
| USER app:        UID 10001|        | USER app:        UID 10001|
+-------------+-------------+        +-------------+-------------+
              |                                    |
              v                                    v
  host UID: 0 or 10001                 host UID: 1000 or 110000

  Assumed inputs: host user 1000, subuid start 100000, app UID 10001

How container process UIDs appear on the host under rootful Docker without remapping and under rootless Docker, using the assumed UIDs from the table (illustrative mapping, not measured output).

Why run backend images as a docker non-root user, and who should do it?

Most backend compromises start as code execution inside the app: a deserialization bug, a vulnerable dependency, a template injection. Whatever the attacker runs inherits the process's identity. As UID 0, they can rewrite binaries and config in the image, install tools, read every file in the container, and bind privileged ports. As an unprivileged UID, they are limited to what that user can touch. If you build the image carefully, that is the app's own working directory and little else. This limits the blast radius.

The second benefit appears after a container escape. If a kernel or runtime bug lets the process break out, it lands on the host as the same UID it had inside. On a rootful daemon, a non-root container means the attacker arrives as an unprivileged host user, not as host root.

Non-root is not a sandbox. The process still makes syscalls against the shared host kernel, so kernel vulnerabilities remain reachable. Configuration can also cancel the benefit entirely. --privileged, broad capabilities such as CAP_SYS_ADMIN, or a mounted Docker socket each give a path back to host root regardless of the UID.

This applies to backend and platform engineers shipping long-running services, especially onto Kubernetes clusters whose admission policies reject pods that don't declare runAsNonRoot. Make it the default for every new service, since the cost is lowest before paths and permissions harden around root. For existing services, plan it as a tracked migration, not a drive-by change.

How do you set up a non-root user at build time?

Treat the Dockerfile as the place where the runtime identity gets fixed, so that nothing at deploy time has to guess it. Use this checklist for each image:

  • Create the group and user with fixed numeric IDs. On Debian- or RHEL-based images, use groupadd and useradd with explicit --gid and --uid. On Alpine, use addgroup -g and adduser -u. Choose an ID above the range the base image uses for system accounts, such as 10001, and use the same value in every service. Volume ownership, host-side tooling and policy rules can then rely on one known number.
  • Set USER to the numeric ID, not the name. Write USER 10001:10001. Kubernetes checks runAsNonRoot by reading the image's user field. A name like app gives it no way to confirm the user is not UID 0 without reading /etc/passwd, so the kubelet refuses to start the container.
  • Set ownership in COPY, not in a later RUN chown. Each instruction creates a layer. A recursive chown after a copy rewrites the metadata of every file, so the files are stored twice and the image grows by roughly the size of the copied tree. COPY --chown=... applies the ownership in the same layer as the copy.
  • Keep code and binaries read-only to the runtime user. Have root own application files and give the app's group read access only. If an attacker gets code execution, they then cannot overwrite the binary or inject modules into the code path. Grant write access only to the directories covered in the next section.
  • Keep the toolchain in the build stage. Compilers, package managers and shells belong in the builder. The final stage gets the artifact and nothing else, which removes tools a non-root attacker would otherwise reuse.
  • Check the base image first. Many minimal and distroless-style bases already include an unprivileged user. Look up its numeric UID and use that instead of creating a second account.
# syntax=docker/dockerfile:1

# ---- Build stage: the toolchain lives here and is not shipped ----
FROM golang:1.22-bookworm AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
# Static binary so the runtime stage needs no compiler or libc headers
RUN CGO_ENABLED=0 go build -o /out/server ./cmd/server

# ---- Runtime stage: only the artifact and a fixed non-root identity ----
FROM debian:bookworm-slim

# Fixed numeric IDs, the same in every service, above the system-account range
RUN groupadd --gid 10001 app \
 && useradd --uid 10001 --gid 10001 --no-create-home \
      --shell /usr/sbin/nologin app

WORKDIR /app

# Ownership and mode are set in the same layer as the copy (no RUN chown layer).
# root owns the binary and the app group can only read and execute it,
# so the runtime user cannot overwrite it.
COPY --from=build --chown=0:10001 --chmod=0550 /out/server /app/server

# Numeric UID:GID lets Kubernetes verify runAsNonRoot without reading /etc/passwd
USER 10001:10001

ENTRYPOINT ["/app/server"]

A multi-stage Dockerfile that builds in a toolchain stage, creates a fixed-UID/GID user in a slim runtime stage, copies a root-owned, read-only binary with COPY --chown and --chmod, and sets USER to the numeric ID.

Which paths, ports, and file permissions does the app need?

Before writing a single chown, list every path the process writes to at runtime. A good way to do this is to start the container with a read-only root filesystem and watch which writes fail. This is more reliable than reading the code, because libraries and runtimes also write files that the app never mentions.

  • Temp files. Many libraries write to /tmp without asking.
  • Caches. HTTP clients, template engines, and ORMs often write to $HOME/.cache or a similar path.
  • Uploads and generated files. Decide whether these need to survive a restart.
  • PID and lock files. These usually belong in /tmp or /run, not under the app directory.
  • Logs. Write to stdout/stderr where possible so no log directory is needed.
  • Home directory. A UID with no home directory, or one owned by root, breaks tools that expect $HOME to be writable.
  • Language caches. Python writes __pycache__ next to source files, so compile bytecode at build time or set PYTHONDONTWRITEBYTECODE. Package managers keep caches in the home directory.
Write location Recommended handling Why
App config, compiled assets Image-owned, read-only Fixed at build time
/tmp, PID/lock files emptyDir or tmpfs Scratch data, lost on restart
$HOME/.cache, bytecode emptyDir, or pre-built at build time Can be regenerated
User uploads, SQLite files Persistent volume Must survive pod restarts

Set the ownership of image-owned directories at build time with the numeric UID. That way the runtime user never needs write access to the rest of the root filesystem.

For ports, listen on a port above 1024, such as 8080. Binding to a port below 1024 traditionally requires root or CAP_NET_BIND_SERVICE, which are the privileges you are trying to remove. Map the public port outside the container instead: with -p 80:8080, a Service's targetPort, or the load balancer.

apiVersion: v1
kind: Pod
metadata: {name: api, labels: {app: api}}
spec:
  securityContext:
    runAsNonRoot: true
    runAsUser: 10001              # numeric UID that owns image dirs
    fsGroup: 10001                # mounted volumes become writable by this GID
  containers:
    - name: api
      image: registry.example.com/team/api:1.4.2
      env:
        - {name: XDG_CACHE_HOME, value: /home/app/.cache}
        - {name: PYTHONDONTWRITEBYTECODE, value: "1"}  # no __pycache__ at runtime
      ports:
        - containerPort: 8080     # above 1024: no root, no CAP_NET_BIND_SERVICE
      securityContext:
        readOnlyRootFilesystem: true   # any unlisted write fails loudly
        allowPrivilegeEscalation: false
        capabilities: {drop: ["ALL"]}
      volumeMounts:
        - {name: tmp, mountPath: /tmp}                 # scratch, PID/lock files
        - {name: cache, mountPath: /home/app/.cache}   # regenerable cache
        - {name: uploads, mountPath: /srv/app/uploads} # must survive restarts
  volumes:
    - {name: tmp, emptyDir: {medium: Memory, sizeLimit: 64Mi}}  # tmpfs
    - {name: cache, emptyDir: {}}
    - {name: uploads, persistentVolumeClaim: {claimName: api-uploads}}
---
apiVersion: v1
kind: Service
metadata: {name: api}
spec:
  selector: {app: api}
  ports:
    - port: 80                    # port clients connect to
      targetPort: 8080            # unprivileged port inside the container

A Pod with a read-only root filesystem that mounts emptyDir volumes for /tmp and the cache and a persistent volume for uploads, listens on 8080, and relies on a Service to map external port 80 to it.

How do you enforce runAsNonRoot and dropped capabilities at run time?

A USER line in the Dockerfile only sets a default. A rebuilt base image, a final stage that forgets to set USER, a --user 0 added while debugging, or a Helm value override can bring back UID 0 without anyone noticing. Run-time settings stop the container from starting in that state, or remove the privileges root would otherwise have.

In Kubernetes, set these fields in the container's securityContext: runAsNonRoot: true, an explicit numeric runAsUser and runAsGroup, allowPrivilegeEscalation: false, capabilities.drop: ["ALL"], and readOnlyRootFilesystem: true. With runAsNonRoot, the kubelet refuses to start a container whose effective UID is 0. It also refuses when the image declares a non-numeric user such as app and you have not set runAsUser, because it cannot confirm that the name does not resolve to root. That is why the numeric ID belongs in the manifest.

Plain Docker has no direct equivalent of runAsNonRoot. The closest you can get is to always pass a numeric --user, so the image's own USER setting no longer decides anything.

Kubernetes securityContext field Docker flag Effect
runAsNonRoot: true none (pass --user explicitly) Refuses to start as UID 0
runAsUser / runAsGroup --user 10001:10001 Fixes UID and GID
allowPrivilegeEscalation: false --security-opt no-new-privileges Prevents setuid binaries from gaining privileges
capabilities.drop: ["ALL"] --cap-drop ALL Removes all Linux capabilities
readOnlyRootFilesystem: true --read-only Makes the image filesystem immutable

A read-only root filesystem needs explicit writable paths for the scratch directories identified earlier. Use an emptyDir volume in Kubernetes, or --tmpfs in Docker.

# Kubernetes: the kubelet enforces these at container start.
# Plain Docker equivalent of the same controls:
#   docker run --rm \
#     --user 10001:10001 \
#     --cap-drop ALL \
#     --security-opt no-new-privileges \
#     --read-only \
#     --tmpfs /tmp \
#     registry.example.com/orders-api:1.4.2
apiVersion: v1
kind: Pod
metadata:
  name: orders-api
spec:
  containers:
    - name: orders-api
      image: registry.example.com/orders-api:1.4.2
      securityContext:
        runAsNonRoot: true              # refuse to start if effective UID is 0
        runAsUser: 10001                # numeric, so the check works even if the image says USER app
        runAsGroup: 10001
        allowPrivilegeEscalation: false # setuid binaries cannot gain privileges
        capabilities:
          drop: ["ALL"]                 # start from zero capabilities
        readOnlyRootFilesystem: true    # image filesystem cannot be modified
      volumeMounts:
        - name: tmp                     # the one scratch path the app writes to
          mountPath: /tmp
  volumes:
    - name: tmp
      emptyDir: {}

A Pod securityContext that enforces non-root execution, no privilege escalation, no capabilities and a read-only root filesystem, with an emptyDir for /tmp, next to the equivalent docker run flags in the header comment.

When should you avoid or delay a non-root migration, and what breaks?

Most non-root failures come from state the image does not control, so check these before switching.

  • UID mismatches on existing data. Bind mounts and persistent volumes keep the numeric owner from whoever wrote them. If a service ran as root and now runs as UID 10001, its own files return permission denied. Changing the UID of a running service leaves its data unreadable until ownership is migrated, so plan a one-time chown job or init step before the cutover.
  • Slow startup on large volumes. fsGroup and recursive chown touch every file, which can delay startup on volumes with many files. Setting fsGroupChangePolicy: OnRootMismatch skips the walk when the top-level ownership already matches. Whether it takes effect depends on the platform and volume type, because some drivers ignore fsGroup entirely.
  • Hidden writes. A read-only root filesystem exposes libraries that write caches, PID files, or temp data to paths nobody documented.
  • Debugging. Without root, you can't apt install tools into a live container. Use ephemeral debug containers or a separate debug image.
  • Third-party entrypoints. Some images set their own USER or start as root and drop privileges with gosu or su-exec. Forcing a UID makes that step fail, so read the entrypoint first.
  • Arbitrary UIDs. Platforms that assign random UIDs need writable directories owned by GID 0 with group write permission.

Delaying is reasonable when shared volumes have mixed ownership and no maintenance window, when a vendor image doesn't support a custom UID, or when the service is scheduled for replacement.

What are the alternatives to non-root containers, and how do they compare?

Option Protects against Costs
Non-root USER in the image App compromise yielding UID 0 inside the container; writes to root-owned paths Ownership fixes on files and volumes; can be overridden at run time unless enforced
Rootless Docker A daemon or container escape landing as host root, because the daemon itself runs unprivileged User-mode networking adds overhead and can hide client source IPs; ports below 1024 need a host sysctl change; overlay storage depends on kernel support, with slower fallbacks; features needing host privileges are limited, such as some cgroup limits and AppArmor
User namespace remapping Container UID 0 mapping to host UID 0 Usually daemon-wide; bind-mount ownership must match the remapped range; conflicts with sharing host namespaces
Dropped capabilities Raw sockets, mount, ptrace and similar kernel operations Must list the few capabilities the app needs
Read-only root filesystem Persistent tampering and dropped binaries Explicit writable mounts for temp, cache and PID files
no-new-privileges Escalation through setuid binaries or file capabilities Breaks tools that rely on setuid, which backend images rarely need

These options solve different problems, so they stack instead of replacing each other. A non-root user limits what the process can do inside the container. Remapping and rootless Docker limit what container root means on the host. The three hardening flags shrink what any UID can reach. Running a non-root image with dropped capabilities, a read-only root filesystem and no-new-privileges costs little and is a reasonable baseline. Rootless Docker or remapping is a host-level decision. It is justified for multi-tenant hosts or shared build machines, where a daemon escape matters most.

How do you verify the image in CI, and what does it cost?

Verification takes three checks. Run docker run --rm IMAGE id to see the effective UID and GID the process actually gets. Run docker inspect --format '{{.Config.User}}' IMAGE to read what the image declares. Then smoke-test with docker run --rm --read-only --tmpfs /tmp IMAGE and hit a health endpoint. The id output proves runtime behavior, and the inspect output is what an orchestrator evaluates before starting anything. A name like app passes docker run, but Kubernetes rejects it under runAsNonRoot because the kubelet cannot prove a non-numeric user is not root. Declare a numeric UID.

The CI check reads .Config.User, strips any :group suffix, and exits non-zero if the value is empty, 0, or root. Running it on every image build turns a deploy-time pod rejection into a failed pipeline step that names the cause.

The cost is mostly up front. You fix paths, chown writable directories, and align volume ownership. After that, you maintain the list of writable mounts and keep a debug image or ephemeral debug container for the tooling you removed.

Treat the UID as a documented contract: the image owns it, and the platform's securityContext and volume permissions depend on it. When the UID changes, both sides update together.

Illustrative estimate (assumed numbers, not a benchmark):

hours saved per quarter = incidents avoided × hours per incident

With an assumed 4 permission or pod-rejection incidents per quarter at 3 hours each, that is 12 hours saved. Compare that against roughly 1 hour to add the check.

How OneEnv can help

Disclosure: OneEnv is the product behind this blog.

OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.

Applied to docker non-root user, this is where it helps:

Saves time

  • Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
  • One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
  • Changing a shared variable is one edit and one review instead of editing every service's .env by hand.

Saves cost

  • Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
  • Less duplicated configuration to maintain: one shared definition inherited by many services.
  • A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
  • OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.

These are qualitative benefits, not measured results — how much you save depends on how many services share the value.

Want to try it? Start at oneenv.io.