安装Node.js
使用NodeSource仓库安装指定版本(如14.x):
curl -sL https://rpm.nodesource.com/setup_14.x | sudo bash -
sudo yum install -y nodejs
验证安装:node -v、npm -v。
配置网络接口
编辑网卡配置文件(如/etc/sysconfig/network-scripts/ifcfg-ens33):
DEVICE=ens33
BOOTPROTO=static # 静态IP
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。
防火墙设置
开放Node.js所需端口(如80、443):
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload
或针对特定端口:
sudo firewall-cmd --permanent --add-port=3000/tcp
sudo firewall-cmd --reload
```。
监听地址与端口
在代码中指定监听IP和端口(如仅监听本地):
const http = require('http');
const server = http.createServer((req, res) => {
res.end('Hello World\n');
});
server.listen(3000, '127.0.0.1', () => {
console.log('Server running at http://127.0.0.1:3000/');
});
若需监听所有IP,将'127.0.0.1'改为'0.0.0.0'。
使用环境变量
通过环境变量动态配置端口和主机:
const port = process.env.PORT || 3000;
const host = process.env.HOST || '0.0.0.0';
server.listen(port, host, () => {
console.log(`Server running at http://${host}:${port}/`);
});
启动时指定:PORT=8080 HOST=0.0.0.0 node app.js。
反向代理(可选)
用Nginx代理Node.js应用,提升性能和安全性:
sudo yum install nginx/etc/nginx/conf.d/nodejs.conf):server {
listen 80;
server_name example.com;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_set_header Host $host;
}
}
sudo systemctl restart nginx。ping example.com 或 curl http://localhost:3000。ss或netstat查看端口状态,top监控资源占用。参考来源: