NextJS 14/15 Dockerfile 优化17倍体积
未优化的Dockerfile
FROM node:18-alpine
WORKDIR /app
COPY ./ ./
RUN npm ci \
&& npm run build
EXPOSE 3000
CMD ["npm","run","start"]
已优化的Dockerfile
FROM node:18-alpine as base
# Stage 1: Install dependencies
FROM base AS deps
RUN apk add --no-cache libc6-compat
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
# Stage 2: Install dependencies and build the application
FROM base as builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build
# Stage 3: Create production image with only the necessary files
FROM base AS runner
WORKDIR /app
ENV NODE_ENV=production
RUN addgroup --system --gid 1001 nodejs && \
adduser --system --uid 1001 nextjs && \
mkdir -p .next && \
chown nextjs:nodejs .next
COPY --from=builder /app/public ./public
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"]
需要在代码中next.config.js加上以下代码 , 相关文档:https://nextjs.org/docs/pages/api-reference/config/next-config-js/output#automatically-copying-traced-files
module.exports = {
output: 'standalone',
}
【成果】
经过瘦身之后从2.6GB 变成了 155MB
Facebook评论