编辑网络配置文件
使用netplan(Ubuntu 18.04及以上版本)或/etc/network/interfaces(旧版本)配置IP地址、网关等。
netplan配置示例(推荐):
编辑/etc/netplan/01-netcfg.yaml:
network: version: 2 renderer: networkd ethernets: eth0: dhcp4: no # 关闭DHCP(若需静态IP) addresses: [192.168.1.100/24] # 静态IP+子网掩码 gateway4: 192.168.1.1 # 网关 nameservers: addresses: [8.8.8.8, 8.8.4.4] # DNS 保存后执行:sudo netplan apply。
旧版本(/etc/network/interfaces):
sudo nano /etc/network/interfaces # 示例(静态IP): 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 8.8.4.4 sudo systemctl restart networking 验证网络连通性
使用ping或ip addr show检查IP是否生效:
ping 8.8.8.8 # 测试外网连通性 ip addr show eth0 # 查看IP配置 绑定服务器IP和端口
在Node.js代码中通过listen()指定IP和端口:
const http = require('http'); const server = http.createServer((req, res) => { res.end('Hello World'); }); // 绑定到特定IP(如0.0.0.0监听所有接口,或指定具体IP) server.listen(3000, '0.0.0.0', () => { console.log('Server running at http://0.0.0.0:3000/'); }); 使用环境变量配置
通过process.env动态设置IP和端口,方便不同环境切换:
const port = process.env.PORT || 3000; const host = process.env.HOST || '127.0.0.1'; server.listen(port, host, () => { console.log(`Server running at http://${host}:${port}/`); }); 启动时指定环境变量:
PORT=3000 HOST=192.168.1.100 node app.js 代理与HTTPS配置
http-proxy库或设置环境变量HTTP_PROXY/HTTPS_PROXY。https模块加载证书文件:const https = require('https'); const fs = require('fs'); const options = { key: fs.readFileSync('server.key'), cert: fs.readFileSync('server.crt') }; https.createServer(options, (req, res) => { res.end('Secure Connection'); }).listen(443); sudo apt install nginx /etc/nginx/sites-available/default,添加:server { listen 80; server_name yourdomain.com; location / { proxy_pass http://localhost:3000; # 转发到Node.js应用 proxy_set_header Host $host; } } sudo nginx -t && sudo systemctl restart nginx 确保Ubuntu防火墙(ufw)允许Node.js端口:
sudo ufw allow 3000/tcp # 允许指定端口 sudo ufw enable # 启用防火墙