有没有办法优化 Docker Image 的大小?

问题描述

我有使用 V10 在本地运行的 Angular 应用程序。我试图在 Dockerfile 的帮助下构建一个 Docker 镜像。但是在构建镜像时,我的 Docker 镜像大小正在构建为 1.32GB。有没有办法减小它的大小?

下面是我写的 Dockerfile

# base image
FROM node:12.2.0

# set working directory (also creates two folders needed for cypress)
RUN mkdir /usr/src/app && mkdir /usr/src/app/cypress && mkdir /usr/src/app/cypress/plugins
workdir /usr/src/app

# add `/usr/src/app/node_modules/.bin` to $PATH
ENV PATH /usr/src/app/node_modules/.bin:$PATH

# install app and cache app dependencies
copY . /usr/src/app
RUN npm install --silent
EXPOSE 4200
# start app 
CMD ["npm","run","ng serve"]

请注意:- 在本地,根文件显示属性为 1,14,774 项,总计 1.3 GB。

解决方法

您的 base image 未压缩大小为 906MB。我建议您尝试使用 150MB 的 slim version

# base image
FROM node:12.2.0-slim

# set working directory (also creates two folders needed for cypress)
RUN mkdir /usr/src/app && mkdir /usr/src/app/cypress && mkdir /usr/src/app/cypress/plugins
WORKDIR /usr/src/app

# add `/usr/src/app/node_modules/.bin` to $PATH
ENV PATH /usr/src/app/node_modules/.bin:$PATH

# install app and cache app dependencies
COPY . /usr/src/app
RUN npm install --silent
EXPOSE 4200
# start app 
CMD ["npm","run","ng serve"]

还有更小的 alpine version (77.7MB)。

,

我通过在创建图像时不复制 node_modules 文件夹解决了这个问题。所以我所做的是我只是从 github 克隆,其中 node_modules 文件夹本身不可用并创建图像。之后总大小变成只有 14.48 MB。因此,删除 node_modules 解决了我的问题。