Ship and operate
Run as a non-root user
Reduce the impact of an application compromise by giving the container process only the filesystem access it needs.
8 minute lesson
Many base images start as root inside the container. Isolation helps, but unnecessary root privileges still increase risk.
Use the non-root user supplied by the base image or create one. Make application files readable by that user and writable only where the program truly needs to write. Do not solve permission errors by making everything world-writable.
COPY --chown=node:node --from=build /app/dist ./dist
USER node
CMD ["node", "dist/server.js"]
The user change must match filesystem ownership. Copying files as root and switching users later is fine for read-only application code, but writable paths such as an uploads or cache directory need narrow, explicit ownership. Test both a required write and a forbidden write instead of checking only the numeric UID.
Non-root is one layer of defense. Also avoid unnecessary Linux capabilities, mount filesystems read-only where practical, and do not mount the Docker socket into an application container. Root inside a container is not automatically root on the host, but a kernel or runtime mistake has a much larger impact when the process begins with broad privileges.
Run the image and print its identity with docker run --rm notes-api:prod id.
Lesson completed