From 5fd5a6f8ed8d857f39022eaee8d368a1134b8d48 Mon Sep 17 00:00:00 2001 From: Jim O'Donnell Date: Thu, 5 Dec 2024 09:29:57 +0000 Subject: [PATCH] build: use a base image for Docker builds Split the Docker build into three stages: - base image: Node 20 Alpine with the build environment, package files, Yarn and Lerna config. - builder image: bootstraps the project and root apps from the base image. - runner image: installs only production dependencies and runs the built apps from the `builder` image. This is the image that's deployed to Kubernetes. - run the Next.js apps as the `node` user, to secure the apps in production. --- Dockerfile | 41 +++++++++++++---------------------------- 1 file changed, 13 insertions(+), 28 deletions(-) diff --git a/Dockerfile b/Dockerfile index 6081ffc78fd..c89d1265e0c 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM node:20-alpine AS builder +FROM node:20-alpine AS base ARG COMMIT_ID ENV COMMIT_ID=$COMMIT_ID @@ -18,12 +18,6 @@ ENV APP_ENV=$APP_ENV ENV NEXT_TELEMETRY_DISABLED=1 -ARG CONTENTFUL_ACCESS_TOKEN - -ARG CONTENTFUL_SPACE_ID - -ARG SENTRY_AUTH_TOKEN - RUN mkdir -p /usr/src WORKDIR /usr/src/ @@ -36,12 +30,20 @@ ADD .yarnrc /usr/src/ ADD lerna.json /usr/src/ -COPY ./packages /usr/src/packages - ADD yarn.lock /usr/src/ RUN chown -R node:node . +FROM base AS builder + +ARG CONTENTFUL_ACCESS_TOKEN + +ARG CONTENTFUL_SPACE_ID + +ARG SENTRY_AUTH_TOKEN + +COPY --chown=node:node ./packages /usr/src/packages + USER node RUN --mount=type=cache,id=fem-builder-yarn,uid=1000,gid=1000,target=/home/node/.yarn YARN_CACHE_FOLDER=/home/node/.yarn yarn install --production=false --frozen-lockfile --ignore-scripts @@ -55,28 +57,11 @@ RUN --mount=type=cache,id=fem-builder-yarn,uid=1000,gid=1000,target=/home/node/. RUN echo $COMMIT_ID > /usr/src/packages/app-root/public/commit_id.txt RUN --mount=type=cache,id=fem-builder-yarn,uid=1000,gid=1000,target=/home/node/.yarn YARN_CACHE_FOLDER=/home/node/.yarn yarn workspace @zooniverse/fe-root build -FROM node:20-alpine AS runner - -ARG NODE_ENV=production -ENV NODE_ENV=$NODE_ENV - -RUN mkdir -p /usr/src - -WORKDIR /usr/src/ - -RUN chown -R node:node . +FROM base AS runner USER node -COPY --from=builder /usr/src/package.json /usr/src/package.json - -COPY --from=builder /usr/src/.yarn /usr/src/.yarn - -COPY --from=builder /usr/src/.yarnrc /usr/src/.yarnrc - -COPY --from=builder /usr/src/packages ./packages - -COPY --from=builder /usr/src/yarn.lock /usr/src/yarn.lock +COPY --from=builder --chown=node:node /usr/src/packages ./packages RUN --mount=type=cache,id=fem-runner-yarn,uid=1000,gid=1000,target=/home/node/.yarn YARN_CACHE_FOLDER=/home/node/.yarn yarn install --production --frozen-lockfile --ignore-scripts --prefer-offline