最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Ubuntu Node.js网络配置如何操作
时间:2026-07-16 17:50:49 编辑:袖梨 来源:一聚教程网
Ubuntu系统Node.js网络配置指南

一、Ubuntu系统网络基础配置
在配置Node.js网络前,需先确保Ubuntu系统的首层网络(系统网络接口)设置正确,主要包括静态IP分配、DNS解析等。
1. 配置静态IP地址(推荐生产环境使用)
Ubuntu 20.04及以上版本使用netplan管理网络配置,编辑对应的YAML文件(如/etc/netplan/01-netcfg.yaml),按以下格式配置静态IP:
network:version: 2renderer: 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是否生效。
2. 配置动态IP(DHCP,适合家用环境)
若无需固定IP,可保持dhcp4: yes(默认值),系统会自动获取IP地址。无需额外操作,重启网络服务或电脑即可生效。
3. 验证网络连通性
- 测试网络连接:
ping www.baidu.com(若能收到回复则表示网络正常)。 - 检查DNS解析:
cat /etc/resolv.conf(确认DNS服务器地址是否正确)。
二、Node.js应用网络配置
系统网络配置完成后,需在Node.js应用中指定监听的IP和端口,以接收外部请求。
1. 基础监听配置
使用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 Worldn');});// 监听指定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检查)。
2. 使用环境变量配置(灵活推荐)
通过环境变量管理网络参数,便于在不同环境(开发/生产)中切换配置:
const http = require('http');// 从环境变量读取端口和IP(若未设置则使用默认值)const port = process.env.PORT || 3000; // 默认端口3000const 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 Worldn');});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、负载均衡等功能。
1. 安装Nginx
sudo apt updatesudo apt install nginx2. 配置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;# 替换为你的域名或公网IPlocation / {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。
四、常见问题排查
- 无法访问应用:检查Ubuntu防火墙是否放行端口(
sudo ufw allow 3000),或Nginx是否配置正确。 - Node.js应用无法启动:确认端口未被占用(
kill -9 $(lsof -t -i:3000)),或IP地址是否正确。 - 网络不通:检查Ubuntu系统网络配置(
ip addr),或路由器是否允许该IP访问外网。