努力
奋斗

腾讯云服务器选择Debian镜像后如何安装Node.js?

服务器

在腾讯云服务器上使用 Debian 镜像安装 Node.js,推荐通过 NodeSource 官方源 安装,这样可以获得较新的版本并方便后续更新。以下是详细步骤:


✅ 方法一:使用 NodeSource 脚本安装(推荐)

1. 登录服务器

ssh root@your_server_ip

2. 更新系统包列表

sudo apt update && sudo apt upgrade -y

3. 安装必要依赖

sudo apt install -y curl ca-certificates gnupg

4. 添加 NodeSource 仓库并安装 Node.js

以下以安装 Node.js 20.x LTS 为例(如需其他版本,替换版本号即可):

# 导入 NodeSource GPG 密钥
curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | sudo gpg --dearmor -o /usr/share/keyrings/nodesource.gpg

# 设置 NodeSource 仓库
echo "deb [signed-by=/usr/share/keyrings/nodesource.gpg] https://deb.nodesource.com/node_20.x nodistro main" | sudo tee /etc/apt/sources.list.d/nodesource.list

# 更新包列表并安装 Node.js 和 npm
sudo apt update
sudo apt install -y nodejs

5. 验证安装

node -v   # 应输出类似 v20.x.x
npm -v    # 应输出对应 npm 版本

✅ 方法二:使用 nvm 安装(适合多版本管理)

如果你需要灵活切换多个 Node.js 版本,推荐使用 nvm(Node Version Manager)。

1. 安装 nvm

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash

2. 重新加载 shell 配置

source ~/.bashrc
# 或关闭当前终端后重新连接 SSH

3. 安装指定版本的 Node.js

nvm install 20      # 安装最新 20.x LTS
nvm use 20          # 切换到该版本
nvm alias default 20  # 设置默认版本

4. 验证

node -v
npm -v

🔒 安全建议

  • 确保防火墙仅开放必要端口(如 22、80、443 等)。
  • 定期更新系统和 Node.js:
    sudo apt update && sudo apt upgrade -y
  • 生产环境建议使用 PM2 管理 Node.js 进程:
    npm install -g pm2
    pm2 start your-app.js

📌 注意事项

  • Debian 11/12 均兼容上述方法。
  • 避免直接从 apt 安装旧版 Node.js(Debian 默认源中的版本可能过旧)。
  • 如果使用腾讯云轻量应用服务器,操作完全相同。

如有具体问题(如权限错误、网络问题),可提供报错信息进一步排查。

未经允许不得转载:轻量云Cloud » 腾讯云服务器选择Debian镜像后如何安装Node.js?