下面分几种常见方式,说明 在 CentOS 上配置 Node.js 运行环境,涵盖 安装 → 环境变量 → 运行 → 开机自启 → 生产建议。
可自由选择版本(如 18.x / 20.x)
sudo yum install -y curl
curl -fsSL https://rpm.nodesource.com/setup_18.x | sudo bash -
sudo yum install -y nodejs
node -v
npm -v
sudo yum install -y epel-release
sudo yum install -y nodejs
⚠️ 版本可能较老(v10 左右)
适合多版本切换
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
加载环境:
source ~/.bashrc
安装 Node:
nvm install 18
nvm use 18
npm config set registry https://registry.npmmirror.com
查看:
npm config get registry
mkdir -p /opt/nodeapp
cd /opt/nodeapp
// app.js
const http = require('http');
const server = http.createServer((req, res) => {
res.end('Hello Node.js on CentOS');
});
server.listen(3000, () => {
console.log('Server running on port 3000');
});
运行:
node app.js
访问:
http://服务器IP:3000
npm install -g pm2
启动项目:
pm2 start app.js --name nodeapp
常用命令:
pm2 list
pm2 restart nodeapp
pm2 stop nodeapp
pm2 logs
开机自启:
pm2 startup
pm2 save
sudo vi /etc/systemd/system/nodeapp.service
内容:
[Unit]
Description=Node.js App
After=network.target
[Service]
Type=simple
User=root
WorkingDirectory=/opt/nodeapp
ExecStart=/usr/bin/node /opt/nodeapp/app.js
Restart=always
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl start nodeapp
sudo systemctl enable nodeapp
查看状态:
systemctl status nodeapp
sudo firewall-cmd --add-port=3000/tcp --permanent
sudo firewall-cmd --reload
which node
如果使用 NVM,确认:
echo $NVM_DIR
netstat -tunlp | grep 3000
如果你愿意,可以告诉我:
我可以给你 完整生产级部署方案。