Dockerfile Example for Selfhosted NextJs Application
Updated at
If you want to selfhost a nextJs application you might want to dockerize it.
For this you need to have the standalone output in your next.config.js:
0const nextConfig = {1 output: 'standalone',2}
Afterward, you can build a docker image out of it using a dockerfile. Here is an example dockerfile that allows you to build docker image of your application:
0FROM node:18-alpine AS base12# Install dependencies only when needed3FROM base AS deps4RUN apk add --no-cache libc6-compat5WORKDIR /app67COPY package.json yarn.lock* package-lock.json* pnpm-lock.yaml* ./8RUN \9 if [ -f yarn.lock ]; then yarn --frozen-lockfile; \10 elif [ -f package-lock.json ]; then npm ci; \11 elif [ -f pnpm-lock.yaml ]; then yarn global add pnpm && pnpm i --frozen-lockfile; \12 else echo "Lockfile not found." && exit 1; \13 fi141516# Rebuild the source code only when needed17FROM base AS builder18WORKDIR /app19COPY --from=deps /app/node_modules ./node_modules20COPY . .2122ENV NODE_ENV production23ENV NEXT_TELEMETRY_DISABLED 12425RUN yarn build2627FROM base AS runner28WORKDIR /app2930ENV NODE_ENV production31ENV NEXT_TELEMETRY_DISABLED 13233RUN addgroup --system --gid 1001 nodejs34RUN adduser --system --uid 1001 nextjs3536COPY --from=builder /app/public ./public37COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./38COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static3940USER nextjs4142EXPOSE 30004344ENV PORT 300045ENV HOSTNAME 0.0.0.04647CMD ["node", "server.js"]