Skip to content

Instantly share code, notes, and snippets.

@iampato
Created May 4, 2025 16:52
Show Gist options
  • Save iampato/21cf964daa2b32419272e286029c6335 to your computer and use it in GitHub Desktop.
Save iampato/21cf964daa2b32419272e286029c6335 to your computer and use it in GitHub Desktop.
NextJs Docker file for small builds
# Stage 1: Build the application
FROM node:18-alpine AS builder
# Set working directory
WORKDIR /app
# A wildcard is used to ensure both package.json AND package-lock.json are copied
COPY package*.json ./
# Install all app dependencies
RUN npm i --legacy-peer-deps
# RUN npm i
# Bundle app source
COPY . .
# Set build argument for environment
ARG APP_ENV
ENV APP_ENV $APP_ENV
# Copy the corresponding .env file based on the build environment
COPY .env.$APP_ENV .env
# Build the application
RUN npm run build:special
# Stage 2: Run the application with a minimal image
FROM node:18-alpine AS runner
# Set working directory
WORKDIR /app
# Set build argument for port
ARG PORT
ENV PORT $PORT
# Copy the built application from the builder stage
COPY --from=builder /app/.next ./.next
COPY --from=builder /app/public ./public
COPY --from=builder /app/package.json ./package.json
COPY --from=builder /app/package-lock.json ./package-lock.json
COPY --from=builder /app/next.config.js ./next.config.js
COPY --from=builder /app/.env ./.env
# Install only production dependencies
RUN npm i --only=production --legacy-peer-deps
# Expose the port Next.js runs on
EXPOSE $PORT
# Start the application
CMD ["npm", "start"]
#--build-arg APP_ENV=development
#--build-arg APP_ENV=production
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment