我知道有这个问题的答案,但是我不想再创建一个配置文件并在那里加载所有配置并运行pm2进程。
Project Structure
-----------------
.env
index.js -> server is listening in this file
routes/
models/
middleware/
startup/
package.json
...
内部 package.json
{
"name": "eventbooking",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node -r dotenv/config index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@hapi/joi": "^15.0.3",
"bcryptjs": "^2.4.3",
"compression": "^1.7.4",
"dotenv": "^8.0.0",
"express": "^4.17.1",
"express-async-errors": "^3.1.1",
"helmet": "^3.18.0",
"joi-objectid": "^2.0.0",
"jsonwebtoken": "^8.5.1",
"mongoose": "^5.5.14",
"winston": "^3.2.1"
}
}
正如您从我的 package.json 文件中看到的那样,我正在从 scripts>开始加载 node -r dotenv / config index.js 文件
当我使用以下命令在本地运行时
npm开始
项目完全正常。
现在我已经将项目部署到服务器上,如果我手动运行
npm开始
然后工作正常。
当我在生产环境中的Ubuntu Server中安装 PM2 并执行以下步骤时,它将无法正常工作。
第1步:在根目录下的项目文件夹内进行模式
pm2 start index.js --name "Event Booking"
然后得到以下内容
App name │ id │ version │ mode │ pid │ status │ restart │ uptime │ cpu │ mem │ user │ watching │
├──────────┼────┼─────────┼──────┼───────┼────────┼─────────┼────────┼─────┼──────────┼──────┼──────────┤
│ index │ 0 │ 1.0.0 │ fork │ 29897 │ online │ 0 │ 0s │ 0% │ 3.7 MB │ root │ disabled
但是该项目无法正常工作。有什么问题。
即使我以以下方式运行
pm2 start -r dotenv/config index.js --name 'Event Booking'
然后出现错误
错误:未知选项`-r'
使用pm2运行脚本的任何其他解决方案
答案 0 :(得分:1)
您需要遵循我的回答中的注释:https://stackoverflow.com/a/55853036/2208713。我可以从上面的问题中看到,您正在将pm2语法与npm混合使用。如果您从我的回答中选择模式,您将可以轻松完成此操作-但请仔细按照我的指示进行!
答案 1 :(得分:0)
有两种解决方案。
解决方案1:
在运行pm2进程时,使用-node-args 如下运行
pm2 start index.js --name eventbooking --node-args="-r dotenv/config"
除了 dotenv / config 之外,您还可以传递多个用空格隔开的参数,因为我从 dotenv 包中加载了所有内容,但我只需要演示如下
pm2 start index.js --name eventbooking --node-args="-r dotenv/config --production --port=1337"
解决方案2:
或者,您可以使用 pm2 init 初始化项目,这将创建名称为 ecosystem.config.js
的pm2配置文件。出于某些原因,应用下的参数不起作用,所以我不得不再次添加 node_args ,如下所示
{
"apps": [
{
"name": "eventbooking",
"script": "./index.js",
"node_args": ["-r dotenv/config"]
}
]
}
实际上,我坚持使用解决方案1 以获得更简洁和最少的代码模式。
如果有人对PM2选项感兴趣,请访问以下链接