Node.js 当 pm2 从脚本启动时应用程序无法访问任何环境变量,但当从 ssh 启动时可以

Node.js app can't access any env variables when pm2 is started from a script but can when launched from ssh

我正在尝试使用 pm2 进程管理器在生产 EC2 服务器上启动 node.js 应用程序。

当我通过 ssh 进入实例并 运行 pm2 start app.js 时,PM2 启动正常并且可以访问所有环境变量。一切都很好。

但是,我想从名为 applicationstart.sh 的 Codedeploy 挂钩脚本 运行 pm2 start app.js,应用程序失败并显示 errored 状态,因为它缺少所有环境变量.

这里是添加脚本的地方,因此每次部署都会启动它并调用 pm2 start:appspec.yml

version: 0.0
os: linux
files:
  - source: /
    destination: /home/ubuntu/teller-install
hooks:
  AfterInstall:
    - location: scripts/afterinstall.sh
      timeout: 1000
      runas: root
  ApplicationStart:
    - location: scripts/applicationstart.sh
      timeout: 300
      runas: ubuntu

这是应用程序启动脚本:

#!/bin/bash

echo "Running Hook: applicationstart.sh"
cd /home/ubuntu/teller-install/Server/
pm2 start app.js
exit 0

当我从 ssh 运行 脚本时,我以 ubuntu 身份登录,并将 appconfig.yml 中的脚本设置为 运行 作为 ubuntu还有。

为什么从终端启动 pm2 和从启动挂钩脚本启动 pm2 会有什么不同?

这里是 运行ning 直接来自 ssh:

我可以提供急需解决方案所需的任何信息。谢谢!

我必须在调用 pm2 start app.js 加载环境变量之前添加 source /etc/profile

脚本现在看起来像

#!/bin/bash

echo "Running Hook: applicationstart.sh"
cd /home/ubuntu/teller-install/Server/
source /etc/profile
pm2 start app.js
exit 0