温馨提示×

怎样用debian跑nodejs

小樊
48
2026-09-01 17:03:35
栏目: 编程语言

在 Debian 上运行 Node.js,通常分为 安装 Node.js运行 Node 程序 两部分。下面给你几种常见、可靠的做法。


一、在 Debian 上安装 Node.js

方法 1:使用 Debian 官方仓库(最简单,但版本可能较旧)

sudo apt update
sudo apt install nodejs npm

检查版本:

node --version
npm --version

适合:学习、简单脚本、对版本要求不高的情况


方法 2:使用 NodeSource(推荐,版本新)

以 Node.js 20.x 为例:

sudo apt update
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

适合:生产环境、现代前端/后端项目


方法 3:使用 nvm(适合开发、多版本切换)

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
source ~/.bashrc
nvm install --lts
node -v

适合:开发机、需要多个 Node 版本


二、运行 Node.js 程序

1. 写一个简单的示例

mkdir ~/node-demo
cd ~/node-demo
nano app.js

app.js

console.log("Hello Debian Node.js");

运行:

node app.js

2. 启动一个 HTTP 服务示例

const http = require('http');

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello from Debian!\n');
});

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000');
});

运行:

node app.js

访问:

http://<服务器IP>:3000

三、让 Node 在后台持续运行(常见做法)

使用 pm2(推荐)

sudo npm install -g pm2
pm2 start app.js
pm2 save
pm2 startup

四、常见问题

  • 权限问题:避免用 sudo 跑 npm 全局安装,推荐 nvm
  • 端口被占用:检查 lsof -i:3000
  • 防火墙:Debian 若用 ufw,需放行端口
    sudo ufw allow 3000
    

如果你愿意,可以告诉我:

  • 本地 Debian 还是 云服务器
  • 跑的是 前端 / 后端 / 脚本
  • 是否需要 systemd 开机自启

我可以直接给你一套完整配置。

0