如何使用127.0.0.1从Windows主机访问WSL2中运行的服务?

问题描述

我有一个Express API服务器并在端口8080上的WSL2上运行。我试图从运行Postman和浏览器的主机Windows计算机上使用127.0.0.1访问端点,但是无法访问API 。将127.0.0.1更改为localhost可行,但我想知道为什么127.0.0.1不可行。也许Window的主机文件与此路由/转发冲突?

这是Windows主机文件

#
127.0.0.1 localhost
::1 localhost
# Added by Docker Desktop
192.168.0.14 host.docker.internal
192.168.0.14 gateway.docker.internal
# To allow the same kube context to work on the host and the container:
127.0.0.1 kubernetes.docker.internal
# End of section

这是WSL2主机文件

# This file was automatically generated by WSL. To stop automatic generation of this file,add the following entry to /etc/wsl.conf:
# [network]
# generateHosts = false
127.0.0.1       localhost
127.0.1.1       HOST.localdomain   HOST
<feff>
127.0.0.1       localhost
::1     localhost
192.168.0.14    host.docker.internal
192.168.0.14    gateway.docker.internal
127.0.0.1       kubernetes.docker.internal

# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

要做的只是从Windows中击127.0.0.1,然后在WSL2中运行我的API进行响应。这可能吗?谢谢您的帮助!

解决方法

我需要这些东西才能与WSL2一起使用

  1. Upgrade to the latest version of windows
  2. wsl --shutdown in powershell
  3. 设置>网络和Internet>网络重置为described here
  4. 配置Windows“高级”防火墙以打开所有网络的端口(WSL是公共的)