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

s_k*_*les 5 bash amazon-web-services node.js pm2

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

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

但是,我想pm2 start app.js从名为 的 Codedeploy 挂钩脚本运行applicationstart.sh,该应用程序失败并显示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
Run Code Online (Sandbox Code Playgroud)

这是应用程序启动脚本:

#!/bin/bash

echo "Running Hook: applicationstart.sh"
cd /home/ubuntu/teller-install/Server/
pm2 start app.js
exit 0
Run Code Online (Sandbox Code Playgroud)

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

为什么从终端启动 pm2 和从启动钩子脚本启动之间会有什么区别?

这是直接从 ssh 运行:

在此输入图像描述

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

s_k*_*les 4

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

脚本现在看起来像

#!/bin/bash

echo "Running Hook: applicationstart.sh"
cd /home/ubuntu/teller-install/Server/
source /etc/profile
pm2 start app.js
exit 0
Run Code Online (Sandbox Code Playgroud)