如何配置Linux VPS运行Node.js应用?版本兼容及升级问题求助
Alright, let's tackle this step by step—those Node version mismatch and upgrade hiccups are totally common on Linux VPS, so we'll sort out the version issue first then get your app up and running smoothly with PM2.
The reason your Node version stays outdated after upgrading is almost certainly because you're mixing system-provided Node (installed via apt/yum) with a newer version, or your system's PATH isn't pointing to the updated binaries. The most reliable fix is using nvm (Node Version Manager) to manage multiple Node versions cleanly.
- First, fully remove the old system-installed Node and npm to avoid conflicts:
- For Debian/Ubuntu-based systems:
sudo apt remove --purge nodejs npm sudo apt autoremove sudo rm -rf /usr/local/bin/node /usr/local/bin/npm /usr/local/lib/node_modules - For CentOS/RHEL-based systems:
sudo yum remove nodejs npm sudo rm -rf /usr/local/bin/node /usr/local/bin/npm /usr/local/lib/node_modules
- For Debian/Ubuntu-based systems:
- Install nvm:
Close your current terminal and reopen it, or run this to load nvm immediately:curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bashsource ~/.bashrc # Use ~/.zshrc instead if you use Zsh - Install the latest stable LTS Node.js (this version will be fully compatible with modern PM2):
nvm install --lts - Set this LTS version as your default system Node:
nvm alias default node - Verify the upgrade worked:
You should now see the latest LTS version numbers (e.g.,node -v npm -vv20.x.xfor Node,v10.x.xfor npm).
Now that your Node version is sorted, install the latest PM2 globally:
npm install pm2@latest -g
Confirm PM2 is installed and compatible:
pm2 -v
Let's get your app running and set it to survive server reboots:
- Navigate to your app's directory first:
cd /path/to/your/node/application - Start the app with a custom name (makes managing easier later):
pm2 start index.js --name "your-app-name" - Check the app's status to confirm it's running:
pm2 status - Set PM2 to auto-start your app when the VPS boots:
Run this command, then copy and execute thesudocommand it outputs (it will look something like the example below):
Example output command to run:pm2 startupsudo env PATH=$PATH:/home/your-user/.nvm/versions/node/v20.10.0/bin /home/your-user/.nvm/versions/node/v20.10.0/lib/node_modules/pm2/bin/pm2 startup systemd -u your-user --hp /home/your-user - Save your current PM2 process list so it persists across reboots:
pm2 save
- If your app still throws errors after starting, check PM2's detailed logs for clues:
Common issues here include missing dependencies—runpm2 logs your-app-namenpm installin your app directory to fix that. - Make sure your VPS firewall allows traffic on your app's port (e.g., 3000):
- Debian/Ubuntu:
sudo ufw allow 3000/tcp - CentOS/RHEL:
sudo firewall-cmd --add-port=3000/tcp --permanent sudo firewall-cmd --reload
- Debian/Ubuntu:
内容的提问来源于stack exchange,提问作者Pal_IT-Dev

