Docker 容器中使用宿主机 USB 设备
2025/12/30约 289 字小于 1 分钟
有时候我们需要在 Docker 容器或 Devcontainer 开发容器环境下使用宿主机 USB 设备,例如调试单片机、连接 USB 串口设备等。本文介绍在 Windows WSL 和 macOS 主机上实现该功能的方法。
WSL Docker
window 主机使用usbipd-win
usbipd list
usbipd bind --busid=<BUSID>
usbipd attach --wsl --busid=<BUSID>Docker 容器直接挂载 /dev 目录就能直接用了,例如:docker run --rm -it --privileged -v /dev:/dev debian:bookworm bash
Devcontainer json 配置:
{
// ...
"mounts": [
// Allow attaching USB devices to running container
"source=/dev,target=/dev,type=bind"
]
// ...
}Mac Docker
macOS 主机使用usbip,需要 rust 环境
git clone https://github.com/jiegec/usbip.git
cd usbip
cargo build --release
cargo run --example host容器安装 usbip client
# Debian
docker run --rm -it --privileged --pid=host debian:bookworm bash
apt update && apt install -y usbip
# Ubuntu / Debian
docker run --rm -it --privileged --pid=host ubuntu:22.04 bash
apt update && apt install -y linux-tools-virtual hwdata
update-alternatives --install /usr/local/bin/usbip usbip $(command -v ls /usr/lib/linux-tools/*/usbip | tail -n1) 20
# Alpine
docker run --rm -it --privileged --pid=host alpine
apk update && apk add -y linux-tools-usbip hwdata容器连接宿主机 USB 设备
# List available devices
usbip list -r $remote_ip
# Attach to a device
usbip attach -r $remote_ip -b $bus_id