From f91ce5296db7b04decfa0edb23406fccfc70722b Mon Sep 17 00:00:00 2001 From: Jason Allan Date: Sat, 8 Mar 2025 14:36:19 +0000 Subject: [PATCH] Set `node` as user in Dockerfile + some refactoring The most important part of these changes is deprivileging the user from `root` to `node` to mitigate escalation attacks. https://github.com/nodejs/docker-node/blob/main/docs/BestPractices.md#non-root-user Also, this refactors for simplicity by reducing much of the repetition --- default/Dockerfile | 29 ++++++++++++----------------- 1 file changed, 12 insertions(+), 17 deletions(-) diff --git a/default/Dockerfile b/default/Dockerfile index 207bf93..69cd954 100644 --- a/default/Dockerfile +++ b/default/Dockerfile @@ -1,22 +1,17 @@ -FROM node:20-alpine AS development-dependencies-env -COPY . /app +FROM node:20-alpine AS base +USER node WORKDIR /app -RUN npm ci - -FROM node:20-alpine AS production-dependencies-env COPY ./package.json package-lock.json /app/ -WORKDIR /app -RUN npm ci --omit=dev -FROM node:20-alpine AS build-env +FROM base AS staging +RUN npm ci COPY . /app/ -COPY --from=development-dependencies-env /app/node_modules /app/node_modules -WORKDIR /app -RUN npm run build +# Build app and prepare `node_modules` for production +# This second install will remove the omitted deps automatically +RUN npm run build \ + && npm ci --omit=dev -FROM node:20-alpine -COPY ./package.json package-lock.json /app/ -COPY --from=production-dependencies-env /app/node_modules /app/node_modules -COPY --from=build-env /app/build /app/build -WORKDIR /app -CMD ["npm", "run", "start"] \ No newline at end of file +FROM base +COPY --from=staging /app/node_modules /app/node_modules +COPY --from=staging /app/build /app/build +CMD ["npm", "run", "start"]