Next.js Dockerfile using npm instead of yarn

The example Dockerfile provided on the Next.js documentation only shows how to build for yarn. Below is a small adjustment to the original file to work with npm instead.

This is useful if you have a package.lock.json instead of a yarn.lock file, because your project uses npm install rather than yarn install.

# Install dependencies only when needed
FROM node:alpine AS deps
# Check to understand why libc6-compat might be needed.
RUN apk add --no-cache libc6-compat
# COPY package.json yarn.lock ./
COPY package.json package-lock.json ./
# RUN yarn install --frozen-lockfile
RUN npm ci

# Rebuild the source code only when needed
FROM node:alpine AS builder
COPY . .
COPY --from=deps /app/node_modules ./node_modules
# RUN yarn build && yarn install --production --ignore-scripts --prefer-offline
RUN npm run build && npm install --production --ignore-scripts --prefer-offline

# Production image, copy all the files and run next
FROM node:alpine AS runner

ENV NODE_ENV production

RUN addgroup -g 1001 -S nodejs
RUN adduser -S nextjs -u 1001

# 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 --chown=nextjs:nodejs /app/.next ./.next
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package.json ./package.json

USER nextjs


# Next.js collects completely anonymous telemetry data about general usage.
# Learn more here:
# Uncomment the following line in case you want to disable telemetry.

# CMD ["yarn", "start"]
CMD ["npm", "run", "start"]

Leave a Reply

Your email address will not be published. Required fields are marked *