目录
在使用WSL2进行开发时,发现Windows端下载速度正常,但WSL内Git克隆、pip安装依赖包速度较慢,难以跑满实际网速,部分场景需依赖国内镜像源提速。尝试了几种WSL网络配置优化方案,记录如下,供参考。
方法一:WSL2镜像网络模式配置
- 在WSL终端中执行命令,编辑环境配置文件
shell
vim ~/.bashrc
打开文件后,注释掉文件中http_proxy、https_proxy相关的旧配置,避免与新网络模式冲突。
- 执行命令关闭WSL,使配置生效
shell
wsl --shutdown
- 进入路径
C:\Users\你的用户名\,新建名为.wslconfig的文件,用记事本打开并写入以下配置
md
[wsl2]
memory=8GB
processors=8
[experimental]
autoMemoryReclaim=gradual
networkingMode=mirrored
dnsTunneling=true
firewall=true
autoProxy=true
sparseVhd=true
保存文件后重新启动WSL,即可完成镜像网络模式配置。
实测该方案可优化WSL网络连通性,下载速度可稳定在几百KB至1MB左右。
方法二:WSL2版本更新与开发网络配置
部分场景下WSL默认版本不支持新网络特性,可先更新WSL版本,再配置开发环境网络参数。
- 以管理员身份打开PowerShell终端,执行WSL预览版更新命令
shell
wsl --update --pre-release
若执行时出现403报错,可按以下步骤修复环境依赖:
- 开启WSL所需Windows核心功能
shell
dism /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart
dism /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart
- 执行完成后重启电脑,使系统功能生效。
- 同步系统时间,避免网络证书校验异常
shell
net start w32time
w32tm /resync
- 重启后再次以管理员身份执行WSL更新命令,出现版本更新进度提示即代表更新成功
shell
正在检查更新。
正在将适用于的 Linux 的 Windows 子系统更新到版本: 2.7.3.
- 按照方法一的配置,编辑
.wslconfig文件,写入网络优化配置
md
[wsl2]
nestedVirtualization=true
ipv6=true
[experimental]
autoMemoryReclaim=gradual # gradual | dropcache | disabled
networkingMode=mirrored
dnsTunneling=true
firewall=true
autoProxy=true
配置完成后重启WSL。
- WSL开发环境网络连通性配置
shell
# 获取主机网关IP,测试本地网络端口连通性
export hostip=$(cat /etc/resolv.conf | grep -oP 'nameserver\s+\K\S+')
curl -x http://${hostip}:7890 https://github.com -I --connect-timeout 5
若测试出现连接失败,可配置临时环境变量,适配本地开发网络:
shell
export ALL_PROXY="http://localhost:7890"
export HTTP_PROXY="http://localhost:7890"
export HTTPS_PROXY="http://localhost:7890"
针对Git克隆失败的问题,单独配置Git网络参数:
shell
git config --global http.proxy "http://localhost:7890"
git config --global https.proxy "http://localhost:7890"
该方案可成功完成Git克隆与包安装,实测下载速度约2MB,会随网络环境小幅波动。