Skip to content

Instantly share code, notes, and snippets.

@adiologydev
Created February 6, 2022 15:26
Show Gist options
  • Save adiologydev/38c96398c231b37425fc16f263e2dd93 to your computer and use it in GitHub Desktop.
Save adiologydev/38c96398c231b37425fc16f263e2dd93 to your computer and use it in GitHub Desktop.
NextJS Docker Deployment 101
version: '3.3'
services:
nextjs:
ports:
- 3000:3000 # host port:container port (we all get confused here at some point)
build:
context: ./
dockerfile: Dockerfile
volumes:
- ./:/usr/src/app
- /usr/src/app/node_modules
- /usr/src/app/.next
env_file:
- .env
# Source and Credit: https://github.com/vercel/next.js/tree/canary/examples/with-docker
# It's slightly modified than the original, please read through before using it :)
FROM node:lts-alpine AS deps
# Check https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine to understand why libc6-compat might be needed.
RUN apk add --no-cache libc6-compat
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
# If you're using yarn, comment the two lines above and uncomment the following
# COPY yarn.lock ./
# yarn install --frozen-lockfile
# Rebuild the source code only when needed
FROM node:lts-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
# Next.js collects completely anonymous telemetry data about general usage.
# Learn more here: https://nextjs.org/telemetry
# Uncomment the following line in case you want to disable telemetry during the build.
# ENV NEXT_TELEMETRY_DISABLED 1
RUN npm run build
# Production image, copy all the files and run next
FROM node:lts-alpine AS runner
WORKDIR /app
ENV NODE_ENV production
# Uncomment the following line in case you want to disable telemetry during runtime.
# ENV NEXT_TELEMETRY_DISABLED 1
RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs
# You only need to copy next.config.js if you are NOT using the default configuration
COPY --from=builder /app/next.config.js ./
COPY --from=builder /app/public ./public
COPY --from=builder /app/package.json ./package.json
# Automatically leverage output traces to reduce image size
# https://nextjs.org/docs/advanced-features/output-file-tracing
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
USER nextjs
EXPOSE 3000
ENV PORT 3000
CMD ["node", "server.js"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment