# Dockerfile for Next.js 14 - Optimized for Production

# Use the official Node.js image with Alpine Linux for a smaller footprint
FROM node:20-alpine AS base

# Set the working directory in the container
WORKDIR /app

# Copy package.json and package-lock.json (or yarn.lock)
COPY package*.json ./

# Install dependencies - leveraging Docker cache
RUN npm install --production --frozen-lockfile || yarn install --production --frozen-lockfile

# Copy the rest of the application code
COPY . .

# Build the Next.js application
RUN npm run build || yarn build

# Stage 2: Production image - smaller and leaner
FROM node:20-alpine AS runner

# Set the working directory
WORKDIR /app

# Set environment variables
ENV NODE_ENV production
ENV NEXT_TELEMETRY_DISABLED 1 # Opt-out of Next.js telemetry

# Add a non-root user for security
RUN addgroup -g 1001 -S nodejs
RUN adduser -S nextjs -u 1001

# Copy only the necessary files from the builder stage
COPY --from=base /app/next.config.js ./
COPY --from=base /app/public ./public
COPY --from=base --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=base --chown=nextjs:nodejs /app/.next/static ./.next/static

# Change ownership of all copied files to the non-root user
USER nextjs

# Expose the port Next.js listens on
EXPOSE 3000

# Command to start the Next.js server in production mode
CMD ["node", "server.js"]