为 Lerna monorepo 项目编写 Dockerfile

在前文 使用 Lerna 创建单一仓库的 TypeScript 多包项目 基础上,增加了 docker 的支持。

代码见:https://github.com/MarshalW/monorepo-lerna/tree/v1.1.0

基本思路是:

  • 各个子模块不必发布到比如 npm,而是借助 lerna 建立依赖支持
  • dockder multistage build,多阶段构建
  • 先构建总体的阶段,主要是公用依赖库
  • 再按照依赖顺序,分别构建各自阶段,需要用到 lerna bootstrap 为子项目配置依赖
  • 最后的阶段
    • 复制之前子项目阶段的相关文件,主要是 ts 编译后的 js
    • 通过 CMD 启动 simple-service

文件代码:

Dockerfile
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
FROM node:16-alpine3.15 as base

WORKDIR /usr/src/app
COPY ./package.json ./
RUN npm install
COPY ./lerna.json ./
COPY ./tsconfig.json ./

# simple-nlp
FROM base as mw-simple-nlp-build
WORKDIR /usr/src/app/packages/simple-nlp
COPY packages/simple-nlp/package.json ./
WORKDIR /usr/src/app
RUN npx lerna bootstrap --scope=mw-simple-nlp --includeDependencies
WORKDIR /usr/src/app/packages/simple-nlp
COPY packages/simple-nlp/src ./src
COPY packages/simple-nlp/tsconfig.json ./
RUN npm run build

# simple-service
FROM base as mw-simple-service-build
WORKDIR /usr/src/app/packages/simple-service
COPY packages/simple-service/package.json ./
WORKDIR /usr/src/app
RUN npx lerna bootstrap --scope=mw-simple-service --includeDependencies
WORKDIR /usr/src/app/packages/simple-service
COPY packages/simple-service/src ./src
COPY packages/simple-service/tsconfig.json ./
RUN npm run build

# final stage
FROM base
COPY --from=mw-simple-nlp-build /usr/src/app/packages/simple-nlp /usr/src/app/packages/simple-nlp
COPY --from=mw-simple-service-build /usr/src/app/packages/simple-service /usr/src/app/packages/simple-service

WORKDIR /usr/src/app

EXPOSE 3000

CMD [ "node", "packages/simple-service/lib/index.js" ]