本指南介绍如何在 Ubuntu 或 Debian VPS 上安装 Node.js(JavaScript 运行时)和 npm(包管理器),用于运行 Web 应用(Express、NestJS、构建工具等)。
前提条件
- 具备
sudo或 root 的 Linux VPS - Ubuntu 20.04+ 或 Debian 11+(64 位)
- 可用的 SSH 连接
建议
若经常执行 npm install 或编译,建议使用磁盘更快的 VPS,例如我们的 NVMe VPS。
推荐方式:NodeSource(LTS)
1. 更新系统
Bashsudo apt update && sudo apt upgrade -y
2. 安装依赖
Bashsudo apt install -y ca-certificates curl gnupg
3. 添加 NodeSource 仓库(示例:Node.js 22.x LTS)
请将 22.x 替换为所需 LTS 版本,详见 NodeSource distributions。
Bashcurl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash -
4. 安装 Node.js
Bashsudo apt install -y nodejs
5. 验证
Bashnode -v npm -v
快捷方式:发行版软件包
Bashsudo apt install -y nodejs npm
版本可能较旧。生产环境更推荐 NodeSource 或 nvm。
更新 npm(可选)
Bashsudo npm install -g npm@latest
最佳实践
- 不要用 root 跑项目里的
npm:使用专用用户。 - 生产环境可用 PM2 或 systemd 实现开机自启。
- 仅开放必要端口;可用 Nginx 反向代理。
故障排除
- 全局安装报 Permission denied:配置用户级全局目录或使用
nvm。 - Command not found:重新登录 SSH 或新开 shell。
延伸阅读:加固 SSH、Nginx + Certbot。