【问题标题】:Issue with PM2 and DotEnv not working on ubuntu serverPM2 和 DotEnv 无法在 ubuntu 服务器上运行的问题
【发布时间】:2019-06-16 09:50:21
【问题描述】:

我知道这个问题有答案,但我不想再创建一个配置文件并在那里加载所有配置并运行 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 > start 加载 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 运行脚本的任何其他解决方案

【问题讨论】:

    标签: node.js process pm2


    【解决方案1】:

    您需要在此处按照我的回答中的注释进行操作:https://stackoverflow.com/a/55853036/2208713。我可以从您上面的问题中看到您将 pm2 语法与 npm 混合在一起。如果您从我的回答中获取模式,您将能够轻松完成这项工作 - 但请仔细按照我的说明进行操作!

    【讨论】:

    • 非常感谢安迪,我找到了一些替代方案。请看看我的解决方案。我会很高兴的。 +1 帮助我。
    • 没问题,我的朋友,很高兴你成功了。我个人更喜欢您的解决方案 2,因为所有 pm2 参数都很好地存储在 config js 文件中,但这取决于您使用什么其他工具来管理您的环境。
    【解决方案2】:

    有两种方法可以实现解决方案。

    解决方案 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 配置文件

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

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2020-05-16
      • 1970-01-01
      • 2012-10-15
      • 2017-09-22
      • 2019-02-02
      • 2018-09-27
      • 2023-02-07
      • 1970-01-01
      • 2022-01-18
      相关资源
      最近更新 更多