# Multi-stage build for better layer caching and smaller final image FROM node:18-alpine AS deps WORKDIR /app # Install dumb-init early RUN apk add --no-cache dumb-init # Copy package files first to leverage Docker layer caching COPY package*.json ./ # Install dependencies with optimized settings RUN npm install --prefer-offline --no-audit --legacy-peer-deps # Build stage FROM node:18-alpine AS builder WORKDIR /app # Copy dependencies from deps stage COPY --from=deps /app/node_modules ./node_modules COPY . . # Set Node.js memory limit for build and debug options ENV NODE_OPTIONS="--max-old-space-size=2048" ENV NEXT_TELEMETRY_DISABLED=1 ENV DEBUG=* # List files to ensure everything is copied correctly RUN ls -la # Build the application with better error handling RUN set -e && npm run build 2>&1 | tee build.log || (echo "Build failed! Last 50 lines of output:" && tail -50 build.log && exit 1) # Production stage FROM node:18-alpine AS runner WORKDIR /app ENV NODE_ENV=production ENV NEXT_TELEMETRY_DISABLED=1 # Install dumb-init for proper signal handling RUN apk add --no-cache dumb-init # Create non-root user for security RUN addgroup -g 1001 -S nodejs RUN adduser -S nextjs -u 1001 # Copy necessary files from builder stage COPY --from=builder /app/next.config.js* ./ COPY --from=builder /app/public ./public COPY --from=builder /app/package.json ./package.json # Copy built application COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./ COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static USER nextjs EXPOSE 3000 # Use dumb-init to handle signals properly ENTRYPOINT ["dumb-init", "--"] CMD ["node", "server.js"]