在 Windows 中安装和配置 WSL2 与 Ubuntu

在 Windows 中安装和配置 WSL2 与 Ubuntu

讲述如何在 Windows 中通过 WSL2 使用 Ubuntu,设置启动目录和网络配置。

为什么选择 WSL2

WSL2 是 Windows Subsystem for Linux 的第二代架构,相比WSL1(Linux系统调用转换为Windows内核调用),WSL2是一台轻量级虚拟机,有真正的Linux内核,能原生运行Docker、容器、systemd等。而且我要部署的服务,不需要VMware这种完整的虚拟机,WSL2完全能胜任工作。

从零开始在 Windows 安装 WSL2 与 Ubuntu

1. 安装 PowerShell 7

1.1 更新 Windows Terminal

1.2 以管理员身份启动终端

1.3 安装 WinGet

输入以下命令安装 WinGet:

powershell
$progressPreference = 'silentlyContinue'
Install-PackageProvider -Name NuGet -Force | Out-Null
Install-Module -Name Microsoft.WinGet.Client -Force -Repository PSGallery | Out-Null
Write-Host "Using Repair-WinGetPackageManager cmdlet to bootstrap WinGet..."
Repair-WinGetPackageManager -AllUsers

1.4 使用 WinGet 安装 PowerShell 7

powershell
winget install Microsoft.PowerShell

1.5 设置 PowerShell 7 默认以管理员身份运行

2. 安装 WSL2 与 Ubuntu

在 PowerShell 中运行:

powershell
wsl --install -d Ubuntu

2.1 打开 Ubuntu

按 Win 键,搜索 Ubuntu 并打开。

2.2 设置 Linux 用户名和密码

text
Enter new UNIX username:
New password:
Retype new password:

2.3 确认 Ubuntu 正在使用 WSL2

在 PowerShell 中运行:

powershell
wsl --status
wsl -l -v

应看到:

text
NAME      STATE   VERSION
* Ubuntu  Running 2

如果不是,执行:

powershell
wsl --set-default Ubuntu

3. 更新 WSL 与 Ubuntu

打开 PowerShell,运行:

powershell
wsl --update

4. 设置 Ubuntu 默认启动目录

在 Linux 命令行中运行项目时,把文件放在 WSL 的 Linux 文件系统中通常性能更好;微软也明确建议使用类似 /home/<用户名>/Project 的路径,而不是 /mnt/c/...

在 PowerShell 中运行:

powershell
notepad $PROFILE

输入:

powershell
function wsl {
    if ($args.Count -eq 0) {
        & "$env:SystemRoot\System32\wsl.exe" -d Ubuntu --cd '~'
    } else {
        & "$env:SystemRoot\System32\wsl.exe" @args
    }
}

这样在终端中输入 wsl 时,默认会进入 /home/你的 Linux 用户名,而不是 /mnt/c/Users/你的 Windows 用户名/...

5. 配置 WSL 系统代理

打开 PowerShell,运行:

powershell
notepad $env:USERPROFILE\.wslconfig

修改为:

ini
[wsl2]
networkingMode=mirrored    # 启用镜像网络
autoProxy=true             # 让 WSL 使用 Windows 的 HTTP/HTTPS 代理信息
dnsTunneling=true
firewall=true

重启 WSL:

powershell
wsl --shutdown
wsl

测试:

bash
env | grep -i proxy

看到类似如下信息,说明配置成功:

text
https_proxy=http://127.0.0.1:你的代理软件端口
HTTPS_PROXY=http://127.0.0.1:你的代理软件端口
新故事即将发生
termux使用