在 CentOS 上“管理 Node.js”通常包含 安装、版本切换、更新、卸载、进程管理、权限与运维 等方面。下面按常见场景给你一个实用指南。
curl -fsSL https://rpm.nodesource.com/setup_20.x | sudo bash -
sudo yum install -y nodejs
验证:
node -v
npm -v
适合多版本切换
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
source ~/.bashrc
使用:
nvm install 18
nvm install 20
nvm use 20
nvm alias default 20
sudo yum install epel-release
sudo yum install nodejs npm
npm install -g n
n 20
n latest
⚠️ 注意:在 CentOS 上用 n 可能覆盖系统 Node,生产环境建议用 nvm
npm install
npm update
npm cache clean --force
使用淘宝镜像(国内快):
npm config set registry https://registry.npmmirror.com
npm install -g pm2
pm2 start app.js
pm2 startup
pm2 save
常用:
pm2 list
pm2 logs
pm2 restart app
pm2 stop app
示例 /etc/systemd/system/nodeapp.service:
[Unit]
Description=Node App
After=network.target
[Service]
User=nodeuser
WorkingDirectory=/opt/nodeapp
ExecStart=/usr/bin/node app.js
Restart=always
[Install]
WantedBy=multi-user.target
systemctl daemon-reload
systemctl start nodeapp
systemctl enable nodeapp
firewall-cmd --permanent --add-port=3000/tcp
firewall-cmd --reload
root 跑 Nodeuseradd -m nodeuser
.env 管理配置sudo yum remove nodejs
nvm uninstall 20
| 场景 | 推荐 |
|---|---|
| 开发 | nvm |
| 生产 | NodeSource + PM2 / systemd |
| 多版本 | nvm |
| 长期稳定 | LTS + systemd |
如果你愿意,可以告诉我:
我可以给你更精确的一套配置方案。