CentOS中配置Node.js网络主要包括系统网络设置、Node.js应用监听配置及反向代理等,步骤如下:
系统网络配置
/etc/sysconfig/network-scripts/ifcfg-ens33
),设置静态IP、子网掩码、网关和DNS:DEVICE=ens33
BOOTPROTO=static
ONBOOT=yes
IPADDR=192.168.1.100
NETMASK=255.255.255.0
GATEWAY=192.168.1.1
DNS1=8.8.8.8
保存后重启网络服务:sudo systemctl restart network
。nmcli
命令配置,如:sudo nmcli connection modify "ens33" ipv4.method manual ipv4.addresses "192.168.1.100/24" ipv4.gateway "192.168.1.1" ipv4.dns "8.8.8.8"
sudo nmcli connection up "ens33"
配置防火墙
sudo firewall-cmd --permanent --add-port=80/tcp
sudo firewall-cmd --permanent --add-port=3000/tcp
sudo firewall-cmd --reload
Node.js应用监听配置
const http = require('http');
const server = http.createServer((req, res) => {
res.end('Hello World');
});
server.listen(3000, '0.0.0.0', () => { // '0.0.0.0'允许所有IP访问
console.log('Server running at http://0.0.0.0:3000/');
});
Nginx反向代理(可选)
sudo yum install nginx
,启动并设为开机自启:sudo systemctl start nginx && sudo systemctl enable nginx
。/etc/nginx/conf.d/nodeapp.conf
):server {
listen 80;
server_name yourdomain.com;
location / {
proxy_pass http://localhost:3000; // 转发到Node.js应用
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
检查配置并重启Nginx:sudo nginx -t && sudo systemctl reload nginx
。SSL证书配置(可选)
sudo yum install certbot python2-certbot-nginx
sudo certbot --nginx -d yourdomain.com
配置Node.js使用HTTPS(需修改应用代码,参考)。验证:通过浏览器访问http://yourdomain.com
或https://yourdomain.com
,确认Node.js应用正常响应。