在Windows环境下运行Linux工具链一直是开发者的痛点。传统虚拟机方案资源占用高,双系统切换又不够便捷。微软推出的WSL(Windows Subsystem for Linux)完美解决了这个痛点,而像Codex/Claude Code这类AI编程助手在WSL环境中的部署体验直接影响开发效率。
我花了三周时间实测了各种安装组合,最终整理出这套兼顾性能与稳定性的方案。相比官方文档,这个方案主要优化了三个痛点:
首先确认你的Windows版本:
bash复制winver
必须满足:
注意:WSL2会占用80%物理内存上限,需手动配置限制
以管理员身份运行PowerShell:
powershell复制wsl --install -d Ubuntu-22.04
dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart
dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart
安装后重启系统,执行版本升级:
powershell复制wsl --set-default-version 2
在%USERPROFILE%\.wslconfig中添加:
ini复制[wsl2]
memory=12GB # 根据物理内存调整
swap=4GB # 建议为内存的1/3
localhostForwarding=true
这个配置平衡了性能与稳定性:
WSL2的虚拟硬盘(VHDX)默认位于C盘,建议迁移到非系统盘:
powershell复制wsl --shutdown
wsl --export Ubuntu-22.04 D:\wsl\ubuntu.tar
wsl --import Ubuntu-22.04 D:\wsl\ D:\wsl\ubuntu.tar
安装NVIDIA驱动后,在WSL内执行:
bash复制curl -fsSL https://nvidia.github.io/libnvidia-container/gpgkey | sudo gpg --dearmor -o /usr/share/keyrings/nvidia-container-toolkit-keyring.gpg
sudo apt-get install -y nvidia-cuda-toolkit
验证安装:
bash复制nvidia-smi
nvcc --version
推荐使用conda管理环境:
bash复制wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh
bash Miniconda3-latest-Linux-x86_64.sh
conda create -n codex python=3.9
conda activate codex
安装插件:
生成SSH密钥:
bash复制ssh-keygen -t ed25519
cat ~/.ssh/id_ed25519.pub >> ~/.ssh/authorized_keys
wsl -d Ubuntu-22.04进入子系统localhost:2222连接安装htop和nvtop:
bash复制sudo apt install htop nvtop
常用监控命令:
bash复制htop # 查看CPU/内存
nvtop # 查看GPU状态
df -h # 磁盘空间
症状:nvidia-smi正常但torch.cuda.is_available()返回False
解决方案:
bash复制sudo apt install nvidia-cuda-toolkit
conda install pytorch torchvision torchaudio pytorch-cuda=11.7 -c pytorch -c nvidia
临时解决方案:
powershell复制wsl --shutdown
netsh winsock reset
永久方案:在.wslconfig中添加:
ini复制[wsl2]
kernelCommandLine = vsyscall=emulate
监控内存使用:
bash复制watch -n 1 free -m
若发现泄漏,定期执行:
powershell复制wsl --shutdown
bash复制git clone https://github.com/microsoft/WSL2-Linux-Kernel.git
.config文件:makefile复制CONFIG_PERF_EVENTS=y
CONFIG_DEBUG_INFO=y
bash复制make -j$(nproc)
sudo cp vmlinux /usr/lib/modules/$(uname -r)/build/
在/etc/wsl.conf中添加:
ini复制[automount]
options = "metadata,uid=1000,gid=1000,umask=22,fmask=111"
安装zsh和插件:
bash复制sudo apt install zsh
sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"
git clone https://github.com/zsh-users/zsh-autosuggestions ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autosuggestions
必备工具列表:
bash复制sudo apt install -y \
build-essential \
cmake \
git-lfs \
ninja-build \
libssl-dev \
libffi-dev \
python3-dev
这套方案经过三个月的生产环境验证,在以下场景表现优异:
最后分享一个冷知识:WSL2的/mnt/c目录访问Windows文件比原生Linux慢5倍,建议将工作区放在WSL内部文件系统