PM2 和 DotEnv 无法在 ubuntu 服务器上运行的问题

Issue with PM2 and DotEnv not working on ubuntu server

我知道这个问题有答案,但我不想再创建一个配置文件并加载那里的所有配置和 运行 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 文件中看到的那样,我正在加载 node -r dotenv/config index.js 文件来自 scripts > start

当我在本地运行使用以下命令时

npm 启动

该项目完全正常。

现在我已经将项目部署到服务器,如果我手动 运行

npm 启动

然后工作正常。

当我在 Ubuntu 生产服务器中安装 PM2 并执行以下步骤时,它无法正常工作。

第一步:在根目录和项目文件夹里面模式

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

运行 脚本的任何其他解决方案

您需要按照我在此处的回答中的注释进行操作:。从你上面的问题我可以看出你混淆了 pm2 语法和 npm。如果您采用我的回答中的模式,您将能够很容易地完成这项工作 - 但请仔细按照我的说明进行操作!

有两种方法可以解决。

解决方案一:

当运行将pm2进程运行与--node-args连接如下

pm2 start index.js --name eventbooking --node-args="-r dotenv/config"

除了 dotenv/config 你可以传递多个参数 space 分开,我不需要太多,因为我从 [=34 加载所有东西=]dotenv 包但显示仅供演示如下

pm2 start index.js --name eventbooking --node-args="-r dotenv/config --production --port=1337"

方案二:

或者,您可以使用 pm2 init 初始化您的项目,这将创建名为 ecosystem.config.js[ 的 pm2 配置文件=14=]

对我来说,由于某些原因,app 下的 args 不起作用,所以我不得不添加 node_args 再如下

{
  "apps": [
    {
      "name": "eventbooking",
      "script": "./index.js",
      "node_args": ["-r dotenv/config"]
    }
  ]
}

实际上,我坚持使用解决方案 1 以获得更清晰和最少的代码模式。

如果有人对 PM2 选项感兴趣,请访问以下 link

http://pm2.keymetrics.io/docs/usage/quick-start/