Node.js › Docker & Containerization for Node.js

Why is it considered a security best practice to run a Node.js Docker container as a non-root user?

Advanced

Answer

By default, a Docker container's process runs as root unless explicitly configured otherwise -- if an attacker manages to exploit a vulnerability in the application and achieve code execution inside the container, running as root gives them significantly more capability within that container (and, depending on the container runtime's own configuration, potentially an easier path toward escaping to the host); explicitly switching to a dedicated non-root user limits the practical impact of such a compromise, following the principle of least privilege.
FROM node:20-alpine
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
WORKDIR /app
COPY --chown=appuser:appgroup . .
USER appuser
CMD ["node", "server.js"]

# Official Node.js images also ship a pre-created 'node' user you can use directly:
# USER node
Real-world example A security audit of a company's container images flags several running as root unnecessarily; switching each Dockerfile to use the pre-built 'node' user included in the official Node.js base images (via a simple USER node instruction) closes this finding across the fleet with minimal code changes.

Common follow-ups: What specific additional capabilities does a root process inside a container have that a non-root process doesn't?;How do file permission issues sometimes arise when switching to a non-root user, and how do you resolve them?