温馨提示×

debian nodejs如何设置环境

小樊
43
2026-09-14 11:19:22
栏目: 编程语言

在 Debian 上“设置 Node.js 环境”通常包含 安装 Node.js / npm、版本管理、环境变量、镜像源 等。下面按常见场景给你一份清晰指南。


一、安装 Node.js(推荐方式)

✅ 方式 1:使用 NodeSource(推荐,版本新)

sudo apt update
sudo apt install -y curl

# 以 Node.js 20 为例
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs

# 验证
node -v
npm -v

✅ 方式 2:使用 Debian 自带仓库(版本较旧)

sudo apt update
sudo apt install -y nodejs npm

二、使用 nvm 管理 Node 版本(开发推荐)

适合需要多版本切换的场景。

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

nvm install 20
nvm use 20
nvm alias default 20

验证:

node -v
which node

三、配置 npm 全局环境(重要)

1️⃣ 避免 sudo 安装全局包

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

# 写入环境变量
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc
source ~/.bashrc

四、配置环境变量(常用)

编辑:

nano ~/.bashrc

示例:

export NODE_ENV=production
export PORT=3000

生效:

source ~/.bashrc

五、设置 npm 镜像(国内加速)

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

查看:

npm config get registry

六、Systemd 运行 Node 服务(生产环境)

示例 node.service

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

[Service]
User=www
WorkingDirectory=/var/www/app
Environment=NODE_ENV=production
ExecStart=/usr/bin/node server.js
Restart=always

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

七、常见问题

❓ node 命令不存在

which node
echo $PATH

❓ 权限错误

不要用 sudo npm install -g,用 nvm 或 npm prefix。


如果你能说明:

  • 开发环境还是生产环境
  • 是否使用 Docker / pm2 / nginx
  • Debian 版本(cat /etc/os-release

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

0