在 Linux 上配置 Node.js 时的“网络设置”,通常取决于你是在本机开发、部署服务器,还是容器/云环境。下面按常见场景系统说明。
ping -c 3 baidu.com
ip addr
# 或
ifconfig
Node.js 服务起不来或访问不了,90% 是防火墙问题。
systemctl status firewalld
开放端口(如 3000):
firewall-cmd --add-port=3000/tcp --permanent
firewall-cmd --reload
ufw allow 3000
ufw reload
Node.js 默认监听:
server.listen(3000, '127.0.0.1');
❌ 只能本机访问
✅ 用 0.0.0.0 才能外部访问:
server.listen(3000, '0.0.0.0', () => {
console.log('Server running on 0.0.0.0:3000');
});
node app.js
查看当前限制:
ulimit -n
临时修改:
ulimit -n 65535
永久修改(推荐):
vim /etc/security/limits.conf
添加:
* soft nofile 65535
* hard nofile 65535
编辑:
vim /etc/sysctl.conf
常用配置(Web 服务):
net.core.somaxconn = 65535
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30
生效:
sysctl -p
Node.js 不应直接对外,通常用 Nginx。
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
重启 Nginx:
nginx -t
systemctl restart nginx
npm install -g pm2
pm2 start app.js
pm2 save
pm2 startup
docker run -p 3000:3000 node-app
Node.js 中必须监听:
0.0.0.0
0.0.0.0你可以告诉我:
我可以直接给你一套可执行的最简配置方案。