Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 111 ยท Containers in Depth

Users and Permissions

Run containers as a non-root user, understand UID and GID numbers, fix 'Permission denied' on volumes and bind mounts, and lock down the filesystem with --read-only.

Almost every container you have started so far ran its program as root. It is the default, and it works, which is exactly why so many images keep doing it. But root inside a container is a much stronger starting point for an attacker than an ordinary user, and, as soon as you mount a directory from the host or share a volume between containers, "who owns this file?" becomes a question that decides whether your application works at all.

This lesson explains the identity model in plain terms: what a user ID really is, how --user and USER change it, why files in volumes show unexpected owners, how to fix the infamous "Permission denied" without resorting to chmod 777, and how a read-only root filesystem takes the idea one step further. All outputs were produced on a real Docker Engine with small Alpine, Ubuntu and Python images. If you have not seen USER in a Dockerfile yet, read WORKDIR, USER, EXPOSE and LABEL first; here we go deeper.

Users are just numbers

A Linux process runs with a numeric user ID (UID) and group ID (GID). Names such as root or app are only labels that /etc/passwd and /etc/group map to those numbers. And here is the point that explains most container permission problems: containers share the host's kernel, and the kernel only knows numbers. Each image carries its own /etc/passwd, so the same number can have different names in different images, or no name at all.

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

--user (or -u) changes the identity of the main process. Alpine has no account for 1000, so there is no name to print, but the process works fine: the kernel needs only the number. To see the "same number, different name" effect, we create a file owned by 1000 in a volume and list it from two images:

CONSOLE
$ docker run --rm -v demo:/w alpine:3.22 sh -c 'touch /w/report.txt && chown 1000:1000 /w/report.txt'
$ docker run --rm -v demo:/w alpine:3.22 ls -l /w
-rw-r--r--    1 1000     1000             0 ... report.txt
$ docker run --rm -v demo:/w ubuntu:24.04 ls -l /w
-rw-r--r-- 1 ubuntu ubuntu 0 ... report.txt
$ docker run --rm ubuntu:24.04 id ubuntu
uid=1000(ubuntu) gid=1000(ubuntu) groups=1000(ubuntu),4(adm),20(dialout),...

It is one and the same file. Ubuntu 24.04 happens to ship a user named ubuntu with UID 1000; Alpine does not. When you debug ownership, always use ls -ln (numeric) and compare numbers, not names.

What you get when you give no group

A detail that bites people: --user 1000 without a group does not mean group 1000.

CONSOLE
$ docker run --rm --user 1000 alpine:3.22 sh -c 'id; echo HOME=$HOME; cd; pwd; touch x; echo $?'
uid=1000 gid=0(root) groups=0(root)
HOME=/
/
touch: x: Permission denied
1

With a bare number and no matching account, the process gets GID 0 (the root group) and HOME=/, which is not writable by it. Always write --user UID:GID explicitly, and give the user a home directory (or point HOME somewhere writable) if your tool wants to write config or cache files there. You can add supplementary groups with --group-add:

CONSOLE
$ docker run --rm --user 1000:1000 --group-add 20 alpine:3.22 id
uid=1000 gid=1000 groups=20(dialout),1000

If you name a user that does not exist in the image, Docker refuses to start the container:

CONSOLE
$ docker run --rm --user bob alpine:3.22 id
docker: Error response from daemon: unable to find user bob: no matching entries in passwd file

Names are resolved inside the image's /etc/passwd; numbers never need a lookup. That is why numeric IDs are the portable choice in Dockerfiles and orchestrator settings.

Why run as non-root?

What does a root process inside a container do that an ordinary user cannot? It can write to any file in the image's filesystem (including your application code and system binaries), read root-only files, install packages with the package manager, and change ownership of anything it can reach. Compare:

CONSOLE
$ docker run --rm --user 1000 alpine:3.22 sh -c 'touch /etc/x'
touch: /etc/x: Permission denied
$ docker run --rm --user 1000 alpine:3.22 sh -c 'cat /etc/shadow'
cat: can't open '/etc/shadow': Permission denied
$ docker run --rm --user 1000 alpine:3.22 sh -c 'ls -l /etc/shadow; touch /tmp/ok && echo tmp-ok'
-rw-r-----    1 root     shadow         260 ... /etc/shadow
tmp-ok

The non-root process can still do its normal work (it wrote to /tmp) but cannot tamper with the system. If an attacker finds a bug in your web app, they inherit exactly those limits. They also cannot use many kernel features that need root, and a container escape is much harder to turn into full control of the host. Root in a container is not root on the host by default (Docker drops many capabilities, see Non-Root Users and Capabilities), but "mostly contained root" is a worse place to start than "ordinary user".

Running as non-root reduces the damage of a compromise; it does not make a container a secure sandbox on its own. Treat it as one layer in Container Security Basics.

Do low ports need root?

Traditionally, binding to ports below 1024 required root, so people ran web servers as root "because it listens on 80". Modern Docker sets the kernel setting net.ipv4.ip_unprivileged_port_start to 0 inside containers, so this is no longer true:

CONSOLE
$ docker run --rm --user 1000 alpine:3.22 cat /proc/sys/net/ipv4/ip_unprivileged_port_start
0
$ docker run --rm --user 1000 python:3-alpine python -c "
import socket
s=socket.socket(); s.bind(('0.0.0.0',80)); print('bound 80 as uid 1000')"
bound 80 as uid 1000

(Docker only controls this inside the container's network namespace; with --network host the host's value applies.) The reason the official nginx image fails as a non-root user is different: it wants to write to directories owned by root.

CONSOLE
$ docker run -d --name ng --user 1000 nginx:alpine
$ docker logs ng 2>&1 | tail -2
2026/.. [emerg] 1#1: mkdir() "/var/cache/nginx/client_temp" failed (13: Permission denied)
nginx: [emerg] mkdir() "/var/cache/nginx/client_temp" failed (13: Permission denied)
$ docker ps -a --filter name=ng --format '{{.Status}}'
Exited (1) 2 seconds ago

You will meet this often: a program that quietly assumed it was root. The fix is to give it directories it owns (or use an image designed for non-root, such as the "unprivileged" nginx variants) rather than going back to root.

Building a non-root image

On Debian and Ubuntu based images create a system user with groupadd and useradd; on Alpine use addgroup and adduser (shown in WORKDIR, USER, EXPOSE and LABEL). Pick a fixed numeric UID and GID well above the range used by system accounts, such as 10001, so file ownership is the same on every machine.

Python
# app.py
import os
import tempfile

print("uid:", os.getuid(), "gid:", os.getgid())
with tempfile.NamedTemporaryFile(dir="/tmp") as f:
    print("scratch file in /tmp:", f.name.startswith("/tmp/"))
try:
    open("/app/cache.db", "w")
except OSError as err:
    print("cannot write /app:", err.strerror)
DOCKERFILE
FROM python:3-slim
RUN groupadd --system --gid 10001 app \
 && useradd --system --uid 10001 --gid app --no-create-home --shell /usr/sbin/nologin app
WORKDIR /app
COPY app.py .
USER app:app
CMD ["python", "app.py"]
CONSOLE
$ docker build -t nonroot .
$ docker run --rm nonroot
uid: 10001 gid: 10001
scratch file in /tmp: True
cannot write /app: Permission denied
$ docker run --rm nonroot id
uid=10001(app) gid=10001(app) groups=10001(app)

Three design choices are worth copying:

  • --no-create-home and --shell /usr/sbin/nologin: this account exists only to own a process. Nobody logs in as it.
  • /app and the code in it are owned by root and not writable by app. A compromised process cannot rewrite its own code. The program can still read it, because the default mode is world-readable.
  • Only the directories the app needs to write (here /tmp) are writable. If the app needs a data directory, create just that one and chown it, ideally with COPY --chown or RUN install -d -o app -g app /data.

To check which user an image will use, and to override it for one run:

CONSOLE
$ docker image inspect -f 'image user: [{{.Config.User}}]' nonroot alpine:3.22
image user: [app:app]
image user: []
$ docker run -d --name u --user 10001 alpine:3.22 sleep 100
$ docker exec u id
uid=10001 gid=0(root) groups=0(root)
$ docker exec --user root u id -u
0

An empty [] means "root". docker exec inherits the container's user, and docker exec --user root lets you open a root shell in a running container, which is useful for debugging but also a reminder that USER is a default, not a lock. Anyone who can talk to the Docker daemon can become root in any container (see Securing the Docker Daemon).

Volumes, bind mounts and ownership

Now the part that causes most "Permission denied" tickets. File ownership is just numbers stored on the file, and they follow the data wherever it is mounted.

Named volumes copy ownership from the image (once)

When you mount a new, empty named volume over a directory that exists in the image, Docker first copies the image's content (and its ownership) into the volume. After that, the volume keeps whatever is in it. Take this image: /data was created and given to app, while /logs was created but left owned by root:

DOCKERFILE
FROM alpine:3.22
RUN addgroup -S -g 10001 app && adduser -S -u 10001 -G app app \
 && mkdir -p /data /logs && chown app:app /data
USER app
WORKDIR /home/app
CMD ["sh", "-c", "id; ls -ld /data /logs; touch /data/a && echo data-ok; touch /logs/a || echo logs-denied"]
CONSOLE
$ docker run --rm -v vol1:/data -v vol2:/logs permdemo
uid=10001(app) gid=10001(app) groups=10001(app),10001(app)
drwxr-xr-x    2 app      app           4096 ... /data
drwxr-xr-x    2 root     root          4096 ... /logs
data-ok
touch: /logs/a: Permission denied
logs-denied

The empty volumes inherited the ownership of the directories in the image. That is why preparing the directory in the Dockerfile (mkdir + chown before USER) is the cleanest fix for a volume the app writes to.

But if you mount a volume on a path the image does not contain, there is nothing to copy and the mount point is created owned by root:

CONSOLE
$ docker run --rm -v vol3:/other --user 10001 alpine:3.22 sh -c 'ls -ld /other; touch /other/a || echo denied'
drwxr-xr-x    2 root     root          4096 ... /other
touch: /other/a: Permission denied
denied

One way out is a one-shot root container that fixes the ownership of the volume, after which the real container works:

CONSOLE
$ docker run --rm -v vol3:/other alpine:3.22 chown 10001:10001 /other
$ docker run --rm -v vol3:/other --user 10001 alpine:3.22 sh -c 'ls -ld /other; touch /other/a && echo ok'
drwxr-xr-x    2 10001    10001         4096 ... /other
ok

In Compose the same trick is a short-lived init service that runs chown before the app starts (see Startup Order and Health).

Files created by root cannot be edited by others

A very common pipeline: one step builds files as root, a later step runs as a normal user and cannot touch them.

CONSOLE
$ docker run --rm -v work:/work alpine:3.22 sh -c 'echo built-by-root > /work/out.txt; ls -ln /work'
total 4
-rw-r--r--    1 0        0               14 ... out.txt
$ docker run --rm -v work:/work --user 1000:1000 alpine:3.22 sh -c 'cat /work/out.txt; echo x >> /work/out.txt || echo cannot-edit; rm /work/out.txt || echo cannot-delete'
built-by-root
sh: can't create /work/out.txt: Permission denied
cannot-edit
rm: can't remove '/work/out.txt': Permission denied
cannot-delete

Reading works (world-readable mode), writing and deleting do not: the kernel looks at the numbers (user 1000 is neither the owner 0, nor in group 0) and the permission bits (rw-r--r--) and says no.

Bind mounts: your host account matters

With a bind mount there is no copying at all. The container sees the host directory exactly as it is. On Linux, that means files appear with the host's real UIDs, and a container running as root creates root-owned files in your project folder:

CONSOLE
# Linux host, running as the user "alice" (uid 1000)
$ mkdir out
$ docker run --rm -v "$PWD/out:/out" alpine:3.22 touch /out/by-root.txt
$ ls -ln out
-rw-r--r-- 1 0 0 0 ... by-root.txt
$ rm out/by-root.txt
rm: cannot remove 'out/by-root.txt': Permission denied

(That output is typical of a Linux host; it is shown read-only because the Docker Desktop machine used for this lesson behaves differently, as explained below.) The standard fix is to run the container as your own account:

Terminal
docker run --rm --user "$(id -u):$(id -g)" -v "$PWD/out:/out" alpine:3.22 touch /out/by-me.txt

Now the file belongs to you on the host as well. For development containers that must write into your source tree, passing your own UID:GID (or a Compose user: setting with variables) is the simplest, most portable solution; see Bind Mounts.

Docker Desktop (Windows and macOS) behaves differently. The containers run inside a Linux virtual machine, and host folders are shared through a translation layer that shows files as world-accessible. On the Windows machine used to test this lesson, a bind-mounted folder looked like this inside the container, and writes from any UID succeeded:

CONSOLE
$ docker run --rm -v "$PWD/shared:/shared" alpine:3.22 ls -ln /shared
-rwxrwxrwx    1 0        0                3 ... host.txt
$ docker run --rm -v "$PWD/shared:/shared" --user 5555:5555 alpine:3.22 sh -c 'echo more >> /shared/host.txt && echo appended'
appended

That is convenient, but it hides ownership bugs: a setup that works on your laptop can fail on a Linux CI server or production host. Test non-root setups at least once on Linux, or use named volumes, which behave the same everywhere.

Decision guide

Situation Best approach
App writes to a directory baked into the image mkdir + chown that directory in the Dockerfile, then mount a named volume there
App writes to a fresh volume at a path the image lacks Create the path in the image first, or fix ownership with a one-shot root container
Dev container writes into your project (Linux) --user "$(id -u):$(id -g)"
Many different host users or rootless setups Look at user namespaces (userns-remap) or rootless Docker, covered in seccomp, AppArmor and Read-Only Filesystems
Quick experiment Leave it as root, but do not ship that

Never "fix" a permission error with chmod -R 777. It removes the protection for every process that can see the files, and it hides the real problem, which is a UID mismatch.

Read-only root filesystems

Once the app runs as non-root and writes in only a few places, you can make everything else unwritable at the kernel level. --read-only mounts the container's root filesystem read-only; even root cannot change it:

CONSOLE
$ docker run --rm --read-only alpine:3.22 sh -c 'touch /x'
touch: /x: Read-only file system
$ docker run --rm --read-only alpine:3.22 sh -c 'echo hi > /tmp/x'
sh: can't create /tmp/x: Read-only file system

Programs usually need a scratch space. Give them a small in-memory tmpfs (more in tmpfs and In-Memory Storage), and keep volumes for real data:

CONSOLE
$ docker run --rm --read-only --tmpfs /tmp alpine:3.22 sh -c 'echo hi > /tmp/x && echo tmp-ok; touch /etc/x'
tmp-ok
touch: /etc/x: Read-only file system
$ docker run --rm --read-only -v work:/work alpine:3.22 sh -c 'echo ok > /work/new.txt && echo volume-still-writable; touch /etc/x'
volume-still-writable
touch: /etc/x: Read-only file system
$ docker run --rm --read-only --tmpfs /tmp:rw,size=1m,mode=1777 --user 1000 alpine:3.22 sh -c 'echo ok > /tmp/f && echo ok-as-1000; df -h /tmp | tail -1'
ok-as-1000
tmpfs                     1.0M      4.0K   1020.0K   0% /tmp

Our nonroot Python image shows how the pieces fit. Run it with the default writable filesystem, then read-only with and without a tmpfs:

CONSOLE
$ docker run --rm --read-only --tmpfs /tmp nonroot
uid: 10001 gid: 10001
scratch file in /tmp: True
cannot write /app: Read-only file system
$ docker run --rm --read-only nonroot 2>&1 | tail -2
  File "/usr/local/lib/python3.x/tempfile.py", line 256, in _mkstemp_inner
OSError: [Errno 30] Read-only file system: '/tmp/tmp...'

Notice the error message for /app changed from "Permission denied" (file ownership) to "Read-only file system" (the mount), and the second run crashed because Python's tempfile had nowhere to put its file. That crash is the typical cost of --read-only: find every path your program writes (temp files, caches, PID files, sockets, ~/.cache) and give each a volume or tmpfs. Once it works, an attacker who gets code execution cannot drop a binary into the filesystem or modify your application. In Compose use read_only: true and tmpfs: on the service.

Make --read-only part of your test run, not an afterthought. Start the container read-only in CI; the first failure tells you exactly which directory needs a tmpfs or volume.

Pitfalls checklist

  • USER app after WORKDIR and COPY is fine, but remember WORKDIR creates missing directories as root. Create writable directories explicitly.
  • USER placed before RUN apt-get install makes the install fail (non-root cannot install packages). Install first as root, switch last.
  • Use numeric UID:GID in orchestrator security settings; names are not resolved there.
  • Do not assume a home directory: pass HOME or create the account with one when a tool caches data.
  • docker cp and files written by docker exec --user root can leave root-owned files in volumes; check with ls -ln.
  • Official images have their own non-root accounts, and the numbers differ: in the Alpine variants postgres is UID 70, redis is 999 and nginx is 101. Use the image's account rather than inventing one when you can, and never assume a UID is the same across images or variants.
  • A named volume copies ownership only the first time it is empty; changing the image's chown later does not update existing volumes.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A file in a volume is listed as owned by ubuntu in one container and by 1000 in another. Why?

    Ownership is stored as a number (here 1000). The Ubuntu image has an account named ubuntu with UID 1000, while Alpine has none, so it prints the bare number. Compare numbers with ls -ln.
  2. 2. What does docker run --user 1000 alpine:3.22 id print for the group?

    Without a matching account and without an explicit :GID, the process gets group 0. Write --user 1000:1000 to avoid surprises.
  3. 3. Your non-root app gets 'Permission denied' writing to a fresh named volume mounted at a path that does not exist in the image. What is the cleanest fix?

    A new volume inherits the image directory's ownership. Creating and chowning the directory in the image means the volume starts out owned by the app user. Running as root or chmod 777 only hides the problem.
  4. 4. What does docker run --read-only do?

    The root filesystem becomes read-only for every process, even root. Mounted volumes and --tmpfs paths remain writable, which is why you add them for temp files and data.
  5. 5. On a Linux host, a container running as root writes into a bind-mounted project folder. What do you see on the host, and what is the usual fix?

    Bind mounts show real host UIDs, so a root process creates root-owned files. Running the container as your own UID:GID makes the files yours. Docker Desktop on Windows and macOS hides this with a translation layer.

Summary

  • The kernel knows only numeric UIDs and GIDs; names come from each image's /etc/passwd. Debug ownership with ls -ln.
  • Run applications as a non-root user with a fixed numeric ID (USER 10001:10001); install packages first as root and switch last.
  • --user 1000 alone gives GID 0 and HOME=/; write --user UID:GID and provide a writable home when needed.
  • Docker allows non-root processes to bind low ports, so "needs port 80" is no reason to stay root.
  • A new named volume inherits ownership from the image path it is mounted on; mount points the image lacks are root-owned. Prepare directories in the Dockerfile.
  • Bind mounts expose host ownership on Linux: use --user "$(id -u):$(id -g)" for dev containers. Docker Desktop on Windows and macOS masks this, so test on Linux too.
  • --read-only plus --tmpfs and volumes for the few writable paths shuts off a whole class of attacks. Never use chmod 777 as a fix.

Next: Debugging Containers