WSL2 网络:镜像模式、localhost 与局域网访问
在 WSL2 NAT 与镜像网络之间选择,正确编辑 .wslconfig,并测试 Windows→Linux 与 Linux→Windows 的连接。
测试环境Pro (26H2) · 版本号 26300.9457 · x64
E1- 版本号
- 26300.9457
- 版本
- Pro (26H2)
- 架构
- x64
- 支持
- 文档(E1)
- 证据
- E1官方文档
- 核验日期
- 2026-10-28
- 页面类型
- 任务
WSL2 默认用 NAT,发行版拿到 Windows 后面的私有地址。出站没问题,但局域网入站和部分 VPN 很别扭。
镜像网络让 WSL 共享 Windows 主机的网络接口,改善 localhost、局域网和 VPN 兼容性。但它不是万能网桥:Hyper-V 防火墙、端口冲突和 IPv6 仍然存在。
NAT vs 镜像
Section titled “NAT vs 镜像”| NAT(默认) | 镜像 | |
|---|---|---|
| WSL IP | 私有,重启会变 | 共享主机接口 |
| Windows → WSL 服务 | localhost 有时要靠转发 |
localhost 更一致 |
| WSL → Windows 服务 | 主机 IP/localhost 不一定 |
能看到主机接口 |
| 局域网 → WSL 服务 | 需要端口代理/防火墙 | 可绑主机接口,仍受防火墙限制 |
| VPN | 常断或需要路由 | 兼容性更好,但不保证 |
| IPv6 | 有限 | 主机支持时可用 |
| 配置 | 无 | .wslconfig + 重启 |
开启镜像模式
Section titled “开启镜像模式”编辑 %UserProfile%\.wslconfig:
[wsl2]networkingMode=mirrored重启 WSL:
wsl --shutdownwsl --version发行版里检查:
ip addrip route应看到镜像 Windows 主机的接口,而不是单个 NAT eth0。
Windows → WSL
Section titled “Windows → WSL”WSL 里起监听:
python3 -m http.server 8000Windows:
curl.exe http://localhost:8000/WSL → Windows
Section titled “WSL → Windows”Windows PowerShell 起监听:
python -m http.server 8001WSL:
curl http://localhost:8001/localhost 失败就试 Windows 局域网 IP;都失败就查 Hyper-V 防火墙和 Windows Defender 防火墙。
| 目标 | 模式 | 额外设置 |
|---|---|---|
| Windows 浏览器 → WSL dev server | 镜像 | 无需;绑 0.0.0.0 或 localhost |
| 局域网手机 → WSL dev server | 镜像 | Hyper-V/Windows 防火墙放行端口 |
| WSL → Windows 服务 | 镜像 | Windows 服务绑局域网接口,不只 127.0.0.1 |
| 企业 VPN + WSL | 镜像 | 开 VPN 测;有些客户端仍要路由 |
| 只用 Docker Desktop | NAT(默认) | 用 Docker 端口发布 |
| 严格隔离局域网 | NAT | 不加端口代理 |
防火墙检查(管理员 PowerShell):
Get-NetFirewallHyperVVMSetting -Name '{40E0AC32-46A5-438A-A0B2-2B479E8F2E90}' | Select-Object Name, DefaultInboundAction, DefaultOutboundAction这个 GUID 是 WSL 的 Hyper-V 防火墙配置。入站被挡就给端口加窄规则,不要把整个配置设成允许。
- Hyper-V 防火墙。 镜像模式走 Hyper-V 防火墙;入站被挡看起来像“服务没起来”。
- 端口占用。 Windows 和 WSL 都可能绑
:8000;换端口或停另一个监听。 - VPN。 有些 VPN 改路由/DNS。开/关 VPN 各测一次,不要假设镜像能修所有隧道。
- Docker Desktop。 它自己的端口发布和 WSL 集成会再加一层。先直接测容器,再怪 WSL。
- IPv6。 只绑
127.0.0.1的服务在 IPv6 上不可达;要显式绑定。
什么时候留 NAT
Section titled “什么时候留 NAT”- 只需要出站互联网和 Windows 本地 dev server。
- Docker Desktop 端口映射已经正常。
- VPN 厂商明确说明了 NAT 行为。
- 不想让 WSL 共享主机接口。
镜像模式是兼容性选择,不是速度设置。
实验室有 WSL 3.0.3 + Ubuntu 24.04,但本页没有重新测试镜像网络。它是 E1。改 .wslconfig 前备份旧文件,准备好 wsl --shutdown 回退。