背景简介
在KVM中配置virtio-9p直通文件系统,使得虚拟机能够直接访问宿主机的文件夹。
环境配置
- 系统:Debian 6.1.66-1 (2023-12-09) x86_64 GNU/Linux
- KVM:5.15.0-76-generic SMP mod_unload modversions
详细步骤
创建共享文件夹
指令:sudo mkdir
myserver@nfs-server:~$ sudo mkdir /mnt/sysdata/kvm/shared/nfs-server/data
使用virt-manager 创建共享
点击打开虚拟机信息界面
点击底部添加硬件
选择文件系统
,驱动程序选择 virtio-9p
,点击浏览
选择源路径
选择本地浏览
选择好源路径
后返回配置界面,输入目标路径
,点击完成
虚拟机内启用共享
重启虚拟机后,加载 virtio-9p模块:
myserver@nfs-server:~$ sudo modprobe 9pnet_virtio
挂载共享文件夹
myserver@nfs-server:~$ sudo mount -t 9p -o trans=virtio /nfs-data /nfs-data
- 第一个
/nfs-data
是virt-management
配置的目标路径。 - 第二个
/nfs-data
是虚拟机内系统目录路径。
查看挂载结果
myserver@nfs-server:~$ ls /nfs-data/
test
配置自动挂载
本次笔记采用 crontab @reboot
的方式实现自动挂载,也可根据自身需求选择不同的形式。
准备一个可执行脚本
root@nfs-server:~# mkdir reboot
root@nfs-server:~# nano reboot/at-reboot-shell.sh
root@nfs-server:~# cat reboot/at-reboot-shell.sh
#!/bin/sh
# 加载 virtio-9p模块
modprobe 9pnet_virtio
# 挂载共享文件夹
mount -t 9p -o trans=virtio /nfs-data /nfs-data
添加文件可执行权限
root@nfs-server:~# chmod +x reboot/at-reboot-shell.sh
配置启动执行
root@nfs-server:/home/myserver# crontab -e
no crontab for root - using an empty one
crontab: installing new crontab
root@nfs-server:/home/myserver# crontab -l
# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').
#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h dom mon dow command
@reboot /root/reboot/at-reboot-shell.sh
至此,虚拟机配置宿主机直通文件夹完成