温馨提示×

ubuntu nodejs网络配置怎么做

小樊
41
2025-08-23 09:14:27
栏目: 编程语言

Ubuntu系统Node.js网络配置步骤

一、系统网络配置(基础网络设置)

  1. 编辑网络配置文件
    使用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 
  2. 验证网络连通性
    使用pingip addr show检查IP是否生效:

    ping 8.8.8.8 # 测试外网连通性 ip addr show eth0 # 查看IP配置 

二、Node.js应用网络配置

  1. 绑定服务器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/'); }); 
  2. 使用环境变量配置
    通过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 
  3. 代理与HTTPS配置

    • HTTP/HTTPS代理:通过http-proxy库或设置环境变量HTTP_PROXY/HTTPS_PROXY
    • SSL证书:使用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); 

三、可选:Nginx反向代理(推荐)

  1. 安装Nginx
    sudo apt install nginx 
  2. 配置反向代理
    编辑/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 # 启用防火墙 

关键参考

  • 系统网络配置:
  • Node.js代码配置:
  • 代理与安全:

0