WSL2网络配置

WSL2 优点和使用场景

优点:

  • 性能可以接受,比裸机略慢但不明显。
  • 和Windows集成紧密,用起来很方便。
  • 升级到Windows11之后图形界面和音频都有支持,性能也还行,除了重度3D程序之外都不算慢。
  • 宿主机有NG显卡的话可以用CUDA,深度学习炼丹师很开心。这些优点对于开发很有帮助,也足够满足日常轻度使用的需求。

总结:日常使用和做开发是没问题的,但如果想干点什么出格的事情就会到处碰壁踩坑。

WSL 2 虚拟网卡vEthernet (WSL)配置

Get-NetAdapter 'vEthernet (WSL)' | Get-NetIPAddress | Remove-NetIPAddress -Confirm:$False
New-NetIPAddress -AddressFamily IPv4 -IPAddress 172.20.120.1 -PrefixLength 24 -InterfaceAlias 'vEthernet (WSL)'
Get-NetNat | ? Name -Eq WSLNat | Remove-NetNat -Confirm:$False
New-NetNat -Name WSLNat -InternalIPInterfaceAddressPrefix 172.20.120.0/24

WSL 2 全局配置

.wslconfig ,用于在 WSL 2 上运行的所有已安装发行版全局配置设置,每次启动 WSL 2 时自动应用;
编辑%UserProfile%/.wslconfig

[wsl2]
networkingMode=bridged
vmSwitch=WSLBridge
ipv6=false
memory=6G
processors=8
kernelCommandLine=ipv6.disable=1
localhostForwarding=true
swap=1.5
swapFile=D:\wsl\swap.vhdx
pageReporting=true
guiApplications=true
debugConsole=false
nestedVirtualization=true
vmIdleTimeout=60000

WSL 2 局部配置

wsl.conf,为 WSL 2 上运行的 Linux 发行版配置每个发行版的配置设置;
编辑/etc/wsl.conf

[network]
hostname = Fedora
generateHosts = false
generateResolvConf = false

[user]
default = fedora

WSL 2 发行版内部网络配置

在用户级bashrc文件或zshrc文件添加启动自动检查和配置网络命令行

if [ "$(ip addr show eth0 | grep 'inet' | awk '{print $2}' | head -n 1)" != "172.20.120.4/24" ];
then
    sudo ip addr del $(ip addr show eth0 | grep 'inet' | awk '{print $2}' | head -n 1) dev eth0
    sudo ip addr add 172.20.120.4/24 broadcast 172.20.120.255 dev eth0
    sudo ip route add 0.0.0.0/0 via 172.20.120.1 dev eth0
    sudo sh -c "echo 'nameserver 114.114.114.114' > /etc/resolv.conf"
fi

WSL 2 禁用IPv6

尝试删除网卡ipv6配置,导致发行版systemctl命令运行报错:

System has not been booted with systemd as init system (PID 1). Can't operate.
wsl2 Failed to connect to bus: Host is down

正确方式:
1、全局配置wslconfig增加kernelCommandLine=ipv6.disable=1
2、虚拟网卡vEthernet关闭IPv6支持;

参考文章

posted @ 2023-03-19 21:40  露宝的大先生  阅读(3675)  评论(0编辑  收藏  举报