From 57b8ddf17c463ab1bcfbb611098dc1e5b44574cd Mon Sep 17 00:00:00 2001 From: Aswin V Date: Fri, 9 Dec 2022 20:34:40 +0530 Subject: [PATCH] Optimise multi platform build (#128) * Use next.js standalone to optimise docker image * Temporarily disable release branch check * Set `PORT` env * Use the build machine architecture to build and target platform for running * Prep for PR * Update node image * Test with latest image and use ARG for image version * Prep for PR --- .dockerignore | 5 ++++- Dockerfile | 31 +++++++++++++++++++------------ next.config.js | 1 + 3 files changed, 24 insertions(+), 13 deletions(-) diff --git a/.dockerignore b/.dockerignore index 2d04ff2..27b3512 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,8 +1,11 @@ +Dockerfile +.dockerignore node_modules npm-debug.log +README.md +.next .git .github .vscode -*Dockerfile* .env .env.example \ No newline at end of file diff --git a/Dockerfile b/Dockerfile index 0478afc..2422bbf 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,39 +1,46 @@ -FROM node:16.18.0-alpine3.15 AS base +ARG NODEJS_IMAGE=node:16.18.1-alpine3.16 +FROM --platform=$BUILDPLATFORM $NODEJS_IMAGE AS base FROM base AS deps RUN apk add --no-cache libc6-compat WORKDIR /app + +# Install dependencies based on the preferred package manager COPY package.json package-lock.json ./ -RUN npm install +RUN npm ci FROM base AS builder WORKDIR /app -COPY . . COPY --from=deps /app/node_modules ./node_modules +COPY . . ENV NEXT_PUBLIC_GTM_ID "" ENV NEXT_TELEMETRY_DISABLED 1 -RUN npm run build && npm install --production --ignore-scripts --prefer-offline +RUN npm run build -FROM base AS runner +FROM $NODEJS_IMAGE AS runner WORKDIR /app ENV NODE_OPTIONS="--max-http-header-size=81920" ENV NODE_ENV production +ENV NEXT_TELEMETRY_DISABLED 1 -RUN addgroup -g 1001 -S nodejs -RUN adduser -S nextjs -u 1001 + +RUN addgroup --system --gid 1001 nodejs +RUN adduser --system --uid 1001 nextjs COPY --from=builder /app/public ./public -COPY --from=builder --chown=nextjs:nodejs /app/.next ./.next -COPY --from=builder /app/node_modules ./node_modules -COPY --from=builder /app/package.json ./package.json + +# Automatically leverage output traces to reduce image size +# https://nextjs.org/docs/advanced-features/output-file-tracing +COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./ +COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static USER nextjs EXPOSE 4000 -ENV NEXT_TELEMETRY_DISABLED 1 +ENV PORT 4000 -CMD ["npm", "start"] \ No newline at end of file +CMD ["node", "server.js"] \ No newline at end of file diff --git a/next.config.js b/next.config.js index 19d7ba2..c17d62e 100644 --- a/next.config.js +++ b/next.config.js @@ -1,6 +1,7 @@ /** @type {import('next').NextConfig} */ module.exports = { reactStrictMode: true, + output: 'standalone', webpack: (config, { isServer }) => { if (!isServer) { config.resolve.fallback = {