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 base
1
2# Install dependencies only when needed
3FROM base AS deps
4RUN apk add --no-cache libc6-compat
5WORKDIR /app
6
7COPY 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  fi
14
15
16# Rebuild the source code only when needed
17FROM base AS builder
18WORKDIR /app
19COPY --from=deps /app/node_modules ./node_modules
20COPY . .
21
22ENV NODE_ENV production
23ENV NEXT_TELEMETRY_DISABLED 1
24
25RUN yarn build
26
27FROM base AS runner
28WORKDIR /app
29
30ENV NODE_ENV production
31ENV NEXT_TELEMETRY_DISABLED 1
32
33RUN addgroup --system --gid 1001 nodejs
34RUN adduser --system --uid 1001 nextjs
35
36COPY --from=builder /app/public ./public
37COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
38COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
39
40USER nextjs
41
42EXPOSE 3000
43
44ENV PORT 3000
45ENV HOSTNAME 0.0.0.0
46
47CMD ["node", "server.js"]