WSL2 虚拟机

1. WSL2 虚拟化技术原理

  • 架构:基于 Hyper-V 精简虚拟化(Micro-VM),运行独立 Linux 内核。
  • 隔离性:拥有独立进程空间、内存、文件系统、网络栈,接近完整虚拟机。
  • 资源机制:CPU/内存动态分配,Windows 可回收;磁盘为 ext4 格式 vhdx 虚拟磁盘。
  • 与传统 VM 区别:无 BIOS/UEFI,不支持 ISO 引导安装,仅支持 rootfs 镜像导入;启动秒级、与 Windows 深度集成。
  • 与 WSL1 区别:WSL1 为系统调用翻译层;WSL2 支持完整系统调用、Docker、systemd。

2. WSL2 安装 Linux(安装包方式)

2.1 支持官方 WSL 镜像的发行版

Ubuntu、Debian、Alpine、Fedora、Arch、Kali、openSUSE、AlmaLinux

2.2 资源获取

2.3 安装步骤

  1. 开启功能(管理员 PowerShell)
wsl --install
wsl --update
wsl --set-default-version 2
  1. 导入镜像(以 Ubuntu 为例)
mkdir D:\WSL\Ubuntu2404
wsl --import Ubuntu2404 D:\WSL\Ubuntu2404 ubuntu-2404-wsl.rootfs.tar.gz --version 2
  1. 初始化用户(进入 WSL 后执行)
useradd -m -G sudo ubuntu
passwd ubuntu
echo -e "[user]\ndefault=ubuntu" | sudo tee /etc/wsl.conf

3. WSL2 虚拟机管理命令

3.1 启动(含用户与权限原理)

# 默认启动(使用 /etc/wsl.conf 默认用户,无密码)
wsl -d Ubuntu2404

# 指定用户启动(Windows 直接授权,无需密码验证)
wsl -d Ubuntu2404 -u ubuntu
wsl -d Ubuntu2404 -u root

权限原理:本地启动由 Windows 全权授权,不经过 Linux PAM 密码验证;仅远程 SSH 需密码。

3.2 停止

wsl -t Ubuntu2404        # 停止单个
wsl --shutdown           # 停止所有

3.3 卸载(注销)

wsl --unregister Ubuntu2404

仅删除注册信息,ext4.vhdx 数据保留。

3.4 备份与导入

备份为 tar / tar.gz

wsl --export Ubuntu2404 D:\backup\ubuntu.tar
wsl --export Ubuntu2404 D:\backup\ubuntu.tar.gz

从 tar / tar.gz 导入

wsl --import UbuntuNew D:\WSL\UbuntuNew D:\backup\ubuntu.tar.gz --version 2

原地恢复目录(vhdx 存在时)

wsl --import-in-place Ubuntu2404 D:\WSL\Ubuntu2404\ext4.vhdx

3.5 开机自启

任务计划程序:

  • 触发器:计算机启动时
  • 操作:启动程序 wsl.exe
  • 参数:-d Ubuntu2404 -u root sleep infinity
  • 勾选:最高权限、不管用户是否登录

4. 存储与文件共享机制

4.1 WSL 内部存储

  • 路径:安装目录\ext4.vhdx(ext4 格式)
  • 访问:Windows 地址栏输入 \\wsl$\Ubuntu2404

4.2 默认挂载 Windows 磁盘

/mnt/c
/mnt/d
  • 性能较低,开发项目建议放 WSL 内部。

4.3 自定义挂载

sudo mkdir /mnt/ssd
sudo mount -t drvfs E: /mnt/ssd

4.4 系统级挂载配置(/etc/wsl.conf)

[automount]
enabled = true
options = "metadata,umask=0022,fmask=0022"
mountFsTab = true

5. WSL2 网络类型

5.1 NAT 模式(默认)

  • WSL 独立内网 IP(172.x.x.x)
  • 可访问外网与 Windows
  • 外部访问需端口转发

5.2 Mirror 镜像模式(Win11 推荐)

  • WSL 与 Windows 共用同一 IP
  • 端口直接互通,无需转发

配置 .wslconfig

[wsl2]
networkingMode=mirrored
dnsTunneling=true
firewall=true

5.3 Bridge 桥接模式

  • WSL 获取局域网独立 IP(同网段)
  • 需要 Hyper-V 虚拟交换机
[wsl2]
networkingMode=bridged
vmSwitch=ExternalSwitch

6. 远程使用:终端与桌面

6.1 远程终端(SSH)

  1. 安装并启动 SSH
sudo apt install openssh-server
sudo systemctl enable --now ssh
  1. 连接
ssh 用户名@WSL_IP
  • 局域网可通过 Windows IP + 端口转发访问

6.2 远程桌面(RDP + 桌面环境)

  1. 安装轻量桌面与 xrdp
sudo apt install xfce4 xfce4-goodies xrdp
sudo sed -i 's/3389/3390/' /etc/xrdp/xrdp.ini
sudo systemctl enable --now xrdp
  1. Windows 远程桌面连接
WSL_IP:3390

6.3 WSLg 原生 GUI(Win11)

  • 直接运行 Linux 图形程序
  • 无需 xrdp,自动集成显示