Skip to content

Commit fed0aaf

Browse files
authored
Merge pull request #3006 from owenyang0/feature/dockerfile-optimise
feat: 优化dockerfile,可使包体积从1.1G缩小至200M
2 parents b24befb + 7d7718d commit fed0aaf

File tree

3 files changed

+27
-7
lines changed

3 files changed

+27
-7
lines changed

.env.example

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,3 +173,4 @@
173173
# ENABLE_CACHE=
174174
# VERCEL_ENV=
175175
# NEXT_PUBLIC_VERSION=
176+
# NEXT_BUILD_STANDALONE=

Dockerfile

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,42 @@
11
ARG NOTION_PAGE_ID
22
ARG NEXT_PUBLIC_THEME
33

4-
# Install dependencies only when needed
5-
FROM node:18-alpine3.18 AS deps
4+
FROM node:18-alpine3.18 AS base
5+
6+
# 1. Install dependencies only when needed
7+
FROM base AS deps
68
# Check https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine to understand why libc6-compat might be needed.
79
RUN apk add --no-cache libc6-compat
810
WORKDIR /app
911
COPY package.json ./
1012
RUN yarn install --frozen-lockfile
1113

12-
# Rebuild the source code only when needed
13-
FROM node:18-alpine3.18 AS builder
14+
# 2. Rebuild the source code only when needed
15+
FROM base AS builder
1416
ARG NOTION_PAGE_ID
17+
ENV NEXT_BUILD_STANDALONE=true
18+
1519
WORKDIR /app
20+
1621
COPY --from=deps /app/node_modules ./node_modules
1722
COPY . .
1823
RUN yarn build
1924

20-
ENV NODE_ENV production
25+
# 3. Production image, copy all the files and run next
26+
FROM base AS runner
27+
ENV NODE_ENV=production
28+
29+
WORKDIR /app
30+
31+
COPY --from=builder /app/public ./public
32+
33+
# Automatically leverage output traces to reduce image size
34+
# https://nextjs.org/docs/advanced-features/output-file-tracing
35+
COPY --from=builder /app/.next/standalone ./
36+
COPY --from=builder /app/.next/static ./.next/static
37+
38+
# 个人仓库把将配置好的.env.local文件放到项目根目录,可自动使用环境变量
39+
# COPY --from=builder /app/.env.local ./
2140

2241
EXPOSE 3000
2342

@@ -26,4 +45,4 @@ EXPOSE 3000
2645
# Uncomment the following line in case you want to disable telemetry.
2746
# ENV NEXT_TELEMETRY_DISABLED 1
2847

29-
CMD ["yarn", "start"]
48+
CMD ["node", "server.js"]

next.config.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ const nextConfig = {
8484
eslint: {
8585
ignoreDuringBuilds: true
8686
},
87-
output: process.env.EXPORT ? 'export' : undefined,
87+
output: process.env.EXPORT ? 'export' : process.env.NEXT_BUILD_STANDALONE === 'true' ? 'standalone' : undefined,
8888
staticPageGenerationTimeout: 120,
8989
// 多语言, 在export时禁用
9090
i18n: process.env.EXPORT

0 commit comments

Comments
 (0)