简体   繁体   English

NestJS 最小化 dockerfile

[英]NestJS minimize dockerfile

I want to dockerize my nestjs api.我想码头化我的nestjs api。 With the config listed below, the image gets 319MB big.使用下面列出的配置,图像变得 319MB 大。 What would be a more simple way to reduce the image size, than multi staging?有什么比多阶段更简单的减小图像大小的方法?

Dockerfile Dockerfile

FROM node:12.13-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
CMD npm start

.dockerignore .dockerignore

.git
.gitignore
node_modules/
dist/

For reducing docker image size you can use为了减小 docker 图像大小,您可以使用

  1. Multi-stage build多阶段构建
  2. Npm prune Npm 修剪

While using multi-stage build you should have 2(or more) FROM directives, as usual, the first stage does build, and the second stage just copies build from the first temporary layer and have instructions for run the app.在使用多阶段构建时,您应该有 2(或更多)个 FROM 指令,像往常一样,第一阶段确实构建,第二阶段只是从第一个临时层复制构建并具有运行应用程序的指令。 In our case, we should copy dist & node_modules directories.在我们的例子中,我们应该复制 dist 和 node_modules 目录。

The second important moment its correctly split dependencies between 'devDependencies' & 'dependencies' in your package.json file.第二个重要时刻是在 package.json 文件中正确拆分“devDependencies”和“dependencies”之间的依赖关系。

After you install deps in the first stage, you should use npm prune --production for remove devDependencies from node modules.在第一阶段安装 deps 后,您应该使用 npm prune --production 从节点模块中删除 devDependencies。

FROM node:12.14.1-alpine AS build


WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . ./

RUN npm run build && npm prune --production


FROM node:12.14.1-alpine

WORKDIR /app
ENV NODE_ENV=production

COPY --from=build /app/dist /app/dist
COPY --from=build /app/node_modules /app/node_modules

EXPOSE 3000
ENTRYPOINT [ "node" ]
CMD [ "dist/main.js" ]

If you have troubles with node-gyp or just want to see - a full example with comments in this gist:如果您在使用 node-gyp 时遇到问题或只是想看看 - 一个完整的示例,其中包含此要点中的注释:

https://gist.github.com/nzvtrk/cba2970b1df9091b520811e521d9bd44 https://gist.github.com/nzvtrk/cba2970b1df9091b520811e521d9bd44

More useful references:更多有用的参考资料:

https://docs.docker.com/develop/develop-images/multistage-build/ https://docs.docker.com/develop/develop-images/multistage-build/

https://docs.npmjs.com/cli/prune https://docs.npmjs.com/cli/prune

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM