npm run start 是错误的启动方式
之前踩了一个坑,在ecosystem.config.js
直接配置了``npm run start```作为PM2 启动 Nuxt 的命令:
// ecosystem.config.js
module.exports = {
apps: [
{
name: 'NuxtAppName',
script: 'npm',
args: 'run start',
exec_mode: 'cluster', // enables clustering
instances: 'max', // or an integer
}
]
};
而现在网上找到的启动步骤:pm2 start npm -- run start
其实也是同样的启动方式。这样启动的问题是,cluster部署时,程序可以正常启动,但是我们查看PM2的日志的时候,会发现每次启动 PM2 都会打印错误日志:
2020-07-10T14:49:46: Failed at the ssr@1.0.0 start script.
2020-07-10T14:49:46: This is probably not a problem with npm. There is likely additional logging output above.
2020-07-15T19:38:23: ELIFECYCLE
2020-07-15T19:38:23: ssr@1.0.0 start: `nuxt start`
2020-07-15T19:38:23: Exit status 1
而且在下一次执行pm2 restart
或pm2 reload
的时候,大概率会重启失败,需要再执行一次重启才能启动成功。一直不理解为什么程序启动了,但是每次都有错误日志,且每次重启都失败。
正确的启动姿势
经过一顿研究,才发现,不能直接在 PM2 执行 npm 指令,正确的启动方式应该是执行npm run start
里面的指令:nuxt start
:
// package.json
"scripts": {
"start": "nuxt start"
}
而nuxt start
的执行路径就在/node_modules/nuxt/bin/nuxt.js
,所以正确的ecosystem.config.js
启动配置应该是:
// ecosystem.config.js
module.exports = {
apps: [
{
name: 'NuxtAppName',
exec_mode: 'cluster',
instances: 'max', // Or a number of instances
script: './node_modules/nuxt/bin/nuxt.js',
args: 'start',
},
],
}
在我找要写这片文章的资料的时候,才发现原来官方也已经给了这个方案了:Deploy using PM2 cluster mode
不知道为什么当初在部署的时候就是没看到这片官方指引,看了其他人的博客误导了。在启动上就踩了坑。所以入门一个东西的时候,尽可能地阅读官方文档,要帮助理解的时候再去阅读博客加深理解!
零停机部署
零停机部署就是使用 PM2 的 cluster模式,更新程序的时候用 pm2 reload [appName]
,有多个集群(cluster)的时候,PM2会先重启一部分进程,这样就不会导致服务中断,等新的进程重启成功后再重启其他进程,实现零停机(zero-downtime)部署。
但是reload
似乎在有时候会有代码更新后reload
无法更新代码的问题。但只遇到了一次,实测在更新UI的时候,直接reload是可以更新成功的,等下次遇到了再解决吧。