在 Ubuntu 上部署 Node.js 常见有几种方式,下面从最推荐到最基础依次说明,你可以按需求选择。
适用于 Ubuntu 20.04 / 22.04 / 24.04
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
✅ 输出示例:
v20.x.x
10.x.x
NVM(Node Version Manager) 最适合开发环境。
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
source ~/.bashrc
nvm install 20
nvm use 20
nvm alias default 20
sudo apt update
sudo apt install nodejs npm
⚠️ 版本通常较老,不建议生产环境使用。
npm install -g pm2
pm2 start app.js
pm2 save
pm2 startup
sudo ufw allow 3000
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://localhost:3000;
}
}
node -v 找不到?which node
echo $PATH
一般是因为 NVM 未生效。
npm config set registry https://registry.npmmirror.com
| 场景 | 推荐方式 |
|---|---|
| 生产服务器 | ✅ NodeSource |
| 本地开发 | ✅ NVM |
| 快速测试 | Ubuntu 官方仓库 |
如果你愿意,可以告诉我:
我可以给你一套完整部署方案。