从 Windows 主机连接到 WSL2 上的服务器不起作用

Connecting to server on WSL2 from Windows host doesn't work

更新 1

如果我将代码打包为 Docker 图像 & 运行 它,curl 命令在 WSL2 内部工作,来自 Windows 命令行,所以这是 Quarkus 特有的问题。

原创

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

按照 Quarkus Getting Started 示例(直到第 5 步:运行 应用程序 ),我有代码(服务器)运行ning 在我的 WSL2 bash 命令行上,并使用 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 Networking 视频不同,我没有尝试从我的 Windows 主机外部访问 运行ning 服务器。我什至无法从 Windows 主机到达 WSL2 Ubuntu 内的服务器 运行ning。

尽管如此,我尝试了这个稍微修改过的脚本 from an issue on 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 上的服务器 运行ning。也无法通过浏览器 (Vivaldi) 访问它(见屏幕截图)。

无奈之下,我尝试了以下方法,但 none 奏效了:

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 版本报告为 2004 版(OS 内部版本 19041.1110)

我不熟悉 Quarkus,但我的“转到 ” 本地主机转发在 WSL 中不起作用是尝试 wsl --shutdown,如果可行,请禁用 Windows 快速启动。

但在这种情况下,您也无法通过 WSL2 实例的 eth0 地址访问它,因此 可能 会发生更多事情。如果 Quarkus 样板配置仅绑定到 localhost127.0.0.1,也可以解释这一点。您需要将其绑定到 0.0.0.0 才能使两者正常工作。

为以后查看此答案的其他人更新:Quarkus 自动绑定到 127.0.0.1localhost 确实是这个问题案件。从@markvgti 在评论中的研究来看,这个设置是将 quarkus.http.host=0.0.0.0 添加到 application.properties.

根据 NotTheDr01ds 答案更新中的建议:

quarkus.http.host=0.0.0.0 添加到为我工作的 application.properties