如何在RancherOS系统中动态挂载外部USB硬盘?
Hey there! I’ve set up this exact workflow on RancherOS before, so let me break it down into actionable steps for you:
1. 创建udev规则实现自动挂载/卸载USB硬盘
RancherOS uses udev for hardware event handling, so we’ll create a rule to automatically mount USB drives when they’re plugged in, and clean up when they’re removed.
First, create a udev rule file:
sudo vi /etc/udev/rules.d/90-usb-drive.rulesPaste the following content into the file (adjust mount options if needed):
# Auto-mount USB drives ACTION=="add", SUBSYSTEM=="block", KERNEL=="sd*[0-9]", ENV{ID_BUS}=="usb", \ RUN+="/usr/bin/mkdir -p /mnt/usb-drives/%k", \ RUN+="/usr/bin/mount -o rw,relatime /dev/%k /mnt/usb-drives/%k", \ MODE="0775" # Auto-unmount and clean up when USB drives are removed ACTION=="remove", SUBSYSTEM=="block", KERNEL=="sd*[0-9]", ENV{ID_BUS}=="usb", \ RUN+="/usr/bin/umount -l /mnt/usb-drives/%k", \ RUN+="/usr/bin/rmdir /mnt/usb-drives/%k"%kwill be replaced with the device name (likesdb1) so each drive gets its own unique mount point under/mnt/usb-drives.- Add
uid=1000,gid=1000to the mount options if you need to match a specific user/group for container access.
Reload udev rules to apply changes immediately:
sudo udevadm control --reload-rules
2. 验证自动挂载功能
Plug in your USB drive and check if it’s mounted:
# List mounted drives mount | grep /mnt/usb-drives # Check the mount point directory ls /mnt/usb-drives
You should see your drive’s content listed. Try unplugging it— the mount point directory should be removed automatically.
3. 让容器访问USB挂载点
Now that the drive is mounted to /mnt/usb-drives/<device-name>, you can bind-mount this path directly into your containers.
Example: Run a container with access to the USB drive
docker run -d \ --name my-usb-aware-container \ -v /mnt/usb-drives/sdb1:/container/usb-mount \ nginx:alpine
- Replace
sdb1with your actual device name (you can find this withlsblkwhen the drive is plugged in). - The path
/container/usb-mountis where the drive will appear inside the container.
Handling dynamic plug/unplug
If you need containers to automatically detect drive changes, you have a couple options:
- Script-based monitoring: Use a small sidecar container or host script that watches
/mnt/usb-drivesand restarts/updates containers when drives are added/removed. - Docker Volume Plugin: For a more robust solution, use a plugin like
local-persist(install it on RancherOS viaros os install docker-volume-local-persist). This lets you define volumes that map to USB mount points, and containers can use these volumes dynamically.
4. 持久化配置(可选)
RancherOS preserves changes to /etc if you’ve set up a persistent state partition. To confirm your udev rule will survive reboots, check your state config:
ros config get rancher.state
If it points to a persistent device (like /dev/sda1), your rule will stay after reboot. If not, set it with:
ros config set rancher.state.dev "/dev/your-state-partition"
内容的提问来源于stack exchange,提问作者Chris Hunt

