Docker镜像为什么这么大?NodeJS应用程序

6

我正在将我的应用构建为 Docker 镜像。

我的 Dockerfile 内容:

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,它应该很小啊。


2
我建议使用多阶段构建,然后在第二阶段只安装生产依赖项。请参见例如 https://github.com/textbook/starter-kit/blob/master/Dockerfile - jonrsharpe
没有我的应用程序Docker容器,大小为(867-264) ** 603MB**,我认为这不是关于生产依赖项的问题。这是正常的容器大小吗? - jivenox793
我的机器上的 node:12-alpine 大约是80Mb,所以我不知道你有什么。 - jonrsharpe
你用哪个命令获取了图像的大小? - Tom
我使用 docker image 列出我的镜像,并且有一个大小信息。 - jivenox793
1个回答

8

在 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所指出的,你可能正在寻找一个多阶段构建。 这里的基本概念是,在第二个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"]

哦,我在处理。谢谢。现在最终图像更小了!最终大小为272MB(node_module文件夹中有很多软件包)。 - jivenox793
谢谢,对我来说它从267MB降到了149MB。 - piotr_cz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接