温馨提示×

nodejs在debian如何配

小樊
53
2026-10-08 06:17:30
栏目: 编程语言

下面给你一份 在 Debian 上安装和配置 Node.js 的常用做法,从“能跑起来”到“生产可用”都说清楚。


一、快速安装(推荐:用 NodeSource)

Debian 自带仓库的 Node 版本通常偏旧,推荐用 NodeSource。

1. 更新系统

sudo apt update
sudo apt upgrade -y

2. 安装依赖

sudo apt install -y curl build-essential

3. 添加 NodeSource 源(以 Node 20 为例)

curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -

4. 安装 Node.js

sudo apt install -y nodejs

5. 验证

node -v
npm -v

二、用 nvm 安装(适合开发环境)

如果你一台机器要多个 Node 版本,用 nvm 最方便。

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

重新登录或:

source ~/.bashrc

安装 Node:

nvm install 20
nvm use 20

三、基础环境配置

1. 设置 npm 镜像(国内推荐)

npm config set registry https://registry.npmmirror.com

查看:

npm config get registry

2. 全局安装目录(避免权限问题)

不推荐用 sudo npm -g

mkdir ~/.npm-global
npm config set prefix '~/.npm-global'

加到 ~/.bashrc:

export PATH=~/.npm-global/bin:$PATH

四、运行 Node 服务(生产建议)

1. 用 PM2 管理进程

npm install -g pm2

启动:

pm2 start app.js

常用命令:

pm2 list
pm2 logs
pm2 restart app
pm2 save
pm2 startup

2. 用 Nginx 反向代理(常见结构)

用户 → Nginx(80/443) → Node(3000)

Nginx 示例:

server {
    listen 80;
    server_name example.com;

    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;
    }
}

五、开机自启(systemd 方式)

如果你不用 PM2,也可以写 systemd:

sudo nano /etc/systemd/system/nodeapp.service
[Unit]
Description=Node App
After=network.target

[Service]
User=www-data
WorkingDirectory=/var/www/nodeapp
ExecStart=/usr/bin/node app.js
Restart=always

[Install]
WantedBy=multi-user.target
sudo systemctl enable nodeapp
sudo systemctl start nodeapp

六、常见问题

1. npm ERR! code EACCES

→ 不要用 sudo,用 npm prefix 或 nvm

2. 端口被占用

sudo lsof -i:3000

3. Debian 版本太老

cat /etc/debian_version

Node 20 需要 Debian 10+


如果你能说明:

  • 是 开发 / 生产
  • 用 Express / Nest / Next
  • 是否要 HTTPS / Docker

我可以直接给你一套更贴合的配置方案。

0 踩