You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让局域网(LAN)内设备访问Ubuntu上的Node.js应用?

解决Node.js应用局域网无法访问的问题

1. 修正服务器绑定地址

你的代码中httpServer.listen(portNumber)默认只绑定127.0.0.1(localhost),这会导致只有本机能访问。修改listen参数,让服务器绑定到所有网卡的IP(0.0.0.0),这样局域网内其他设备就能通过Ubuntu的局域网IP访问:

const portNumber = 8080
let app = express()

// 省略其他业务代码...

let httpServer = http.createServer(app)

// 修改为绑定0.0.0.0
httpServer.listen(portNumber, '0.0.0.0', function(){ 
    console.log('listening on port:: ' + portNumber) 
})

2. 开放Ubuntu本地防火墙端口

Ubuntu默认使用ufw防火墙,需要手动开放8080端口:

  • 查看防火墙状态:sudo ufw status
  • 开放8080 TCP端口:sudo ufw allow 8080/tcp
  • 重启防火墙生效:sudo ufw reload

3. 确认局域网访问路径

确保其他设备和Ubuntu机器处于同一局域网(如同一WiFi),然后用Ubuntu的局域网IP替换localhost访问,比如http://192.168.x.x:8080(Ubuntu的局域网IP可通过ip addr命令查看)。

4. 路由器配置说明(仅外网访问需要)

你提供的AT&T防火墙配置页面,仅在需要外网访问时才需设置端口转发。若后续要对外开放,找到页面中的「Port Forwarding」或「Virtual Server」选项,添加规则:外部端口、内部端口均设为8080,内部IP填Ubuntu的局域网IP,协议选择TCP。

5. 临时排查方案

如果上述步骤无效,可临时关闭Ubuntu防火墙测试:sudo ufw disable,测试完成后记得重新开启防火墙:sudo ufw enable,避免安全风险。

内容的提问来源于stack exchange,提问作者owen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 17:42:21