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

5
我正在尝试使用pm2进程管理器在生产EC2服务器上启动一个node.js应用程序。
当我通过ssh登录实例并运行pm2 start app.js时,PM2可以正常启动并访问所有环境变量。一切都很好。
然而,我想从名为applicationstart.sh的Codedeploy钩子脚本中运行pm2 start app.js,但应用程序因缺少所有环境变量而失败,并显示errored状态。 enter image description here 以下是将脚本添加到每个部署中并调用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运行时,我作为ubuntu登录。为什么在从终端启动pm2和从启动挂钩脚本启动pm2之间会有任何差异?以下是直接从ssh运行的情况:

enter image description here

如果需要解决问题,我可以提供任何必要的信息。谢谢!

1个回答

4

在调用 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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接