node.js - 为什么docker镜像太大? NodeJS 应用程序

标签 node.js docker

我正在将我的应用程序构建到 docker 镜像中。

我的码头文件:

FROM node:12-alpine

WORKDIR /usr/app

COPY ./package.json ./package.json

RUN yarn

COPY ./src ./src
COPY ./gulpfile.js ./gulpfile.js
COPY ./tsconfig.json ./tsconfig.json

RUN yarn build

RUN rm -rf ./node_modules
RUN rm -rf ./src
RUN rm -rf ./gulpfile.js
RUN rm -rf ./yarn.lock
RUN rm -rf ./package.json
RUN rm ./tsconfig.json

RUN cd dist && yarn 

CMD ["node", "./dist/boot.js"]

构建完成后,我打开了 docker 镜像并在 /user/app/dist 中找到了我的应用程序大小为 264MB(包括 node_modules)。

但是 docker 镜像有 867MB .

为什么?

我的 dockerfile 脚本有什么问题吗?我正在使用 Node Alpine ,它应该很小。

最佳答案

向 Dockerfile 添加行永远不会使图像变小。由于图像由层构建的方式,RUN行通常会产生上一层的所有内容,以及由此产生的任何变化 RUN命令。

作为 Dockerfile 中的一个具体示例:

# Build the contents of the dist/ directory
RUN yarn build

# Keep the entire contents of the previous layer
# PLUS add markers that the node_modules directory should be removed
RUN rm -rf ./node_modules

正如@jonrsharpe 在评论中指出的那样,您可能正在寻找 multi-stage build .这里的基本概念是第二个 FROM行会导致 docker build从一个新的基础镜像完全重新开始,但随后您可以 COPY --from=前一阶段进入最后阶段。

您可以像这样重建现有的图像:

# Add "AS build" for later use
FROM node:12-alpine AS build

# This is exactly what you had before
WORKDIR /usr/app
COPY ./package.json ./package.json
RUN yarn
COPY ./src ./src
COPY ./gulpfile.js ./gulpfile.js
COPY ./tsconfig.json ./tsconfig.json
RUN yarn build

# Now build the actual image, starting over.
FROM node:12-alpine
WORKDIR /usr/app
COPY --from=build /usr/src/app/dist .
# but not its node_modules tree or anything else
CMD ["node", "boot.js"]

关于node.js - 为什么docker镜像太大? NodeJS 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62247148/

相关文章:

node.js - http ://localhost:3000/api/stuff: 400 Bad Request 的 HTTP 失败响应

javascript - 如何在 Node js中创建异步回调?

docker - 在32位机器上安装和使用docker

nginx - nginx 前端后面的 Artifactory pro 服务器

node.js - 如何在 Redis 中实现条件弹出并发友好?

node.js - 如何在带有 Nest.js 的 Node 中分离客户端和服务器应用程序时获取用户的 IP 地址

javascript - 在 JS (Node.js) 中同时管理多个长时间运行的任务

docker - gitlab和taiga的反向代理-Docker

python - Jupyterhub/单用户共享卷

docker - wercker-cli-将源复制到容器需要几分钟-如何使其更快