在 CentOS 上配置 Node.js 反向代理,最常用、最稳定的方案是 Nginx 反向代理。下面我用 CentOS 7 / 8 举例,从 Node.js 部署 → Nginx 反向代理 → 防火墙/端口 → 可选 HTTPS 给你一套完整流程。
curl -fsSL https://rpm.nodesource.com/setup_18.x | sudo bash -
sudo yum install -y nodejs
验证:
node -v
npm -v
// app.js
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200);
res.end('Hello Node.js');
});
server.listen(3000, () => {
console.log('Server running on port 3000');
});
启动:
node app.js
Node 默认监听 3000 端口
sudo yum install -y nginx
启动并设置开机自启:
sudo systemctl start nginx
sudo systemctl enable nginx
编辑配置文件:
sudo vi /etc/nginx/conf.d/node.conf
写入以下内容(重点):
server {
listen 80;
server_name yourdomain.com; # 或服务器公网 IP
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
sudo nginx -t
sudo systemctl restart nginx
访问:
http://服务器IP
✅ 如果看到 Hello Node.js,说明反向代理成功。
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload
或直接放行端口:
sudo firewall-cmd --permanent --add-port=80/tcp
sudo firewall-cmd --reload
不要让 node app.js 直接跑,推荐使用 PM2
sudo npm install -g pm2
pm2 start app.js --name node-app
pm2 save
pm2 startup
sudo yum install -y certbot python3-certbot-nginx
sudo certbot --nginx -d yourdomain.com
证书会自动配置到 Nginx,并自动续期。
浏览器
↓
80 / 443 (Nginx)
↓
3000 (Node.js)
getenforce
# 如果是 Enforcing
sudo setenforce 0
server {
listen 80;
server_name _;
location / {
proxy_pass http://127.0.0.1:3000;
}
}
如果你愿意,我可以帮你:
直接把你的 CentOS 版本 + Node 端口 + 是否有域名 发我即可。