问题:
wsl2每次启动后,ip都是变化的,我们也没法进行固定,因此除了宿主机,其他机器无法对其进行直接访问。于是我们就需要将其端口和windows端口进行绑定/转发。
1、方法1 Docker desktop for windows:
使用 docker desktop for windows ,然后 enable wsl2 , 然后绑定你的 wsl2服务。
然后 bash进入 linux子系统, docker run xxx -p 1234:1234 xxx 就可以了。
这样外部就可以访问 宿主ip+1234端口 对这个服务进行访问了。
2、方法2 通过powershell 命令来转发
如果有些东西,用docker反而麻烦一些,因此不愿意使用docker来运行,就需要用到这里了。
编写powershell脚本:forward.ps1
$remoteport = bash.exe -c "ifconfig eth0 | grep 'inet '"
$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=@(80,443,22);
#[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 'WSL 2 Firewall Unlock' ";
#adding Exception Rules for inbound and outbound Rules
iex "New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Outbound -LocalPort $ports_a -Action Allow -Protocol TCP";
iex "New-NetFireWallRule -DisplayName 'WSL 2 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"; `
}
请自行 替换 命令中的 $ports=@(80,443,22) 为你所需要的端口们。我这里只转发 80、443、22这3个端口。
3、配置开启生效:
为了让windows 开机自动生效 你的转发命令,这里我用到了 windows的计划任务工具。
参考我的另一篇文章:windows server 2019 使用wsl2 开机挂载 物理磁盘
里面有截图示例。
这里有所区别(”操作“栏中):
因为这里是poswershell脚本,不是cmd的bat脚本,因此命令有所不同。
”程序或脚本“里面填写:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
”添加参数“里面填写:
-command ". 'C:\Users\Administrator\Documents\forward.ps1'"
同样,建议在”触发“里面 配置上 ”延迟运行“。

微信扫一扫,打赏作者吧~