少啰嗦,先看代码
package.json
{
"name": "xxx",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www",
"forever": "node_modules/forever/bin/forever bin/www"
},
"dependencies": {
"async": "0.9.0",
"body-parser": "1.13.2",
"compression": "1.6.2",
"config": "1.12.0",
"connect-multiparty": "2.0.0",
"cookie-parser": "1.3.5",
"debug": "2.2.0",
"ejs": "2.3.3",
"express": "4.13.1",
"forever": "0.15.3",
"http-proxy-middleware": "0.17.3",
"log4js": "0.6.24",
"serve-favicon": "2.3.0"
}
}
dockerfile
FROM hub.c.163.com/lightingfire/nodejs:6.9.1-alpine
WORKDIR /app
COPY package.json /app
RUN npm i --registry https://registry.npm.taobao.org && npm cache clean
COPY . /app
EXPOSE 8086
CMD npm run forever
分析原理
- 使用alpine的nodejs镜像,显著缩小nodejs镜像大小
- 使用npm cache clean命令,清空npm缓存,再次减少npm包占用的时间
- npm i 和 npm chache clean放在一起写,减少build的层数
- 使用淘宝npm源,显著提高npm包下载的速度
- 守护进程forever通过npm运行node_module中的包,避免单独全局安装forever的占用时间
- copy package到run npm i到copy . /app, 这样的顺序可以充分使用镜像缓存
修改过后,对比之前通过jenkins打包时间从10分钟缩短到7.4秒