在EC2上运行GitHub Actions时提示npm、pm2 command not found
The error occurs because non-interactive SSH sessions (like the one used by GitHub Actions) don’t load the same shell profile files as interactive logins. This means your PATH variable doesn’t include the directories where npm and pm2 are installed—even if they’re set up globally for your user.
Here are three reliable fixes:
1. Use absolute paths for npm and pm2
First, log into your EC2 instance interactively and run these commands to get the full paths of npm and pm2:
which npm which pm2
Replace the commands in your workflow’s SSH script with these absolute paths. For example, if the output is /usr/local/bin/npm and /usr/local/bin/pm2, update your script:
script: | cd /home/ubuntu/app/next /usr/local/bin/npm ci /usr/local/bin/npm run build /usr/local/bin/pm2 restart 0
2. Source your shell profile to load PATH
If you installed Node.js via a version manager like nvm, or added the path to your .bashrc/.profile, source that file before running commands. For nvm users:
script: | source ~/.nvm/nvm.sh cd /home/ubuntu/app/next npm ci npm run build pm2 restart 0
If you added the path to .bashrc:
script: | source ~/.bashrc cd /home/ubuntu/app/next npm ci npm run build pm2 restart 0
Note: Some .bashrc files exit early for non-interactive shells. If that’s the case, modify your .bashrc to skip that check, or use one of the other fixes.
3. Explicitly add the directory to PATH
If you know the directory where npm/pm2 are located, add it directly to the PATH in the script:
script: | export PATH="/usr/local/bin:$PATH" # Replace with your actual directory cd /home/ubuntu/app/next npm ci npm run build pm2 restart 0
Additional Tip
Simplify your cd commands by combining them into one: cd /home/ubuntu/app/next instead of two separate cd lines.
内容的提问来源于stack exchange,提问作者Akrur Neupane

