Created
September 7, 2024 15:23
-
-
Save carlos-talavera/600bbe58949237ece5e990efd597ac87 to your computer and use it in GitHub Desktop.
Example of Dockerfile for a Next.js standalone build using pnpm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Don't forget to add output: "standalone" on next.config | |
FROM node:22.6.0-alpine3.19 AS base | |
# Install system dependencies and pnpm dependencies | |
FROM base AS build-deps | |
RUN apk add --no-cache libc6-compat | |
ENV PNPM_HOME="/pnpm" | |
ENV PATH="$PNPM_HOME:$PATH" | |
RUN corepack enable | |
RUN corepack prepare pnpm@latest --activate | |
WORKDIR /app | |
COPY package.json pnpm-lock.yaml ./ | |
RUN pnpm install --frozen-lockfile --prefer-frozen-lockfile | |
# Install sharp for image optimization | |
RUN pnpm add sharp | |
FROM base AS builder | |
# * Important. Use build time variables before building the app. If they're not used here, the build won't work | |
ARG NEXT_PUBLIC_BACKEND_URL | |
ENV NEXT_PUBLIC_BACKEND_URL=$NEXT_PUBLIC_BACKEND_URL | |
ARG FRONTEND_URL | |
ENV FRONTEND_URL=$FRONTEND_URL | |
ARG JWT_SECRET | |
ENV JWT_SECRET=$JWT_SECRET | |
RUN corepack enable | |
RUN corepack prepare pnpm@latest --activate | |
WORKDIR /app | |
COPY --from=build-deps /app/node_modules ./node_modules | |
COPY . . | |
RUN pnpm build | |
FROM base AS runner | |
# Set production environment | |
ENV NODE_ENV=production | |
# Disable telemetry | |
ENV NEXT_TELEMETRY_DISABLED=1 | |
# Set the proper permissions to don't use the root user | |
RUN addgroup --system --gid 1001 nodejs | |
RUN adduser --system --uid 1001 nextjs | |
RUN mkdir .next | |
RUN chown nextjs:nodejs .next | |
# Copy the standalone output files to the correct folders (this is really important as well) | |
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./ | |
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static | |
COPY --from=builder --chown=nextjs:nodejs /app/public ./public | |
USER nextjs | |
EXPOSE 3000 | |
ENV PORT=3000 | |
ENV HOSTNAME="0.0.0.0" | |
# Environment variables needed on runtime | |
ARG NEXT_PUBLIC_BACKEND_URL | |
ENV NEXT_PUBLIC_BACKEND_URL=$NEXT_PUBLIC_BACKEND_URL | |
ARG FRONTEND_URL | |
ENV FRONTEND_URL=$FRONTEND_URL | |
ARG JWT_SECRET | |
ENV JWT_SECRET=$JWT_SECRET | |
# Run the server | |
CMD ["node", "server.js"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment