首页 > 解决方案 > 从 Windows 主机连接到 WSL2 上的服务器不起作用

问题描述

更新 1

如果我将代码打包为 Docker 映像并运行它,curl 命令将在 WSL2 内部Windows 命令行中运行,因此这是 Quarkus 特有的问题。

原来的

我在我的 Windows Home 笔记本电脑上的 WSL2 上安装了 Ubuntu 20.04。

按照Quarkus 入门示例(直到第 5 步:运行应用程序),我在 WSL2bash命令行上运行了代码(服务器),并调用它curl给出了预期的输出:

user@computer:/path$ curl -w '\n' http://localhost:8080/hello
Hello RESTEasy

但是,我无法从主机 Windows 计算机的命令行 ( cmd) 访问该服务器:

C:\Users\username>curl -w "\n" http://localhost:8080/hello

curl: (56) Recv failure: Connection was reset

与此WSL 2 网络视频不同,我没有尝试从 Windows 主机外部访问正在运行的服务器。我什至无法从 Windows 主机访问在 WSL2 Ubuntu 中运行的服务器。

尽管如此,我还是从 Github 上的一个问题中尝试了这个稍微修改过的脚本:

#$remoteport = bash.exe -c "ifconfig eth0 | grep 'inet '"
$remoteport = bash.exe -c "ip addr | grep -Ee 'inet.*eth0'"

$found = $remoteport -match '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}';

if( $found ){
  $remoteport = $matches[0];
} else{
  echo "The Script Exited, the ip address of WSL 2 cannot be found";
  exit;
}

#[Ports]

#All the ports you want to forward separated by coma
$ports=@(8080);


#[Static ip]
#You can change the addr to your ip config to listen to a specific address
$addr='0.0.0.0';
$ports_a = $ports -join ",";


#Remove Firewall Exception Rules
iex "Remove-NetFireWallRule -DisplayName 'WSL2-Firewall-Unlock' ";

#adding Exception Rules for inbound and outbound Rules
iex "New-NetFireWallRule -DisplayName 'WSL2-Firewall-Unlock' -Direction Outbound -LocalPort $ports_a -Action Allow -Protocol TCP";
iex "New-NetFireWallRule -DisplayName 'WSL2-Firewall-Unlock' -Direction Inbound -LocalPort $ports_a -Action Allow -Protocol TCP";

for( $i = 0; $i -lt $ports.length; $i++ ){
  $port = $ports[$i];
  iex "netsh interface portproxy delete v4tov4 listenport=$port listenaddress=$addr";
  iex "netsh interface portproxy add v4tov4 listenport=$port listenaddress=$addr connectport=$port connectaddress=$remoteport";
}

一些设置更改后脚本运行良好,但我仍然无法访问在 WSL2 上运行的服务器。也无法通过浏览器(Vivaldi)访问它(见截图)。

也无法通过浏览器访问 WSL2 服务器

绝望中我尝试了以下方法,但没有奏效:

C:\Users\username>curl -w "\n" http://192.168.1.6:8080/hello

curl: (56) Recv failure: Connection was reset

C:\Users\username>curl -w "\n" http://172.21.240.1:8080/hello

curl: (56) Recv failure: Connection was reset

C:\Users\username>curl -w "\n" http://172.21.251.69:8080/hello

curl: (7) Failed to connect to 172.21.251.69 port 8080: Connection refused

在哪里,

我究竟做错了什么?我以为curl -w "\n" http://localhost:8080/hello只能在 Windows 主机上工作

Winver 将 Windows 版本报告为Version 2004 (OS Build 19041.1110)

标签: networkingwindows-10quarkuswsl-2

解决方案


我对 Quarkus 不熟悉,但我对 localhost 转发在 WSL 中不起作用的“回答”是尝试一个wsl --shutdown,如果可行,请禁用 Windows 快速启动。

但在这种情况下,您也无法在 WSL2 实例的 eth0 地址上访问它,因此可能会发生更多事情。localhost如果 Quarkus 样板配置只是绑定到or ,这也可以解释127.0.0.1。您需要将其绑定到0.0.0.0两者才能正常工作。

为将来查看此答案的其他人更新:在这种情况下,Quarkus 自动绑定127.0.0.1localhost确实是问题所在。根据@markvgti 在评论中的研究,此设置是添加quarkus.http.host=0.0.0.0application.properties.


推荐阅读