温馨提示×

Debian上Node.js如何配置环境

小樊
44
2025-12-14 16:13:31
栏目: 编程语言

在 Debian 上配置 Node.js 环境

一 安装方式选择

  • 使用 APT 默认仓库:安装简单,但版本通常较旧,适合快速试用或兼容性要求不高的场景。
  • 使用 NodeSource 仓库:可安装指定或 LTS 版本,兼顾版本新与系统包管理,适合大多数生产/开发环境。
  • 使用 NVM(Node Version Manager):同一台机器管理多个 Node.js 版本,切换方便,适合开发与多项目并行。

二 安装步骤

  • 准备环境

    • 更新索引并安装必要工具:sudo apt update && sudo apt install -y curl ca-certificates gnupg
  • 方式一 APT 安装默认版本

    • 安装:sudo apt install -y nodejs npm
    • 验证:node -v;npm -v
  • 方式二 NodeSource 安装指定或 LTS 版本

    • 安装 LTS:curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
    • 或安装 18.x:curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
    • 安装:sudo apt install -y nodejs
    • 验证:node -v;npm -v
  • 方式三 NVM 安装与多版本管理

    • 安装 NVM:curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
    • 加载环境:source ~/.bashrc(如使用 zsh 则 source ~/.zshrc)
    • 安装与默认:nvm install --lts;nvm alias default <版本号>;nvm use <版本号>
    • 验证:node -v;npm -v

三 配置 npm 与全局包目录

  • 设置国内镜像(可选,提升下载速度)

    • npm config set registry https://registry.npmmirror.com
    • 验证:npm config get registry
  • 配置全局包目录(避免权限问题)

    • 建议为当前用户设置全局目录(示例:~/.npm-global),并在 shell 配置中导出 PATH
    • mkdir -p ~/.npm-global
    • npm config set prefix ‘~/.npm-global’
    • echo ‘export PATH=~/.npm-global/bin:$PATH’ >> ~/.bashrc && source ~/.bashrc
    • 验证:npm config get prefix;which npm

四 部署示例与进程守护

  • 创建并启动一个 Express 服务

    • mkdir myapp && cd myapp
    • npm init -y
    • npm install express
    • 新建 app.js:
      • const express = require(‘express’);
      • const app = express();
      • app.get(‘/’, (_, res) => res.send(‘Hello from Debian Node.js’));
      • app.listen(3000, () => console.log(‘Server running on port 3000’));
    • 运行:node app.js
  • 使用 PM2 守护进程

    • 全局安装:sudo npm install -g pm2
    • 启动与命名:pm2 start app.js --name “myapp”
    • 常用:pm2 list;pm2 logs;pm2 monit
    • 开机自启:pm2 startup;pm2 save

五 反向代理与网络放行

  • 使用 Nginx 反向代理

    • 安装:sudo apt install -y nginx
    • 配置示例(/etc/nginx/sites-available/default):
      • server {
        • listen 80;
        • server_name your_domain_or_ip;
        • location / {
          • proxy_pass http://127.0.0.1:3000;
          • proxy_http_version 1.1;
          • proxy_set_header Upgrade $http_upgrade;
          • proxy_set_header Connection ‘upgrade’;
          • proxy_set_header Host $host;
          • proxy_cache_bypass $http_upgrade;
        • }
      • }
    • 检查并重载:sudo nginx -t && sudo systemctl reload nginx
  • 防火墙与云安全组

    • UFW:sudo ufw allow ‘Nginx Full’
    • 云厂商安全组:放行 80/443(以及应用端口如 3000 的入方向规则,视网络路径而定)

0