在 CentOS 上跑起 Node.js,一般分 安装 Node.js → 写/部署代码 → 运行 三步。下面给你几种常见、实用的方式。
# 以 Node.js 18 为例
curl -fsSL https://rpm.nodesource.com/setup_18.x | sudo bash -
sudo yum install -y nodejs
验证:
node -v
npm -v
sudo yum install -y nodejs npm
⚠️ CentOS 7 默认版本可能很旧(v6/v8),不推荐生产用
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
source ~/.bashrc
nvm install 18
mkdir ~/nodeapp
cd ~/nodeapp
vim app.js
app.js:
const http = require('http');
const server = http.createServer((req, res) => {
res.end('Hello CentOS Node.js');
});
server.listen(3000, () => {
console.log('Server running on port 3000');
});
node app.js
浏览器或 curl 访问:
curl http://localhost:3000
sudo firewall-cmd --permanent --add-port=3000/tcp
sudo firewall-cmd --reload
云服务器还要在 安全组 放行端口。
nohup node app.js > app.log 2>&1 &
npm install -g pm2
pm2 start app.js
pm2 save
pm2 startup
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://127.0.0.1:3000;
}
}
❌ node: command not found → 没装或 PATH 不对
❌ 外网访问不了 → 防火墙 / 安全组 / 监听地址
❌ CentOS 8 停止维护 → 建议用 Rocky / Alma / Ubuntu
如果你愿意,可以告诉我:
我可以直接给你一套最合适的具体方案。