问题描述
我在 Windows 10 上使用 WSL2.
I'm using WSL2 on Windows 10.
我的开发堆栈在主机操作系统上使用本地网络服务器(localwp 或 wamp).我使用 WSL2 作为主终端(SSH、Git、SASS、自动化工具……).
My dev stack is using a local webserver (localwp or wamp) on the host OS.I use WSL2 as the main terminal (SSH, Git, SASS, automation tools, ...).
我需要的是一种使用服务器名称而不是随机 IP 地址从 WSL2 系统连接到我的主机服务 (MySql) 的方法.
What I need is a way to connect to my host services (MySql) from the WSL2 system using a server name instead of a random IP address.
Windows 主机已经可以使用localhost"连接到 WSL2 服务.有没有其他方法可以解决?
It is already possible for the Windows host to connect to WSL2 services with "localhost". Is there a solution to do it the other way?
推荐答案
您应该使用 hostname.local
从 WSL2 访问 Windows,因为这将使用正确的 IP.请注意,hostname
应替换为在 WSL2 中运行的 hostname
命令的结果.您可以通过从 WSL2 运行 ping $(hostname).local
来检查 IP.
You should use hostname.local
to access Windows from WSL2 because that will use the correct IP. Note that hostname
should be replaced with the result of the hostname
command run in WSL2.You can check the IP by running ping $(hostname).local
from WSL2.
您还需要添加防火墙规则以允许从 WSL2 到 Windows 的流量.在提升的 PowerShell 提示符下运行:
You also need to add a firewall rule to allow traffic from WSL2 to Windows. In an elevated PowerShell prompt run this:
New-NetFirewallRule -DisplayName "WSL" -Direction Inbound -InterfaceAlias "vEthernet (WSL)" -Action Allow
上面的命令应该允许您从 WSL 访问 Windows 公开的任何内容,无论是什么端口,但是请记住,您启动的任何应用程序都会在您首次启动它们时为它们创建一个自动规则,从而阻止来自公共网络(当您收到来自 Windows 防火墙的提示时,询问是否应允许应用接受来自公共网络的连接).
The command above should allow you to access anything exposed by Windows from WSL, no matter what port, however bear in mind that any apps you've launched get an automated rule created for them when you first launch them, blocking access from public networks (this is when you get a prompt from Windows Firewall, asking whether the app should be allowed to accept connections from public networks).
如果您没有明确允许,默认情况下它们将被阻止,这也会阻止来自 WSL 的连接.因此,您可能需要找到该入站规则,并将其从阻止更改为允许(或直接删除).
If you don't explicitly allow, they will be blocked by default, which also blocks connections from WSL. So you might need to find that inbound rule, and change it from block to allow (or just delete it).
在此处查看信息:
https://github.com/microsoft/WSL/issues/4585#issuecomment-610061194
这篇关于WSL2 使用“本地主机";访问 Windows 服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!