Docker Best Practices

Chapter 2 · Practice 1 of 5

Run the container as a non-root user

From Image size and security

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:

  1. Check whether the official image already ships a user (node in Node images).
  2. If not, create one with a fixed UID and group.
  3. Use COPY --chown so the app can read its files.
  4. Switch with USER before CMD.

Verify it with:

bash
docker run --rm your-image id

The output should not print uid=0.

Example

Dockerfile
RUN groupadd --system --gid 10001 app \
    && useradd --system --uid 10001 --gid app app
COPY --chown=app:app . /app
USER app