在 Windows Subsystem for Linux (WSL) 中对外提供服务(如 Web 服务器、数据库等),需要通过以下步骤实现。由于 WSL 的网络架构特殊性,需特别注意网络配置:
localhost
即可访问。0.0.0.0:80
):
bash
sudo apt install nginx
sudo service nginx start
bash
curl http://localhost:80 # 在 WSL2 内测试
powershell
New-NetFirewallRule -DisplayName "WSL2 Web Access" -Direction Inbound -Action Allow -Protocol TCP -LocalPort 80
wsl_port_forward.ps1
:
powershell
$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
http://<Windows主机IP>:80
bash
ip addr show eth0 | grep inet
%USERPROFILE%\.wslconfig
:
ini
[wsl2]
networkingMode=bridged
vmSwitch=你的交换机名称
wsl -u root service nginx start
。/etc/wsl.conf
:
ini
[boot]
command = service nginx start
netsh
的 IPv6 转发规则。powershell
curl http://localhost:80
bash
curl http://<Windows主机IP>:80
场景 | 方法 |
---|---|
WSL1 | 直接使用 localhost |
WSL2(推荐) | Windows 端口转发 + 防火墙规则 |
WSL2(固定 IP) | Hyper-V 桥接模式(复杂) |
推荐使用 WSL2 + 动态端口转发脚本 平衡易用性与功能性。