插件窝 干货文章 windows linux子系统对外提供服务的方法是什么

windows linux子系统对外提供服务的方法是什么

Windows WSL2 WSL 端口 876    来源:    2025-04-25

在 Windows Subsystem for Linux (WSL) 中对外提供服务(如 Web 服务器、数据库等),需要通过以下步骤实现。由于 WSL 的网络架构特殊性,需特别注意网络配置:


1. WSL 网络模式基础

  • WSL1:与 Windows 共享网络栈,直接使用 localhost 即可访问。
  • WSL2:运行在轻量级虚拟机中,有独立 IP,但需通过 Windows 主机的端口转发访问。

2. WSL2 对外提供服务的步骤

(1) 配置 WSL2 中的服务

  • 确保服务在 WSL2 内启动并监听正确端口(如 0.0.0.0:80): bash sudo apt install nginx sudo service nginx start
  • 检查服务是否运行: bash curl http://localhost:80 # 在 WSL2 内测试

(2) 允许 Windows 防火墙放行端口

  • 以管理员身份运行 PowerShell: powershell New-NetFirewallRule -DisplayName "WSL2 Web Access" -Direction Inbound -Action Allow -Protocol TCP -LocalPort 80

(3) 配置端口转发(WSL2 必需)

  • WSL2 的 IP 会变,需用脚本动态转发。创建 wsl_port_forward.ps1powershell $wsl_ip = (wsl hostname -I).Trim() netsh interface portproxy delete v4tov4 listenport=80 netsh interface portproxy add v4tov4 listenport=80 connectport=80 connectaddress=$wsl_ip
  • 每次重启 WSL2 后运行此脚本(或设为开机任务)。

(4) 从外部访问服务

  • 外部设备访问 Windows 主机的 IP 和端口: http://<Windows主机IP>:80

3. 高级场景

直接暴露 WSL2 IP(不推荐)

  • 获取 WSL2 IP: bash ip addr show eth0 | grep inet
  • 问题:WSL2 IP 会随重启变化,且需配置复杂的 Windows 路由规则。

使用 Hyper-V 虚拟交换机(固定 IP)

  1. 创建外部虚拟交换机(通过 Hyper-V 管理器)。
  2. 修改 WSL 配置文件 %USERPROFILE%\.wslconfigini [wsl2] networkingMode=bridged vmSwitch=你的交换机名称
  3. 注意:此方法可能影响网络稳定性。

4. 其他注意事项

  • 服务自启动:WSL2 不会自动启动服务,需通过:
    • Windows 任务计划调用 wsl -u root service nginx start
    • 或修改 /etc/wsl.confini [boot] command = service nginx start
  • IPv6 支持:需额外配置 netsh 的 IPv6 转发规则。

5. 验证方法

  • 在 Windows 中测试: powershell curl http://localhost:80
  • 从局域网另一台设备访问: bash curl http://<Windows主机IP>:80

总结方案

场景 方法
WSL1 直接使用 localhost
WSL2(推荐) Windows 端口转发 + 防火墙规则
WSL2(固定 IP) Hyper-V 桥接模式(复杂)

推荐使用 WSL2 + 动态端口转发脚本 平衡易用性与功能性。