WSL 环境搭建 Ubuntu

WSL 环境搭建 Ubuntu

前言

最近将开发环境从云切换到本地, 需要搭建 Docker 服务, 因此记录下 Windows 下搭建 WSL 的过程. 需要开启 Hyper-V.

搭建步骤

下载镜像

  1. 列举镜像: wsl -l -o
  2. 安装镜像: wsl --install -d Ubuntu-22.04
  3. 根据步骤设置超级用户名称与密码
  4. 设置默认镜像 wsl -s <DistributionName>
  5. 可安装多个镜像, wsl --install -d <DistributionName>

进入系统

  1. 进入默认的镜像: wsl
  2. 进入指定的镜像: wsl -d <DistributionName>
  3. 查看环境变量: env

修改 apt 包镜像源

  1. 进入 apt 目录: /etc/apt
  2. 切换超管用户: su, 输入密码
  3. 备份源文件: cp sources.list sources.list.back
  4. 编辑替换域名为 mirrors.aliyun.com
  5. 重新加载 apt update

额外

忘记用户密码

  1. 执行: wsl -u root
  2. 重设密码: passwd <username>, username 为安装时指定的用户名称
  3. 执行: exit

用户切换

  1. 切换超管用户: su
  2. 切换普通用户: su - <username>

迁移/备份系统卷

系统卷默认在 C 盘中, 占用太多空间, 可以迁移到其他盘符

  1. 导出到文件: wsl --export --vhd <DistributionName> ext4.vhdx
  2. 移动文件到特定目录
  3. (仅迁移,删除原有的卷): wsl --unregister <DistributionName>
  4. 导入: wsl --import-in-place <Distribution Name> ext4.vhdx

迁移后默认用户丢失

编辑文件 nano /etc/wsl.conf

1
2
[user]
default=<username>

避免继承 win10 环境 path

编辑文件 nano /etc/wsl.conf

1
2
[interop]
appendWindowsPath = false

删除特定系统

wsl --unregister <DistributionName>

与宿主机之间通讯

wsl宿主机 通讯:

  1. 执行 cat /etc/resolv.conf
  2. 查找 nameserver , 值为宿主机

宿主机wsl 通讯:

wsl 共享 Windows 的 IP, 因此在 wsl 运行的 端口 123 的服务在宿主机上可直接访问 https://localhost:123

与宿主机文件传输

  1. 进入 wls
  2. 执行 explorer.exe .

宿主机直接访问特定镜像文件管理

资源管理器直接访问 \\wsl$\<DistributionName>

代理设置1

设置

1
2
export http_proxy=http://192.168.240.1:7890
export https_proxy=http://192.168.240.1:7890

取消

1
2
unset http_proxy
unset https_proxy

代理设置2

1
2
3
4
nano /etc/environment 
http_proxy=http://192.168.240.1:7890
https_proxy=http://192.168.240.1:7890
no_proxy=localhost,127.0.0.0/8,127.0.1.1

包管理器

  1. apt
  2. snap