分享自己日常使用 WSL 遇到的问题及方案【持续更新】
背景
自己之前一直是使用 Mac,由于公司有合规和审计要求,所以必须使用公司提供的移动工作站,且没有管理员权限。加上自己习惯了 Linux 命令,所以就决定使用 WSL2。下面是自己遇到的一些问题和方案。
Q1:如何配置 WSL 使用 Windows 中安装的代理软件?
A1:配置 Windows 用户主目录下的 .wslconfig 文件和 WSL 用户主目录下的 .zshrc 文件。
镜像模式(推荐,仅限 Windows 11):
[wsl2] networkingMode=Mirrored
autoProxy=false 在 ~/.zshrc 中添加:
Bash
# WSL Mirrored 模式下直接指向本地 localhost export https_proxy="http://127.0.0.1:7890" export http_proxy="http://127.0.0.1:7890" export all_proxy="http://127.0.0.1:7890" NAT 模式(Windows 10 或旧版):
[wsl2] networkingMode=Nat
autoProxy=false 在 ~/.zshrc 中添加:
Bash
# WSL Nat 模式需要动态获取宿主机虚拟网卡 IP
host_ip=$(ip route | awk '/default/ {print $3}')
export https_proxy="http://$host_ip:7890" export http_proxy="http://$host_ip:7890" export all_proxy="http://$host_ip:7890" 注意:代理软件务必开启 “Allow LAN”(允许局域网连接)。
Q2:WSL 中的常用工具(如 claude-code)敲字会有卡顿?引用自本站帖子
A2:这是因为 WSL 默认加载了 Windows 的环境变量。ZSH 在进行命令补全时会跨文件系统扫描 Windows 路径,导致严重的 I/O 延迟。
- 在
/etc/wsl.conf中关闭自动导入:
[interop] appendWindowsPath=false - 在
~/.zshrc中手动加载需要的 Windows 工具路径(避开卡顿的 PowerShell 路径):
Bash
# 手动添加常用的 Windows 工具 export PATH="$PATH:/mnt/d/Programs/Microsoft VS Code/bin" export PATH="$PATH:/mnt/c/Windows" # export PATH="$PATH:/mnt/c/Windows/system32" Q3:Maven/Java 无法连接网络,DNS 解析卡死?
A3:表现为 curl 正常,但 mvn 构建长时间卡在 Downloading,或 nslookup 报错 Truncated, retrying in TCP mode。
修改 Windows 用户目录下的 .wslconfig 配置文件:
[wsl2] dnsTunneling=false 原因:在 Mirrored 模式下,开启 dnsTunneling 后 Windows 会接管 DNS 请求。由于公司防火墙或 VPN 往往不识别这种隧道流量,会导致解析死锁。关闭它让 WSL2 回归标准 DNS 流程反而能解决问题。
Q4:为什么 Systemctl 命令报错,无法启动服务?
A4:WSL2 默认使用传统的 init 进程,而不启用 systemd,导致 systemctl start 等命令无法使用。
在 /etc/wsl.conf 中开启支持:
[boot] systemd=true 修改后,需在 Windows PowerShell 中执行 wsl --shutdown 重启 WSL。之后即可正常管理系统服务。
Q5:配置 Ubuntu 镜像源为阿里云
A5:手动替换为阿里云镜像源可以大幅提升 apt install 下载速度。
执行以下命令:
Bash
# 备份原文件 sudo cp /etc/apt/sources.list /etc/apt/sources.list.bak
# 将官方源替换为阿里云源 sudo sed -i 's/archive.ubuntu.com/mirrors.aliyun.com/g' /etc/apt/sources.list
sudo sed -i 's/security.ubuntu.com/mirrors.aliyun.com/g' /etc/apt/sources.list
# 更新索引 sudo apt update
最后附上我的.wslconfig 文件内容
PS C:\Users\Administrator> cat .\.wslconfig
[wsl2]
networkingMode=Mirrored
autoProxy=false
firewall=false
processors=8
memory=16GB
swap=0
dnsTunneling=false