Running as a non-root user

By default, Docker will run commands inside the container as the root user. This is a security risk. Therefore, we should run our application as a non-root user.

Conveniently, the Node Docker image already has a user called node. We can use the USER instruction to instruct Docker to run the image as the node user instead of root.

Because of this, we should also move our application to a location accessible by the node user.

Update the Dockerfile with the following lines; place them immediately after the FROM instruction:

USER nodeWORKDIR /home/node

We also need to change the COPY instruction:

COPY . .

Although we have set the USER instruction to use the node user, the USER instruction only affects the RUN, CMD

Get Building Enterprise JavaScript Applications now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.