# Run containers as non-root (USER, cap_drop, read_only)

> Running a container as non-root means its main process uses an unprivileged user, drops extra Linux capabilities and cannot write to its own filesystem, which limits damage from a compromise.

URL: https://levelrail.com/learn/security/run-containers-as-non-root/
Updated: 2026-11-27

Most images start their process as root unless told otherwise. That is convenient and also a bad default. Root inside a container is not the same as root on the host, but it is closer than you want, and a bug in the app, the runtime or the kernel gives an attacker more to work with. The goal of this lesson is to give each container the least power it needs: an unprivileged user, a short capability list, no way to gain privileges and a filesystem it cannot rewrite.

## How it works

Four independent controls stack up:

1. **User.** The process runs as a numeric user ID, not 0.
2. **Capabilities.** Linux splits root's powers into capabilities such as `NET_BIND_SERVICE` or `CHOWN`. Docker gives containers a default subset. `cap_drop: [ALL]` removes them all, and `cap_add` returns only what the app needs.
3. **no-new-privileges.** A kernel flag that stops a process and its children from gaining privileges, for example through a setuid binary.
4. **Read-only root filesystem.** The container image layer cannot be modified at runtime, so a compromised process cannot drop a tool or edit app code. Writable paths are provided explicitly with `tmpfs` or volumes.

Files from the host keep their numeric owner and group inside the container. That is why volume permissions are the usual practical problem, and why [bind mounts versus volumes](https://levelrail.com/learn/docker/bind-mounts-vs-volumes-permissions/)) matters here.

## Step 1: Set the user in the Dockerfile

Create an unprivileged user and switch to it as the last step before the start command:

```dockerfile
FROM node:22-slim
WORKDIR /app
COPY --chown=10001:10001 . .
RUN npm ci --omit=dev
USER 10001:10001
CMD ["node", "server.js"]
```

A numeric ID avoids needing an `/etc/passwd` entry, and works in minimal images. Some official images already ship a non-root user, for instance named `node`, so check the image documentation before creating your own. Write a Dockerfile first if you have not: [write your first Dockerfile](https://levelrail.com/learn/docker/write-your-first-dockerfile/)).

## Step 2: Set or override the user in Compose

For images you do not build, set the user at run time:

```yaml
services:
  app:
    image: myapp:1.0
    user: "10001:10001"
```

The ID must be able to read the app files and write wherever the app stores data. Test by starting it and reading `docker compose logs app`.

## Step 3: Fix volume ownership

If the app now fails with `EACCES` or `permission denied` on its data folder, give the folder to that ID:

```bash
sudo chown -R 10001:10001 ./data
```

Named volumes are created root-owned unless the image sets ownership on the path first. The lesson [fix permission denied on a Docker volume](https://levelrail.com/learn/troubleshooting/fix-permission-denied-on-a-docker-volume/)) walks through this in detail. Avoid the shortcut `chmod 777`, because it gives every user on the host write access.

## Step 4: Drop capabilities and block privilege gain

```yaml
services:
  app:
    image: myapp:1.0
    user: "10001:10001"
    cap_drop:
      - ALL
    cap_add:
      - NET_BIND_SERVICE
    security_opt:
      - no-new-privileges:true
```

Add `NET_BIND_SERVICE` only if the app binds a port below 1024 inside the container. Better, have the app listen on a high port such as 8080 and drop the capability altogether, publishing it as you like. If the container fails at start, read the error, add back the single capability it names and try again. Do this one at a time. A long `cap_add` list defeats the purpose.

## Step 5: Make the root filesystem read-only

```yaml
services:
  app:
    image: myapp:1.0
    read_only: true
    tmpfs:
      - /tmp
    volumes:
      - app-data:/data

volumes:
  app-data:
```

Now the process can write only to `/tmp` (in memory) and `/data`. Many apps want to write caches or pid files in odd places. Run it, watch the logs for `Read-only file system` messages and add a `tmpfs` or volume for each path it needs. See [Docker volumes](https://levelrail.com/learn/docker/docker-volumes-and-persistent-data/)) for persistent data.

## Step 6: Avoid the big shortcuts

Two settings undo most of this work:

- `privileged: true` (or `--privileged`) gives the container almost every capability and access to host devices. Do not use it for ordinary apps. If a container needs a device, map that one device.
- Mounting `/var/run/docker.sock` lets the container control Docker, which amounts to root on the host. Only mount it into a tool that truly needs it. A read-only mount does not help, because the API stays fully usable. Prefer a socket proxy that exposes only the calls you allow.

## Check it worked

```bash
docker compose up -d
docker compose exec app id
docker inspect --format '{{.HostConfig.CapDrop}} {{.HostConfig.ReadonlyRootfs}} {{.HostConfig.SecurityOpt}}' $(docker compose ps -q app)
docker top $(docker compose ps -q app)
```

`id` should show your numeric user and not 0. `inspect` should show the dropped capabilities, `true` for the read-only root and the `no-new-privileges` option. `docker top` shows the process user as seen from the host. Then request the app the way a user would and confirm it works.

## Edge cases and gotchas

- **Images without a shell.** `docker compose exec app id` fails on distroless images. Use `docker inspect` instead.
- **Rootless Docker is different.** Running the Docker daemon itself rootless is another layer. This lesson covers per-container settings.
- **Reverse proxies.** A proxy that binds ports 80 and 443 inside the container needs `NET_BIND_SERVICE`, or run it on high ports behind the published mapping.
- **Databases.** Official database images start as root briefly to fix ownership, then drop to their own user. Overriding `user:` there can break their init scripts, so read the image notes first.
- **Group IDs.** Files writable by group only need the right `group_add` or a matching group ID.
- **Healthchecks.** A read-only filesystem can break healthchecks that write temp files. See [Docker healthchecks](https://levelrail.com/learn/docker/docker-healthchecks/)).

## Troubleshooting

| Symptom | Likely cause | Fix |
| --- | --- | --- |
| `EACCES: permission denied, open '/data/x'` | Volume owned by root | `chown` the folder to the container UID |
| `bind: permission denied` on port 80 | Low port needs a capability | Listen on 8080 or add `NET_BIND_SERVICE` |
| `Read-only file system` | read_only is on and the app writes there | Add a `tmpfs` or volume for that path |
| `operation not permitted` on chown | CHOWN capability dropped | Fix ownership in the image build instead |
| `unable to find user 10001: no matching entries in passwd file` | Name used instead of ID, or no entry | Use numeric `user: "10001:10001"` |
| Container exits at once after dropping caps | App needs one capability | Read logs, add back only that one |
| `docker: Error response from daemon: unable to find user` | Typo in the user name | Check the Dockerfile and the image's users |

## Quick reference

```yaml
services:
  app:
    user: "10001:10001"
    read_only: true
    tmpfs: [/tmp]
    cap_drop: [ALL]
    cap_add: [NET_BIND_SERVICE]   # only if needed
    security_opt:
      - no-new-privileges:true
```

## Related lessons

- [Write your first Dockerfile](https://levelrail.com/learn/docker/write-your-first-dockerfile/)): where USER goes in the build.
- [Bind mounts vs volumes and permissions](https://levelrail.com/learn/docker/bind-mounts-vs-volumes-permissions/)): why UIDs matter on mounted data.
- [Fix permission denied on a Docker volume](https://levelrail.com/learn/troubleshooting/fix-permission-denied-on-a-docker-volume/)): the repair steps.
- [Scan Docker images with Trivy](https://levelrail.com/learn/security/scan-docker-images-with-trivy/)): find known vulnerabilities in what you run.
- [Manage secrets on servers and containers](https://levelrail.com/learn/security/manage-secrets-on-servers-and-containers/)): keep credentials away from the container filesystem.

## Next

Continue with [Scan Docker images with Trivy](https://levelrail.com/learn/security/scan-docker-images-with-trivy/)).

## Frequently asked questions

### Why should containers not run as root?

Root inside a container is still root on the kernel, only with fewer capabilities. If an attacker escapes through a bug, a non-root process starts with far less power, and a root process may write to mounted host paths.

### How do I run a container as a non-root user?

Add a USER instruction to the Dockerfile after creating the user, or set user: "1000:1000" in Compose or --user 1000:1000 on docker run. Then make sure mounted volumes are writable by that ID.

### What does no-new-privileges do?

The security option no-new-privileges stops a process from gaining more privileges through setuid binaries or file capabilities. It is cheap to enable and rarely breaks apps.

### Is docker run --privileged ever acceptable?

Almost never for an ordinary app. It gives the container nearly full access to the host's devices and kernel features. Use a specific capability or device mapping instead.


## Sources

- [Docker docs, Dockerfile USER instruction](https://docs.docker.com/reference/dockerfile/#user)
- [Docker docs, runtime privilege and Linux capabilities](https://docs.docker.com/engine/containers/run/#runtime-privilege-and-linux-capabilities)
