Skip to content

Commit

Permalink
build: use a base image for Docker builds
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
eatyourgreens committed Dec 5, 2024
1 parent ebfab6f commit 5fd5a6f
Showing 1 changed file with 13 additions and 28 deletions.
41 changes: 13 additions & 28 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
FROM node:20-alpine AS builder
FROM node:20-alpine AS base

ARG COMMIT_ID
ENV COMMIT_ID=$COMMIT_ID
Expand All @@ -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/
Expand All @@ -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
Expand All @@ -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

Expand Down

0 comments on commit 5fd5a6f

Please sign in to comment.