Home > Article > Web Front-end > How to do Docker mirroring of Node service? Detailed explanation of extreme optimization
During this period, I have been developing an HTML dynamic service that is common to all categories of Tencent documents. In order to facilitate the generation and deployment of access to various categories, and to comply with the trend of moving to the cloud, I am considering using Docker. Methods are used to fix service content and manage product versions in a unified manner. This article will share the optimization experience I accumulated in the process of serving Docker for your reference. [Related tutorial recommendations: nodejs video tutorial]
Start with an example. Most students who are new to Docker should write the Dockerfile of the project like this, as shown below:
FROM node:14 WORKDIR /app COPY . . # 安装 npm 依赖 RUN npm install # 暴露端口 EXPOSE 8000 CMD ["npm", "start"]
Build, package, upload, all in one go. Then look at the image status. Damn it, the volume of a simple node web service has reached an astonishing 1.3 G, and the image transmission and construction speed is also very slow:
It would be fine if this image only needs to be deployed with one instance, but this service must be provided to all development students for high-frequency integration and deployment environment (see my previous article for solutions to achieve high-frequency integration). First of all, if the image size is too large, it will inevitably affect the image pull and update speed, and the integration experience will be worse. Secondly, after the project is launched, there may be tens of thousands of test environment instances online at the same time. Such container memory consumption cost is unacceptable for any project. An optimized solution must be found.
After discovering the problem, I began to study Docker’s optimization plan and prepared to perform surgery on my image.
The first thing to do is of course the most familiar area of the front end, optimizing the size of the code itself. Typescript was used when developing the project before. In order to save trouble, the project was directly packaged using tsc to generate es5 and then ran directly. There are two main volume problems here. One is that the development environment ts source code has not been processed, and the js code used in the production environment has not been compressed.
The other is that the referenced node_modules is too bloated. Still includes many npm packages for development and debugging environments, such as ts-node, typescript, etc. Now that it is packaged into js, these dependencies should naturally be removed.
Generally speaking, since the server-side code will not be exposed like the front-end code, services running on physical machines are more concerned about stability and do not care about more volume, so these places generally do not Do processing. However, after Dockerization, as the deployment scale becomes larger, these problems become very obvious and need to be optimized in the production environment.
In fact, we are very familiar with the optimization methods of these two points on the front end. If it is not the focus of this article, we will briefly mention it. For the first point, use Webpack babel to downgrade and compress the Typescript source code. If you are worried about error troubleshooting, you can add sourcemap, but it is a bit redundant for docker images, which will be discussed later. For the second point, sort out the dependencies and devDependencies of the npm package, and remove dependencies that are not necessary at runtime to facilitate use in the production environment. npm install --production
Install dependencies.
We know that container technology provides process isolation at the operating system level, and the Docker container itself is a process running on A process under an independent operating system, that is to say, the Docker image needs to be packaged into an operating system-level environment that can run independently. Therefore, an important factor in determining image size becomes obvious: the size of the Linux operating system packaged into the image.
Generally speaking, to reduce the size of the dependent operating system, we need to consider two aspects. The first is to remove as many unnecessary tool libraries as possible under Linux, such as python, cmake, telnet wait. The second is to choose a more lightweight Linux distribution system. Regular official images should provide castrated versions of each release based on the above two factors.
Take node:14, the officially provided version of node, as an example. In the default version, its basic operating environment is Ubuntu, which is a large and comprehensive Linux distribution to ensure maximum compatibility. The version that removes unnecessary tool library dependencies is called the node:14-slim version. The smallest image distribution is called node:14-alpine. Linux alpine is a highly streamlined lightweight Linux distribution that only contains basic tools. Its own Docker image is only 4 to 5M in size, so it is very suitable for making the smallest version of the Docker image.
In our service, since the dependencies for running the service are determined, in order to reduce the size of the base image as much as possible, we choose the alpine version as the base image for the production environment.
这时候,我们遇到了新的问题。由于 alpine 的基本工具库过于简陋,而像 webpack 这样的打包工具背后可能使用的插件库极多,构建项目时对环境的依赖较大。并且这些工具库只有编译时需要用到,在运行时是可以去除的。对于这种情况,我们可以利用 Docker 的分级构建
的特性来解决这一问题。
首先,我们可以在完整版镜像下进行依赖安装,并给该任务设立一个别名(此处为build
)。
# 安装完整依赖并构建产物 FROM node:14 AS build WORKDIR /app COPY package*.json /app/ RUN ["npm", "install"] COPY . /app/ RUN npm run build
之后我们可以启用另一个镜像任务来运行生产环境,生产的基础镜像就可以换成 alpine 版本了。其中编译完成后的源码可以通过--from
参数获取到处于build
任务中的文件,移动到此任务内。
FROM node:14-alpine AS release WORKDIR /release COPY package*.json / RUN ["npm", "install", "--registry=http://r.tnpm.oa.com", "--production"] # 移入依赖与源码 COPY public /release/public COPY --from=build /app/dist /release/dist # 启动服务 EXPOSE 8000 CMD ["node", "./dist/index.js"]
Docker 镜像的生成规则是,生成镜像的结果仅以最后一个镜像任务为准。因此前面的任务并不会占用最终镜像的体积,从而完美解决这一问题。
当然,随着项目越来越复杂,在运行时仍可能会遇到工具库报错,如果曝出问题的工具库所需依赖不多,我们可以自行补充所需的依赖,这样的镜像体积仍然能保持较小的水平。
其中最常见的问题就是对node-gyp
与node-sass
库的引用。由于这个库是用来将其他语言编写的模块转译为 node 模块,因此,我们需要手动增加g++ make python
这三个依赖。
# 安装生产环境依赖(为兼容 node-gyp 所需环境需要对 alpine 进行改造) FROM node:14-alpine AS dependencies RUN apk add --no-cache python make g++ COPY package*.json / RUN ["npm", "install", "--registry=http://r.tnpm.oa.com", "--production"] RUN apk del .gyp
详情可见:https://github.com/nodejs/docker-node/issues/282
我们知道,Docker 使用 Layer 概念来创建与组织镜像,Dockerfile 的每条指令都会产生一个新的文件层,每层都包含执行命令前后的状态之间镜像的文件系统更改,文件层越多,镜像体积就越大。而 Docker 使用缓存方式实现了构建速度的提升。若 Dockerfile 中某层的语句及依赖未更改,则该层重建时可以直接复用本地缓存。
如下所示,如果 log 中出现Using cache
字样时,说明缓存生效了,该层将不会执行运算,直接拿原缓存作为该层的输出结果。
Step 2/3 : npm install ---> Using cache ---> efvbf79sd1eb
通过研究 Docker 缓存算法,发现在 Docker 构建过程中,如果某层无法应用缓存,则依赖此步的后续层都不能从缓存加载。例如下面这个例子:
COPY . . RUN npm install
此时如果我们更改了仓库的任意一个文件,此时因为npm install
层的上层依赖变更了,哪怕依赖没有进行任何变动,缓存也不会被复用。
因此,若想尽可能的利用上npm install
层缓存,我们可以把 Dockerfile 改成这样:
COPY package*.json . RUN npm install COPY src .
这样在仅变更源码时,node_modules
的依赖缓存仍然能被利用上了。
由此,我们得到了优化原则:
最小化处理变更文件,仅变更下一步所需的文件,以尽可能减少构建过程中的缓存失效。
对于处理文件变更的 ADD 命令、COPY 命令,尽量延迟执行。
在保证速度的前提下,体积优化也是我们需要去考虑的。这里我们需要考虑的有三点:
Docker 是以层为单位上传镜像仓库的,这样也能最大化的利用缓存的能力。因此,执行结果很少变化的命令需要抽出来单独成层,如上面提到的npm install
的例子里,也用到了这方面的思想。
如果镜像层数越少,总上传体积就越小。因此,在命令处于执行链尾部,即不会对其他层缓存产生影响的情况下,尽量合并命令,从而减少缓存体积。例如,设置环境变量和清理无用文件的指令,它们的输出都是不会被使用的,因此可以将这些命令合并为一行 RUN 命令。
RUN set ENV=prod && rm -rf ./trash
当然,时间和空间的优化从来就没有两全其美的办法,这一点需要我们在设计 Dockerfile 时,对 Docker Layer 层数做出权衡。例如为了时间优化,需要我们拆分文件的复制等操作,而这一点会导致层数增多,略微增加空间。
这里我的建议是,优先保证构建时间,其次在不影响时间的情况下,尽可能的缩小构建缓存体积。
我们编写传统的后台服务时,总是会使用例如 pm2、forever 等等进程守护程序,以保证服务在意外崩溃时能被监测到并自动重启。但这一点在 Docker 下非但没有益处,还带来了额外的不稳定因素。
首先,Docker 本身就是一个流程管理器,因此,进程守护程序提供的崩溃重启,日志记录等等工作 Docker 本身或是基于 Docker 的编排程序(如 kubernetes)就能提供了,无需使用额外应用实现。除此之外,由于守护进程的特性,将不可避免的对于以下的情况产生影响:
增加进程守护程序会使得占用的内存增多,镜像体积也会相应增大。
由于守护进程一直能正常运行,服务发生故障时,Docker 自身的重启策略将不会生效,Docker 日志里将不会记录崩溃信息,排障溯源困难。
由于多了个进程的加入,Docker 提供的 CPU、内存等监控指标将变得不准确。
因此,尽管 pm2 这样的进程守护程序提供了能够适配 Docker 的版本:pm2-runtime
,但我仍然不推荐大家使用进程守护程序。
其实这一点其实是源自于我们的固有思想而犯下的错误。在服务上云的过程中,难点其实不仅仅在于写法与架构上的调整,开发思路的转变才是最重要的,我们会在上云的过程中更加深刻体会到这一点。
无论是为了排障还是审计的需要,后台服务总是需要日志能力。按照以往的思路,我们将日志分好类后,统一写入某个目录下的日志文件即可。但是在 Docker 中,任何本地文件都不是持久化的,会随着容器的生命周期结束而销毁。因此,我们需要将日志的存储跳出容器之外。
最简单的做法是利用 Docker Manager Volume
,这个特性能绕过容器自身的文件系统,直接将数据写到宿主物理机器上。具体用法如下:
docker run -d -it --name=app -v /app/log:/usr/share/log app
运行 docker 时,通过-v 参数为容器绑定 volumes,将宿主机上的 /app/log
目录(如果没有会自动创建)挂载到容器的 /usr/share/log
中。这样服务在将日志写入该文件夹时,就能持久化存储在宿主机上,不随着 docker 的销毁而丢失了。
当然,当部署集群变多后,物理宿主机上的日志也会变得难以管理。此时就需要一个服务编排系统来统一管理了。从单纯管理日志的角度出发,我们可以进行网络上报,给到云日志服务(如腾讯云 CLS)托管。或者干脆将容器进行批量管理,例如Kubernetes
这样的容器编排系统,这样日志作为其中的一个模块自然也能得到妥善保管了。这样的方法很多,就不多加赘述了。
镜像优化之外,服务编排以及控制部署的负载形式对性能的影响也很大。这里以最流行的Kubernetes
的两种控制器(Controller):Deployment
与 StatefulSet
为例,简要比较一下这两类组织形式,帮助选择出最适合服务的 Controller。
StatefulSet
是 K8S 在 1.5 版本后引入的 Controller,主要特点为:能够实现 pod 间的有序部署、更新和销毁。那么我们的制品是否需要使用 StatefulSet
做 pod 管理呢?官方简要概括为一句话:
Deployment 用于部署无状态服务,StatefulSet 用来部署有状态服务。
这句话十分精确,但不易于理解。那么,什么是无状态呢?在我看来,StatefulSet
的特点可以从如下几个步骤进行理解:
StatefulSet
管理的多个 pod 之间进行部署,更新,删除操作时能够按照固定顺序依次进行。适用于多服务之间有依赖的情况,如先启动数据库服务再开启查询服务。
由于 pod 之间有依赖关系,因此每个 pod 提供的服务必定不同,所以 StatefulSet
管理的 pod 之间没有负载均衡的能力。
又因为 pod 提供的服务不同,所以每个 pod 都会有自己独立的存储空间,pod 间不共享。
为了保证 pod 部署更新时顺序,必须固定 pod 的名称,因此不像 Deployment
那样生成的 pod 名称后会带一串随机数。
Since the pod name is fixed, the Service
connected to StatefulSet
can directly use the pod name as the access domain name without providing Cluster IP
, so the Service
connected to StatefulSet
is called Headless Service
.
Through this we should understand that if a single service is deployed on k8s, or there is no dependency between multiple services, then Deployment
must be simple and The best choice, automatic scheduling, automatic load balancing. If the start and stop of services must meet a certain sequence, or the data volume mounted on each pod needs to still exist after destruction, then it is recommended to choose StatefulSet
.
Based on the principle of not adding entities unless necessary, it is strongly recommended that all workloads running a single service use Deployment
as the Controller.
After studying it, I almost forgot the initial goal, so I quickly rebuilt Docker to see the optimization results.
#It can be seen that the optimization effect on the mirror volume is still good, reaching about 10 times. Of course, if the project does not require such a high version of node support, the image size can be further reduced by about half.
Afterwards, the image warehouse will compress the stored image files, and the image version packaged with node14 will eventually be compressed to less than 50M.
Of course, in addition to visible volume data, the more important optimization actually lies in the architectural design changes from physical machine-oriented services to containerized cloud services. change.
Containerization is already the visible future. As a developer, you must always remain sensitive to cutting-edge technologies and actively practice them in order to transform technology into productivity and contribute to the evolution of the project.
For more node-related knowledge, please visit: nodejs tutorial!
The above is the detailed content of How to do Docker mirroring of Node service? Detailed explanation of extreme optimization. For more information, please follow other related articles on the PHP Chinese website!