我正在将我的应用程序构建到 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/