在 Ubuntu 上部署 Node.js 常见有几种方式,下面从最常用、最推荐到进阶方案给你一个完整说明,适合服务器/生产环境。
sudo apt update
sudo apt upgrade -y
sudo apt install -y curl
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs
node -v
npm -v
✅ 优点:
sudo apt update
sudo apt install -y nodejs npm
⚠️ 缺点:
适合开发 / 多版本切换
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
重新加载 shell:
source ~/.bashrc
nvm install 20
nvm use 20
nvm alias default 20
✅ 优点:
git clone https://github.com/your/project.git
cd project
npm install --production
node app.js
npm install -g pm2
pm2 start app.js --name my-app
pm2 startup
pm2 save
✅ PM2 可保证:
用户 → Nginx (80) → Node.js (3000)
server {
listen 80;
server_name yourdomain.com;
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
}
}
| 场景 | 推荐方案 |
|---|---|
| 生产环境 | NodeSource + PM2 |
| 开发环境 | NVM |
| Web 服务 | Node.js + Nginx |
| 高可用 | PM2 + Nginx |
sudo chown -R $USER:$USER ~/.npm
which node
如果你愿意,可以告诉我:
我可以给你定制部署方案 ✅