Ubuntu 上 Node.js 网络设置与部署实践
一 系统网络与防火墙要点
- 查看网卡与地址:使用命令查看网卡名(如 eth0/enp0s3)与 IP 分配:ip a。
- 测试连通性与 DNS:
- 连通性:ping -c 4 8.8.8.8
- DNS 解析:nslookup example.com 或 dig example.com
- 路由与网关:ip route(确认默认网关)。
- 防火墙放行:若使用 UFW,放行 Node 端口(示例为 3000)与 Nginx(80/443):
- sudo ufw allow 3000
- sudo ufw allow 80,443/tcp
- sudo ufw status(核对规则)
以上步骤有助于在调整 Node 监听与反向代理前,先确保底层网络与防火墙策略正确。
二 Node.js 监听与进程管理
- 监听地址与端口:开发/测试可绑定 127.0.0.1:3000;对外服务建议绑定 0.0.0.0:3000(或具体内网 IP),并在安全组/防火墙放行对应端口。示例:
- const http = require(‘http’);
const server = http.createServer((req,res)=>{ res.end(‘Hello’); });
server.listen(3000, ‘0.0.0.0’, ()=> console.log(‘Listening’));
- 进程守护:使用 PM2 常驻与自启。
- 安装:sudo npm i -g pm2
- 启动:pm2 start app.js --name “myapp”
- 自启:pm2 startup(按提示完成 systemd 注册)
- 保存当前进程列表:pm2 save
上述做法确保 Node 应用在崩溃或重启后自动恢复,适合生产环境。
三 反向代理与 HTTPS 配置
- 安装与启用 Nginx:sudo apt-get update && sudo apt-get install nginx;启动后默认监听 80。
- 反向代理示例(将域名请求转发到 Node 的 3000):
- 新建配置:/etc/nginx/conf.d/myapp.conf
- 内容:
upstream node_app { server 127.0.0.1:3000; }
server {
listen 80; server_name example.com;
location / {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://node_app;
}
}
- 校验并重载:sudo nginx -t && sudo systemctl reload nginx
- 免费 HTTPS:使用 Certbot 为 Nginx 自动签发 Let’s Encrypt 证书,完成后 Nginx 同时提供 443/HTTPS 与自动续期。
通过 Nginx 前置,可统一处理域名、端口、压缩、静态资源与证书,Node 专注业务。
四 端口与系统层面网络设置
- 端口转发(无公网 80/443 或需快速映射时):
- 将 80→3000、443→8443(示例):
sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 3000
sudo iptables -t nat -A PREROUTING -p tcp --dport 443 -j REDIRECT --to-port 8443
sudo iptables -I INPUT -p tcp --dport 3000 -j ACCEPT
sudo iptables -I INPUT -p tcp --dport 8443 -j ACCEPT
sudo iptables-save
- 静态 IP(示例,视发行版/网络管理器而定):
- 使用 Netplan(Ubuntu 18.04+ 常见,编辑 /etc/netplan/*.yaml):
network:
version: 2
renderer: networkd
ethernets:
eth0:
addresses: [192.168.1.100/24]
gateway4: 192.168.1.1
nameservers: { addresses: [8.8.8.8, 1.1.1.1] }
- 使用 /etc/network/interfaces(ifupdown,旧版常见):
auto eth0
iface eth0 inet static
address 192.168.1.100
netmask 255.255.255.0
gateway 192.168.1.1
dns-nameservers 8.8.8.8 1.1.1.1
以上方法分别解决端口映射与服务器固定地址需求,便于 Node 服务对外稳定可达。
五 常见网络问题排查清单
- 链路与解析:ip a 检查地址;ping 检测连通;nslookup/dig 检查 DNS。
- 路由与端口:ip route 查默认网关;ss -ltnp | grep 3000 或 nc/telnet 验证端口可达。
- 防火墙/安全组:sudo ufw status;云上实例放行 80/443/3000。
- 抓包与路由跟踪:sudo tcpdump -i eth0 -n;traceroute/mtr 定位链路瓶颈。
- 应用日志:检查 Node 异常堆栈与访问日志,必要时增加日志级别与输出。
按“链路→端口→策略→应用”的顺序排查,可快速定位大多数网络故障。