Chapter 2 · Practice 1 of 5
Run the container as a non-root user
Why it matters
By default a container process runs as root. If an attacker breaks into your app, root inside the container makes escaping or damaging mounted files far easier. Both Docker and the OWASP Docker Security Cheat Sheet say to run services as an unprivileged user.
How to set it up:
- Check whether the official image already ships a user (
nodein Node images). - If not, create one with a fixed UID and group.
- Use
COPY --chownso the app can read its files. - Switch with
USERbeforeCMD.
Verify it with:
bash
docker run --rm your-image id
The output should not print uid=0.
Example
RUN groupadd --system --gid 10001 app \
&& useradd --system --uid 10001 --gid app app
COPY --chown=app:app . /app
USER app