Skip to content

Instantly share code, notes, and snippets.

@EightArmCode
Last active July 22, 2023 10:12
Show Gist options
  • Save EightArmCode/2bb40bf4876abcdfa7a5f27b27c67098 to your computer and use it in GitHub Desktop.
Save EightArmCode/2bb40bf4876abcdfa7a5f27b27c67098 to your computer and use it in GitHub Desktop.
Dockerized multi-stage NextJs build in standalone mode, to be served by nginx-proxy
/**
* This was pieced together from multiple sources on the web,
* but none of them had solved directory structure for standalone mode at the time.
*
* The final structure used here allows the following location block in nginx:
*
* proxy_pass http://localhost:3000/
*/
# Dockerfile
ARG BUILD_NODE=node:19
ARG RUN_NODE=node:19-alpine
# Stage 1: Install dependencies
FROM $BUILD_NODE AS deps
WORKDIR /app
COPY ["package.json", "yarn.lock", "./"]
RUN yarn --frozen-lockfile --non-interactive
# Stage 2: Build the app
FROM $BUILD_NODE AS builder
WORKDIR /app
COPY --from=deps /app/node_modules node_modules/
COPY . .
RUN yarn build
# Stage 3: Run the app in production mode
FROM $RUN_NODE AS runner
WORKDIR /app
ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED 1
RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs
# @TODO copy these to named volume to be served by nginx
# copy assets and the generated standalone server
COPY --from=builder --chown=nextjs:nodejs app/next.config.mjs app/.next/standalone/ ./
COPY --from=builder --chown=nextjs:nodejs app/.next/standalone/.next/* .next/
COPY --from=builder --chown=nextjs:nodejs app/public/ public/
COPY --from=builder --chown=nextjs:nodejs app/.next/static/ .next/static/
USER nextjs
EXPOSE 3000
ENV PORT 3000
# Serve the app
CMD ["node", "./server.js"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment