# Multi-stage Dockerfile for Next.js application # Stage 1: Dependencies FROM node:18-alpine AS deps WORKDIR /app # Install dependencies based on the preferred package manager COPY package.json package-lock.json* ./ RUN npm ci --only=production && npm cache clean --force # Stage 2: Build FROM node:18-alpine AS builder WORKDIR /app # Copy package files COPY package.json package-lock.json* ./ # Install all dependencies (including dev dependencies) RUN npm ci # Copy source code COPY . . # Build the application RUN npm run build # Stage 3: Production FROM node:18-alpine AS runner WORKDIR /app # Create non-root user for security RUN addgroup --system --gid 1001 nodejs RUN adduser --system --uid 1001 nextjs # Copy the public folder COPY --from=builder /app/public ./public # Set the correct permission for prerender cache RUN mkdir .next RUN chown nextjs:nodejs .next # Copy built application from builder stage COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./ COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static # Switch to non-root user USER nextjs # Expose port EXPOSE 3000 # Set port environment variable ENV PORT=3000 ENV HOSTNAME="0.0.0.0" # Health check HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ CMD node -e "require('http').get('http://localhost:3000', (res) => { process.exit(res.statusCode === 200 ? 0 : 1) })" # Start the application CMD ["node", "server.js"]