Container User Restriction by UID/GID
Running containers as root is among the most frequent production vulnerabilities. Explicitly binding a user via UID/GID narrows the attack surface and prevents accidental system file overwrite. This note covers practical ways to assign and verify container users.
Why restrict the user
Containers default to root (UID 0). Any application vulnerability grants full control inside the container and potentially over the host filesystem when mounted. Limiting the user is a basic defense‑in‑depth step. Even if compromised, rights are limited to that user’s permissions. Orchestrators and monitoring tools also expect non‑root identifiers.
UID/GID: how it works
In Linux every process has numeric UID and GID. Inside a container the default mapping is root → 0. Explicitly setting USER 1000:1000 ties the container user to a specific host user. nobody (65534) is often used for anonymous tasks but is not suited for a main application. Remember: UID/GID are just numbers; names are resolved via /etc/passwd inside the image. If the host has no user with UID 1000, the container user appears as 1000 or uid‑1000 in dependencies.
How to set user in Dockerfile
Directives at the end of Dockerfile:
Or by name if present in the image: USER appuser. Order matters: USER must follow RUN, COPY etc., otherwise subsequent layers remain root. Common variants:
| Directive | Result |
|---|---|
USER 0 | root user (not recommended) |
USER 1000:1000 | numeric UID/GID |
USER appuser | name from image (if present) |
How to set user in docker-compose
In docker-compose.yml use the user key:
Or with explicit name and numeric ID: user: "1000:1000". Example:
Important: compose passes this to docker run --user, so inside the container numeric IDs are used directly.
Checking file access rights
After launch verify the app writes to the correct directories, not executable files. Commands:
docker exec -u 1000:1000 container ls -la /app/data— see ownershipstat /app/data— show UID/GIDidinside container — check current user
Typical mistake: the container tries to write to /app/bin/app, resulting in Permission denied or, if the binary is writable, image contamination.
What to do if the application needs write rights
If the app must modify files:
- Set the directory owner to the user with the needed UID/GID on the host:
chown 1000:1000 /app/data - Use groups: add the user to a group with directory rights, or create a dedicated app group
- Mount a volume with
uid/gidflags:docker run -v /host/path:/container/path:rw,uid=1000,gid=1000 - The container must not have write access to its executable files. This is a vector for image contamination.
- If the application requires root to start, consider splitting into privileged and unprivileged containers via socket communication or unix‑sockets.