Ubuntu系统Node.js网络配置指南
在配置Node.js网络前,需先确保Ubuntu系统的首层网络(系统网络接口)设置正确,主要包括静态IP分配、DNS解析等。
Ubuntu 20.04及以上版本使用netplan管理网络配置,编辑对应的YAML文件(如/etc/netplan/01-netcfg.yaml),按以下格式配置静态IP:
network:
version: 2
renderer: networkd # 使用systemd-networkd作为渲染器
ethernets:
eth0: # 网络接口名称(可通过`ip addr`命令查看)
dhcp4: no # 关闭DHCP自动获取
addresses: ["192.168.1.100/24"] # 静态IP地址及子网掩码(CIDR格式)
gateway4: 192.168.1.1 # 网关地址(路由器IP)
nameservers:
addresses: ["8.8.8.8", "8.8.4.4"] # DNS服务器地址
保存文件后,执行sudo netplan apply应用配置。可通过ip addr show eth0验证IP是否生效。
若无需固定IP,可保持dhcp4: yes(默认值),系统会自动获取IP地址。无需额外操作,重启网络服务或电脑即可生效。
ping www.baidu.com(若能收到回复则表示网络正常)。cat /etc/resolv.conf(确认DNS服务器地址是否正确)。系统网络配置完成后,需在Node.js应用中指定监听的IP和端口,以接收外部请求。
使用Node.js内置http模块创建服务器时,通过listen()方法指定IP和端口:
const http = require('http');
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
// 监听指定IP(如192.168.1.100)和端口(如3000)
server.listen(3000, '192.168.1.100', () => {
console.log('Server running at http://192.168.1.100:3000/');
});
192.168.1.100:需替换为Ubuntu系统的静态IP(或0.0.0.0监听所有网络接口)。3000:端口号(需确保未被其他应用占用,可通过netstat -tulnp | grep 3000检查)。通过环境变量管理网络参数,便于在不同环境(开发/生产)中切换配置:
const http = require('http');
// 从环境变量读取端口和IP(若未设置则使用默认值)
const port = process.env.PORT || 3000; // 默认端口3000
const host = process.env.HOST || '127.0.0.1'; // 默认本地回环地址
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(port, host, () => {
console.log(`Server running at http://${host}:${port}/`);
});
启动应用时,通过命令行设置环境变量:
PORT=3000 HOST=192.168.1.100 node app.js
或在package.json的scripts中添加:
"scripts": {
"start": "PORT=3000 HOST=192.168.1.100 node app.js"
}
运行npm start即可启动应用。
直接暴露Node.js应用到公网存在安全风险,建议使用Nginx作为反向代理,隐藏Node.js端口并提供HTTPS、负载均衡等功能。
sudo apt update
sudo apt install nginx
编辑Nginx配置文件(如/etc/nginx/sites-available/default),添加以下内容:
upstream node_app {
server 127.0.0.1:3000; # 指向Node.js应用的本地地址和端口
}
server {
listen 80; # 监听80端口(HTTP)
server_name your_domain.com; # 替换为你的域名或公网IP
location / {
proxy_pass http://node_app; # 转发请求到Node.js应用
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;
}
}
保存后,测试Nginx配置语法:sudo nginx -t(无错误则继续),然后重启Nginx:sudo systemctl restart nginx。
sudo ufw allow 3000),或Nginx是否配置正确。kill -9 $(lsof -t -i:3000)),或IP地址是否正确。ip addr),或路由器是否允许该IP访问外网。