# ============================================ # Development Stage # ============================================ FROM node:18-alpine AS development WORKDIR /app # Install dependencies for native modules RUN apk add --no-cache python3 make g++ # Copy package files COPY package*.json ./ # Install all dependencies (including devDependencies) RUN npm ci # Copy source code COPY . . # Expose port EXPOSE 3000 # Start in development mode CMD ["npm", "run", "start:dev"] # ============================================ # Build Stage # ============================================ FROM node:18-alpine AS build WORKDIR /app # Install dependencies for native modules RUN apk add --no-cache python3 make g++ # Copy package files COPY package*.json ./ # Install all dependencies RUN npm ci # Copy source code COPY . . # Build the application RUN npm run build # Prune dev dependencies RUN npm prune --production # ============================================ # Production Stage # ============================================ FROM node:18-alpine AS production WORKDIR /app # Create non-root user for security RUN addgroup -g 1001 -S nodejs && \ adduser -S nestjs -u 1001 # Copy built application from build stage COPY --from=build --chown=nestjs:nodejs /app/dist ./dist COPY --from=build --chown=nestjs:nodejs /app/node_modules ./node_modules COPY --from=build --chown=nestjs:nodejs /app/package*.json ./ COPY --from=build --chown=nestjs:nodejs /app/scripts ./scripts # Set environment variables ENV NODE_ENV=production ENV PORT=3000 # Switch to non-root user USER nestjs # Expose port EXPOSE 3000 # Health check HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \ CMD node -e "require('http').get('http://localhost:3000/health', (r) => process.exit(r.statusCode === 200 ? 0 : 1))" # Start the application with migrations CMD ["sh", "-c", "node scripts/run-migrations.js && node dist/main.js"]