Skip to content
Tutorials Center
My learning

Topics

Lesson 68 of 111 ยท Security

Non-Root Users and Capabilities

Run containers as non-root, drop Linux capabilities with --cap-drop, add back only what you need, block privilege escalation, and know why --privileged is dangerous.

If an attacker takes over the program in your container, the first question is: who are they now? If the answer is "root with a long list of powers", the next steps are easy. If it is "an unprivileged user with no powers and a read-only filesystem", the attacker is stuck in a very small room. This lesson shows how to get to the second answer with three tools: a non-root user, Linux capabilities (--cap-drop, --cap-add) and no-new-privileges.

Everything below was run on a real Docker 29. It builds on the mental model from Container Security Basics and the USER instruction from WORKDIR, USER, EXPOSE and LABEL.

Why not root?

Unless you say otherwise, the main process of a container runs as UID 0. Container root is restricted by capabilities and seccomp, but it is still root: it can read every file in the container regardless of permissions, change ownership, install packages, and write to any volume you mounted. If the container ever shares a bind mount with the host, root in the container can create root-owned files there.

Container root is also one kernel bug away from host root. A normal user needs an extra privilege-escalation bug as well. Running as non-root therefore removes a whole class of attacks for almost no cost.

Running as another user

You can pick the user at run time with --user (or -u):

CONSOLE
$ docker run --rm --user 1000:1000 alpine:3 sh -c 'id; touch /x; echo rc=$?; touch /tmp/x && echo tmp-ok'
uid=1000 gid=1000 groups=1000
touch: /x: Permission denied
rc=1
tmp-ok

The process can no longer write to / (owned by root), but /tmp is world-writable, so that works. It cannot read root-only files either:

CONSOLE
$ docker run --rm --user 1000 alpine:3 cat /etc/shadow
cat: can't open '/etc/shadow': Permission denied

The user does not have to exist in the image. Docker only needs numbers:

CONSOLE
$ docker run --rm --user 4242 alpine:3 id
uid=4242 gid=0(root) groups=0(root)

Look closely: with only a UID, the group is root (GID 0). Files that are group-writable by root become writable for this process. Always give both: --user 4242:4242.

Baking the user into the image

For your own images, create a user in the Dockerfile and switch to it with USER. Use a fixed numeric UID so that Kubernetes and file-permission policies can reason about it:

DOCKERFILE
FROM python:3.13-slim

WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt

COPY --chown=10001:10001 app.py .

RUN useradd --system --uid 10001 app
USER 10001:10001

CMD ["python", "app.py"]

Three habits matter here:

  • Install packages and create directories before USER, while you still have root.
  • COPY --chown gives the app user ownership of what it must modify; everything else stays root-owned and therefore read-only for the app. A process that cannot modify its own code cannot be turned into a backdoor as easily.
  • Put USER as late as possible, but before CMD/ENTRYPOINT.

Many official images already ship a user: postgres, redis and mysql drop privileges for you at startup, and the node image contains a node user (UID 1000) you can select with USER node. For images that must start as root (to fix volume permissions, for instance), the entrypoint script drops to a normal user before starting the server. Read the image's documentation before assuming.

The low-port myth

"Non-root cannot bind port 80" used to be true. Docker now sets the kernel parameter that decides which ports are "privileged" to 0 inside a container's network namespace:

CONSOLE
$ docker run --rm --user 1000 alpine:3 cat /proc/sys/net/ipv4/ip_unprivileged_port_start
0

So a non-root process in a container can listen on port 80 without any extra capability. (On Kubernetes or with --network=host the value comes from the node, so check there.) Even so, it is good practice to listen on a high port such as 8080 inside the container and map it with -p 80:8080.

What are capabilities?

On classic Unix, "root" is one giant switch: UID 0 can do everything. Linux splits that power into about forty named capabilities, such as:

Capability Lets a process
CAP_CHOWN change file ownership
CAP_DAC_OVERRIDE ignore file permission checks
CAP_NET_BIND_SERVICE bind ports below 1024 (older kernels)
CAP_NET_RAW open raw sockets (ping-style tools, packet crafting)
CAP_NET_ADMIN configure network interfaces, routes, firewall
CAP_SYS_ADMIN a huge grab-bag: mount filesystems, create namespaces, much more
CAP_SYS_PTRACE inspect and debug other processes
CAP_SYS_TIME set the system clock
CAP_SYS_MODULE load kernel modules

A process has several sets of capabilities; the one that decides what it may do right now is the effective set, and the bounding set is the ceiling it can never exceed. In a container, Docker starts the process with a reduced bounding set.

The 14 default capabilities

Docker does not give containers all of root's power. A plain docker run sets the effective and bounding sets to the value a80425fb. We can ask capsh to decode it:

CONSOLE
$ docker run --rm alpine:3 grep CapEff /proc/self/status
CapEff:	00000000a80425fb
$ docker run --rm alpine:3 sh -c 'apk add -q libcap; capsh --decode=a80425fb'
0x00000000a80425fb=cap_chown,cap_dac_override,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_net_bind_service,cap_net_raw,cap_sys_chroot,cap_mknod,cap_audit_write,cap_setfcap

That is exactly 14 capabilities: enough for common programs (chown files, switch user, send signals, bind ports, ping) but not SYS_ADMIN, NET_ADMIN, SYS_PTRACE, SYS_TIME or SYS_MODULE. Compare with the effects you saw in the previous lesson: mount and ip link add failed because those capabilities are missing.

Dropping capabilities

Most applications need none of the 14. A web service that listens on a high port, reads its config and writes to a volume works with an empty set. --cap-drop ALL removes everything:

CONSOLE
$ docker run --rm --cap-drop ALL alpine:3 grep -E '^Cap(Eff|Bnd)' /proc/self/status
CapEff:	0000000000000000
CapBnd:	0000000000000000

Now even root inside the container is almost powerless. Try the one thing that default root can do, changing a file's owner:

CONSOLE
$ docker run --rm alpine:3 sh -c 'touch /f; chown 1234 /f; echo rc=$?; ls -ln /f'
rc=0
-rw-r--r--    1 1234     0                0 Oct 23 15:03 /f
$ docker run --rm --cap-drop ALL alpine:3 sh -c 'touch /f; chown 1234 /f; echo rc=$?'
chown: /f: Operation not permitted
rc=1

(The timestamp in the ls line will differ.) Same user, same command; the only difference is one capability, CAP_CHOWN.

Adding back exactly what you need

The pattern is drop all, add one:

CONSOLE
$ docker run --rm --cap-drop ALL --cap-add CHOWN alpine:3 sh -c 'grep CapEff /proc/self/status; touch /f; chown 1234 /f; echo rc=$?'
CapEff:	0000000000000001
rc=0

CapEff: 1 is bit 0, CAP_CHOWN, and nothing else. Typical add-backs:

  • NET_BIND_SERVICE for a root process that must bind ports under 1024 on an older kernel.
  • CHOWN, SETUID, SETGID for entrypoints that fix permissions and then drop to a user (the official postgres and redis images need these).
  • NET_ADMIN for VPN clients, network tools and containers that configure interfaces. It is powerful, so use it only in the container that needs it:
CONSOLE
$ docker run --rm --cap-add NET_ADMIN alpine:3 sh -c 'ip link add dummy0 type dummy && ip link show dummy0 | head -1'
3: dummy0: <BROADCAST,NOARP> mtu 1500 qdisc noop state DOWN qlen 1000

That command would fail with "Operation not permitted" without the capability (we saw it in the previous lesson). The interface exists only inside that container's network namespace.

Not sure which capabilities an app needs? Start with --cap-drop ALL, run your tests, and add back whatever the error messages ask for (look for Operation not permitted and EPERM in the logs). Document each cap_add with a comment explaining why.

Blocking privilege escalation with no-new-privileges

Some programs gain extra rights when launched: a setuid binary (such as sudo or su) runs with its owner's privileges, and file capabilities work similarly. If an attacker finds one inside your image, they can climb from an ordinary user to root. The flag no-new-privileges tells the kernel that this process and its children can never gain privileges through execve.

To see it, here is an image with sudo installed and a user app allowed to use it:

DOCKERFILE
FROM alpine:3
RUN apk add --no-cache sudo \
 && adduser -D -u 10001 app \
 && echo 'app ALL=(ALL) NOPASSWD: ALL' > /etc/sudoers.d/app
USER app
CMD ["id"]

Without the flag, app becomes root:

CONSOLE
$ docker run --rm demo sudo id
uid=0(root) gid=0(root) groups=0(root),1(bin),2(daemon),3(sys),4(adm),6(disk),10(wheel),11(floppy),20(dialout),26(tape),27(video)

With the flag, the escalation is refused:

CONSOLE
$ docker run --rm --security-opt no-new-privileges demo sudo id
sudo: The "no new privileges" flag is set, which prevents sudo from running as root.
sudo: If sudo is running in a container, you may need to adjust the container configuration to disable the flag.

You can confirm the flag with NoNewPrivs in the process status:

CONSOLE
$ docker run --rm --security-opt no-new-privileges alpine:3 grep NoNewPrivs /proc/self/status
NoNewPrivs:	1

The flag costs almost nothing and breaks only images that depend on setuid helpers (and sudo inside a container is a smell anyway). Make it part of your default flags.

Putting it all together

Combine a non-root user, no capabilities, no escalation, a read-only root filesystem, writable tmpfs only where required, and resource limits. This Compose service ran a simple Python web server on port 8000:

YAML
services:
  app:
    image: python:3.13-slim
    command: ["python", "-m", "http.server", "8000", "--directory", "/tmp"]
    user: "10001:10001"
    read_only: true
    tmpfs:
      - /tmp
    cap_drop:
      - ALL
    security_opt:
      - no-new-privileges:true
    pids_limit: 100
    mem_limit: 128m
    ports:
      - "127.0.0.1:18103:8000"

And what the container looked like from inside:

CONSOLE
$ docker compose exec app sh -c 'id; grep -E "CapEff|NoNewPrivs" /proc/self/status; touch /usr/x; touch /tmp/ok && echo tmp-ok'
uid=10001 gid=10001 groups=10001
CapEff:	0000000000000000
NoNewPrivs:	1
touch: cannot touch '/usr/x': Read-only file system
tmp-ok

It still served requests (HTTP 200 on 127.0.0.1:18103), but an intruder in it has no capabilities, cannot write anywhere except a memory-backed /tmp, cannot escalate, and cannot fork-bomb the host. seccomp, AppArmor and Read-Only Filesystems goes deeper into the filesystem part.

Privileged containers: why to avoid them

docker run --privileged is the opposite of everything above. This is a read-only example; do not run it on a machine you care about:

Terminal
# read-only example: do NOT run this casually
docker run --rm -it --privileged alpine:3 sh

A privileged container gets all capabilities (including SYS_ADMIN, SYS_MODULE and SYS_PTRACE), no seccomp filtering, no AppArmor profile, and access to all host devices. From inside, a root process can mount the host's disks and read or modify the host. The isolation is effectively gone: "privileged container" and "root on the host" are the same thing for practical purposes.

Legitimate uses are narrow: running Docker inside Docker for CI (and even there, prefer rootless alternatives; see Docker in Docker and Socket Access), some hardware or kernel work, and system-level agents. If a tutorial tells you to add --privileged to "make it work", find the one capability or device the program actually needs instead:

Terminal
# read-only example: grant one device and one capability, not everything
docker run --device /dev/ttyUSB0 --cap-add SYS_NICE my-image

Related dangers that are not named "privileged" but grant similar power: mounting /var/run/docker.sock, --pid=host, --network=host with NET_ADMIN, and bind-mounting / or /etc.

Checklist

For every service you run:

  1. USER set to a numeric non-root UID:GID in the Dockerfile, or --user / user: at run time.
  2. --cap-drop ALL, then --cap-add only what you can justify.
  3. --security-opt no-new-privileges.
  4. No --privileged, no Docker socket, no host namespaces unless essential.
  5. Files the app must write belong to it; everything else is read-only.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You start a container with docker run --user 4242 alpine:3 id. What group does the process get?

    With only a UID, Docker keeps the default group, root (GID 0). Group-writable files owned by root then become writable, so always specify both numbers.
  2. 2. How many capabilities does a default container have?

    Docker starts containers with a reduced set of 14 capabilities. Powerful ones such as SYS_ADMIN and NET_ADMIN are missing unless you add them.
  3. 3. What is the recommended pattern for capabilities?

    Least privilege means starting from nothing and adding back specific capabilities with a documented reason.
  4. 4. What does --security-opt no-new-privileges prevent?

    The kernel flag stops a process and its children from gaining more privileges on execve, so setuid escalation is refused.
  5. 5. Why is --privileged dangerous?

    A privileged container has almost none of the isolation layers left. Grant a single device or capability instead.

Summary

  • Run as a numeric non-root user (USER 10001:10001, --user, or user: in Compose); always give both UID and GID.
  • Docker containers get 14 default capabilities; most apps need none. Use --cap-drop ALL and --cap-add for the specific exceptions.
  • --security-opt no-new-privileges blocks setuid-style escalation (NoNewPrivs: 1).
  • Non-root processes can bind low ports inside containers because ip_unprivileged_port_start is 0, but a high internal port is still a good habit.
  • --privileged, the Docker socket and host namespaces remove the isolation layers; avoid them or replace them with a narrow device or capability.
  • Combine the flags with a read-only root filesystem, tmpfs for scratch space and resource limits.

Next: Image Security and Scanning