|
1 | 1 | # Use the latest Node.js image |
2 | | -FROM node:latest |
| 2 | +FROM node:20-alpine AS base |
3 | 3 |
|
4 | | -# Set the working directory inside the container |
| 4 | +# Install dependencies only when needed |
| 5 | +FROM base AS deps |
| 6 | +RUN apk add --no-cache libc6-compat |
5 | 7 | WORKDIR /app |
6 | 8 |
|
7 | | -# Copy package.json and package-lock.json (if available) |
8 | | -COPY package*.json ./ |
| 9 | +# Install dependencies based on the preferred package manager |
| 10 | +COPY package.json package-lock.json* ./ |
| 11 | +RUN npm ci |
9 | 12 |
|
10 | | -# Install dependencies |
11 | | -RUN npm install |
12 | | - |
13 | | -# Copy the rest of the application code |
| 13 | +# Rebuild the source code only when needed |
| 14 | +FROM base AS builder |
| 15 | +WORKDIR /app |
| 16 | +COPY --from=deps /app/node_modules ./node_modules |
14 | 17 | COPY . . |
15 | 18 |
|
16 | | -# Build the Next.js application |
| 19 | +# Remove static export for production server |
| 20 | +ENV NEXT_TELEMETRY_DISABLED=1 |
| 21 | + |
17 | 22 | RUN npm run build |
18 | 23 |
|
19 | | -# Expose port 3000 to allow access |
| 24 | +# Production image, copy all the files and run next |
| 25 | +FROM base AS runner |
| 26 | +WORKDIR /app |
| 27 | + |
| 28 | +ENV NODE_ENV=production |
| 29 | +ENV NEXT_TELEMETRY_DISABLED=1 |
| 30 | + |
| 31 | +RUN addgroup --system --gid 1001 nodejs |
| 32 | +RUN adduser --system --uid 1001 nextjs |
| 33 | + |
| 34 | +COPY --from=builder /app/public ./public |
| 35 | + |
| 36 | +# Set the correct permission for prerender cache |
| 37 | +RUN mkdir .next |
| 38 | +RUN chown nextjs:nodejs .next |
| 39 | + |
| 40 | +# Automatically leverage output traces to reduce image size |
| 41 | +COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./ |
| 42 | +COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static |
| 43 | + |
| 44 | +USER nextjs |
| 45 | + |
20 | 46 | EXPOSE 3000 |
21 | 47 |
|
22 | | -# Start the application |
23 | | -CMD ["npm", "start"] |
| 48 | +ENV PORT=3000 |
| 49 | +ENV HOSTNAME="0.0.0.0" |
| 50 | + |
| 51 | +CMD ["node", "server.js"] |
0 commit comments