Skip to main content

Containers and Kubernetes · Intermediate · 17 min

Run containers as a non-root user

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Docker Engine 29.10 · Trivy 0.76.2 · hadolint 2.15.1

You will take a Node.js image that runs as root, move it to a numeric non-root user with one writable folder and an unprivileged port, run it with a read-only filesystem and no capabilities, and prove the fix with Trivy and hadolint.

On this page

Most official base images start as root, and most Dockerfiles never change that. It feels harmless because the process is "inside a container". It is not as separate as it looks. Unless the Docker daemon uses user namespaces, which it does not by default, UID 0 in the container is UID 0 on the host. The container's walls are namespaces, cgroups, a capability list and a seccomp filter. If one of them has a flaw, or someone mounts the wrong host folder or the Docker socket into the container, a root process has far more to work with than an ordinary user.

In this tutorial you start from a small Node.js app whose Dockerfile runs it as root, the way many real projects end up after someone fights a "permission denied" error. You check it with two linters, Trivy and hadolint, and watch both complain. Then you fix it properly: a numeric non-root user, code the app cannot change, one folder it can write to, and a port above 1024. Finally you run it with a read-only root filesystem, no Linux capabilities and no way to gain privileges, and check each of those from inside the container.

Everything lives in ~/nonroot-demo, which you delete at the end.

Step 1 · Install Trivy and hadolint

Trivy is a security scanner. Its trivy config command checks a Dockerfile against a set of rules, and one of them flags images that run as root. hadolint is a Dockerfile linter with its own rule for the same mistake. You will use both, because they do not catch exactly the same things.

Install curl, then download both tools at pinned versions from their GitHub releases, check each download against its published checksum, and install them into /usr/local/bin. The case line picks the right file for an Intel/AMD (amd64) or ARM (arm64) machine. The hadolint binary alone is about 55 MB, so on a metered or prepaid connection run this once, on a good network, and keep the tools:

Bash
sudo apt update
sudo apt install -y curl ca-certificates
mkdir -p ~/nonroot-demo/tools
cd ~/nonroot-demo/tools
case "$(dpkg --print-architecture)" in
  amd64) TRIVY_ARCH=64bit; HADOLINT_ARCH=x86_64 ;;
  arm64) TRIVY_ARCH=ARM64; HADOLINT_ARCH=arm64 ;;
  *) echo "This tutorial covers amd64 and arm64 only"; false ;;
esac
curl -fsSLO "https://github.com/aquasecurity/trivy/releases/download/v0.76.2/trivy_0.76.2_Linux-${TRIVY_ARCH}.tar.gz"
curl -fsSLO "https://github.com/aquasecurity/trivy/releases/download/v0.76.2/trivy_0.76.2_checksums.txt"
grep " trivy_0.76.2_Linux-${TRIVY_ARCH}.tar.gz\$" trivy_0.76.2_checksums.txt | sha256sum -c -
tar -xzf "trivy_0.76.2_Linux-${TRIVY_ARCH}.tar.gz" trivy
sudo install -m 755 trivy /usr/local/bin/trivy
curl -fsSLO "https://github.com/hadolint/hadolint/releases/download/v2.15.1/hadolint-linux-${HADOLINT_ARCH}"
curl -fsSL -o hadolint-checksums.sha256 "https://github.com/hadolint/hadolint/releases/download/v2.15.1/checksums.sha256"
grep " \*hadolint-linux-${HADOLINT_ARCH}\$" hadolint-checksums.sha256 | sha256sum -c -
sudo install -m 755 "hadolint-linux-${HADOLINT_ARCH}" /usr/local/bin/hadolint

Each sha256sum -c line prints the file name followed by OK. If it prints FAILED, stop and download again: the file is not the one the project published.

These two binaries did not come from an Ubuntu package, so apt upgrade never updates them. To upgrade, run the same commands with the new version number from each project's releases page.

Check it worked

Bash
trivy --version
hadolint --version

Trivy prints Version: 0.76.2 (and, after its first scan, the version of its checks bundle). hadolint prints Haskell Dockerfile Linter 2.15.1.

Step 2 · Write the app and a Dockerfile that runs as root

The app is a tiny web server with no dependencies. Each request adds one to a counter stored in a file under data/, and the reply shows the counter and the user ID the process runs as. Writing to a file is the point: it is the thing that usually pushes people back to root.

Bash
mkdir -p ~/nonroot-demo/app
cd ~/nonroot-demo/app
cat > server.js <<'JS'
const http = require('node:http')
const fs = require('node:fs')
const path = require('node:path')

const port = Number(process.env.PORT || 8080)
const counterFile = path.join(__dirname, 'data', 'visits.txt')

const server = http.createServer((req, res) => {
  res.setHeader('content-type', 'application/json')
  try {
    let visits = 0
    if (fs.existsSync(counterFile)) visits = Number(fs.readFileSync(counterFile, 'utf8')) || 0
    visits += 1
    fs.writeFileSync(counterFile, String(visits))
    res.end(JSON.stringify({ uid: process.getuid(), visits }) + '\n')
  } catch (err) {
    res.statusCode = 500
    res.end(JSON.stringify({ uid: process.getuid(), error: err.code }) + '\n')
  }
})

server.listen(port, () => console.log(`Listening on port ${port} as uid ${process.getuid()}`))

// docker stop sends SIGTERM; Node.js as PID 1 has no default handler for it.
process.on('SIGTERM', () => server.close(() => process.exit(0)))
JS

Now the Dockerfile as it often looks after a few rounds of "make it work". The app listens on port 80, writes to /app/data, and someone has added USER root to get past both errors:

Bash
cat > Dockerfile <<'DOCKER'
FROM node:26-slim

WORKDIR /app
COPY server.js ./
RUN mkdir -p /app/data

ENV PORT=80
EXPOSE 80

# Added to fix "permission denied" on /app/data and on port 80.
USER root

CMD ["node", "server.js"]
DOCKER

Leaving out USER altogether gives the same result here: node:26-slim, like most official images, starts as root unless you say otherwise.

Scan the folder with Trivy, showing only high and critical findings. The first run downloads Trivy's checks bundle, which takes a few seconds:

Bash
trivy config --severity HIGH,CRITICAL .

Then lint the Dockerfile with hadolint. --no-fail makes it report problems without returning an error code, which is handy while you read the output; leave it off in CI so a finding fails the build:

Bash
hadolint --no-fail Dockerfile

Check it worked

Trivy reports one failure for Dockerfile, something like DS-0002 (HIGH): Last USER command in Dockerfile should not be 'root'. hadolint prints a line such as Dockerfile:11 DL3002 warning: Last USER should not be root.

The two tools differ in one useful way. Trivy also fails a Dockerfile that has no USER line at all. hadolint's rule only looks at the last USER line you wrote, so a Dockerfile without one passes it silently. That is a good reason to run Trivy as well.

Step 3 · See what root in the container means

Build the root image and run it. Port 80 inside the container is published as port 8081 on your machine, bound to 127.0.0.1 so only you can reach it:

Bash
cd ~/nonroot-demo/app
docker build -t nonroot-demo:root .
docker run -d --name demo-root -p 127.0.0.1:8081:80 nonroot-demo:root
curl -s http://127.0.0.1:8081/

The reply is {"uid":0,"visits":1}. Now look at the same process from the host:

Bash
docker exec demo-root id
ps -o user,pid,cmd -C node

docker exec prints uid=0(root) gid=0(root) groups=0(root). On the host, ps lists the node server.js process under the user root. It is the same kernel and the same UID 0. Docker drops many of root's capabilities by default and adds a seccomp filter, which is why this is not instant host access, but every one of those protections is a layer you are now relying on, and options such as -v /:/host or -v /var/run/docker.sock:/var/run/docker.sock remove them in one line.

Two Docker features change the picture, and both are worth knowing:

  • User namespaces (userns-remap in the daemon settings) map UID 0 in containers to an unprivileged range of host UIDs. It is a daemon-wide setting, and it interacts with volumes and some images, so it is not on by default.
  • Rootless Docker runs the whole daemon and every container as your ordinary user, so even a container escape lands as you, not as root. The cost is some limits: publishing host ports below 1024 needs extra setup, some storage and network options are missing, and it is a separate install. It suits developer machines and shared build hosts well. A non-root user inside the image is still worth having, because the image will also run on rootful Docker and on Kubernetes.

Check it worked

You have seen uid=0 in both the app's reply and docker exec demo-root id. Remove the container before the next step:

Bash
docker rm -f demo-root

Step 4 · Move the image to a numeric non-root user

Rewrite the Dockerfile. The changes:

  • The code is copied in as root and stays owned by root. The app can read server.js but cannot change it, so an attacker who gets code execution cannot quietly rewrite the app.
  • The one folder the app needs to write to, /app/data, is created and handed to UID 1000 in the same RUN line.
  • The app listens on 8080. You can still publish it on any host port, 80 included, with -p; the port inside the container does not need to match.
  • USER 1000:1000 uses numbers, not the name node. The official Node.js images already include a node user with UID 1000, so you reuse it rather than create one. Kubernetes can only check runAsNonRoot: true when the image's user is a number, because it cannot look names up inside the image.
Bash
cd ~/nonroot-demo/app
cat > Dockerfile <<'DOCKER'
FROM node:26-slim

WORKDIR /app

# Code belongs to root: the app can read it but not change it.
COPY server.js ./

# The only folder the app writes to belongs to the app's user.
RUN mkdir -p /app/data && chown 1000:1000 /app/data

ENV PORT=8080
EXPOSE 8080

# The node user in the official Node.js images is UID 1000.
USER 1000:1000

CMD ["node", "server.js"]
DOCKER

When the base image has no user

node:26-slim ships a user. Many images do not: ubuntu, debian and python start with only root. Create a system user with a fixed UID in the Dockerfile, then switch to it by number. A UID of 10001 is unlikely to clash with a real user on the host:

Dockerfile
FROM python:3.15-slim
RUN groupadd --system --gid 10001 app \
 && useradd --system --no-log-init --uid 10001 --gid 10001 --no-create-home app
# ... copy the app and install dependencies here ...
USER 10001:10001

Distroless images go the other way: the :nonroot tags, such as gcr.io/distroless/static-debian13:nonroot, already set the user to nonroot, UID 65532, so you add nothing.

When files you copy in must be writable by the app, give them to the app's user at copy time with COPY --chown=1000:1000 seed.json ./data/. That is cheaper than a later RUN chown -R, which copies every file into a new layer and makes the image larger.

Check it worked

Run both tools again. This time ask Trivy to return an error code if it finds anything, the way you would in CI, and run hadolint without --no-fail:

Bash
trivy config --exit-code 1 --severity HIGH,CRITICAL .
hadolint Dockerfile
echo "Both checks passed"

Trivy's summary for Dockerfile shows no failures, hadolint prints nothing, and the last line is Both checks passed. If either tool still finds a problem, it exits with an error and the echo line is never reached.

Step 5 · Build and run the non-root image

Build the fixed image and run it, publishing port 8080 of the container on port 8082 of your machine:

Bash
cd ~/nonroot-demo/app
docker build -t nonroot-demo:1 .
docker run -d --name demo -p 127.0.0.1:8082:8080 nonroot-demo:1
curl -s http://127.0.0.1:8082/
curl -s http://127.0.0.1:8082/
docker exec demo id

Keeping 8080 inside the container is the portable choice. Docker 20.10 and later let any user bind any port inside a container's own network namespace, so port 80 would happen to work here. That relaxation does not apply with --network host, and other runtimes and platforms may not apply it at all. A port above 1024 works everywhere without asking for anything.

Check it worked

The two curl replies are {"uid":1000,"visits":1} and {"uid":1000,"visits":2}, so the app runs as UID 1000 and can write its counter. docker exec demo id prints uid=1000(node) gid=1000(node) groups=1000(node). On the host, ps -o user,pid,cmd -C node now shows the process under UID 1000 (or whichever host account has that UID, often the first user created on the machine), not under root.

Step 6 · Lock the container down at run time

A non-root user is the base. These five docker run options close most of what is left:

  • --read-only mounts the image's filesystem read-only. Nothing in the container can change its own binaries or configuration.
  • --tmpfs /tmp gives programs that expect a scratch folder one in memory. It is empty on every start.
  • -v demo-data:/app/data puts the counter on a named volume, which is writable and outlives the container. When a new named volume is first mounted, Docker fills it from the image's /app/data, ownership included, so UID 1000 can write to it straight away.
  • --cap-drop ALL removes every Linux capability. The app binds port 8080 and writes its own files, which needs none. If an app really needs one, add back only that one with --cap-add.
  • --security-opt no-new-privileges stops any process in the container from gaining privileges later, for example through a setuid program such as su.

Replace the container with a locked-down one:

Bash
docker rm -f demo
docker run -d --name demo \
  --read-only \
  --tmpfs /tmp \
  -v demo-data:/app/data \
  --cap-drop ALL \
  --security-opt no-new-privileges \
  -p 127.0.0.1:8082:8080 \
  nonroot-demo:1
curl -s http://127.0.0.1:8082/

You can also override the user of any image when you start it with --user, which helps with third-party images that run as root but work without it. nobody (65534) is a safe test user:

Bash
docker run --rm --user 65534:65534 node:26-slim id

The output is uid=65534(nobody) gid=65534(nogroup) groups=65534(nogroup). The catch is the same one you fixed above: folders in that image belong to other users, so the program may not be able to write where it expects to. Bind-mounted host folders have the same issue. A folder you created on the host belongs to your host UID, so either chown it to the container's UID or start the container with --user "$(id -u):$(id -g)".

Check it worked

The curl reply is {"uid":1000,"visits":1}, so the app works with every restriction in place. Check each one from inside:

Bash
docker exec demo sh -c 'touch /app/server.js'
docker exec demo sh -c 'grep -E "^(CapBnd|CapEff|NoNewPrivs)" /proc/1/status'
docker exec demo sh -c 'touch /tmp/scratch && ls -l /tmp/scratch'

The first command fails with touch: cannot touch '/app/server.js': Read-only file system. The second prints CapBnd: 0000000000000000, CapEff: 0000000000000000 and NoNewPrivs: 1. CapBnd, the bounding set, is the line that shows the drop: without --cap-drop ALL it shows Docker's default set, for example 00000000a80425fb. CapEff is zero either way, because the kernel clears a non-root process's effective capabilities when it starts, so on its own it proves nothing about --cap-drop. The third creates a file in the in-memory /tmp and lists it, owned by node.

Step 7 · Clean up

Remove the container, the images, the volume and the demo folder:

Bash
docker rm -f demo
docker rmi nonroot-demo:1 nonroot-demo:root
docker volume rm demo-data

The node:26-slim base image is still on your machine. Remove it too if no other project uses it:

Bash
docker rmi node:26-slim

Your shell is still inside the demo folder, so move out of it first:

Bash
cd ~
rm -rf ~/nonroot-demo

Keep trivy and hadolint if you will scan images next, as in /tutorials/scan-container-images-for-vulnerabilities-with-trivy. Otherwise remove them and Trivy's cache:

Bash
sudo rm -f /usr/local/bin/trivy /usr/local/bin/hadolint
rm -rf ~/.cache/trivy

Check it worked

docker ps -a --filter name=demo lists no containers, docker volume ls no longer shows demo-data, and ls ~/nonroot-demo reports that the folder does not exist.

Next steps

  • Build the same habits into a Node.js image from the start: /tutorials/write-a-dockerfile-for-a-node-app
  • Scan the image's packages for known vulnerabilities, not just its Dockerfile: /tutorials/scan-container-images-for-vulnerabilities-with-trivy
  • Enforce non-root users, dropped capabilities and no privilege escalation for a whole Kubernetes namespace: /tutorials/lock-down-the-snip-namespace-with-network-policies
  • Ship a Go service on a distroless nonroot base: /tutorials/package-the-snip-go-api-in-a-distroless-image

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.