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 node
WORKDIR /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, and ENTRYPOINT instructions. By default, when we use COPY to add files into our container, those are added as the root user. To sign the copied files to another user or group, we can use the --chown flag.
Change the COPY instruction to the following:
COPY --chown=node:node . .