温馨提示×

debian nodejs怎么配置

小樊
47
2026-10-07 12:17:08
栏目: 编程语言

在 Debian 上配置 Node.js,通常包含安装 Node.js / npm、版本管理(可选)、环境变量与镜像配置、以及常见服务化运行方式。下面按实用场景一步步说明。


一、在 Debian 上安装 Node.js

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

sudo apt update
sudo apt install -y nodejs npm

查看版本:

node -v
npm -v

方式 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

二、配置 npm(镜像 & 全局路径)

1. 使用国内镜像(可选但推荐)

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

查看:

npm config get registry

2. 避免全局安装权限问题(推荐)

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

添加到 ~/.bashrc:

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

然后:

source ~/.bashrc

三、运行 Node.js 项目

1. 基础运行

node app.js

2. 使用 PM2(生产推荐)

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

四、使用 systemd 管理 Node 服务(服务器常用)

示例:/etc/systemd/system/node-app.service

[Unit]
Description=Node.js App
After=network.target

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

[Install]
WantedBy=multi-user.target

启用:

sudo systemctl daemon-reload
sudo systemctl enable node-app
sudo systemctl start node-app

五、常见问题

1. node: command not found

  • 检查 PATH
  • 确认安装成功:which node

2. 端口权限(如 80)

sudo setcap cap_net_bind_service=+ep /usr/bin/node

3. 国内服务器慢

  • 使用 npmmirror
  • 使用 cnpm:
npm install -g cnpm --registry=https://registry.npmmirror.com

如果你能告诉我:

  • Debian 版本(如 11 / 12)
  • 用途(开发 / 生产 / 前端 / 后端)
  • 是否用 Docker

我可以给你更精确的配置方案。

0 踩