For AI agents: the complete documentation index is available at https://www.tteam.icu/llms.txt, the full documentation bundle is available at https://www.tteam.icu/llms-full.txt, and this page is available as Markdown at https://www.tteam.icu/ops/other/libvirt.md.

libvirt

安装

Debian/Ubuntu
Red Hat/Rocky/Alma/CentOS
apt update
apt install -y \
  virt-manager \
  virtinst \
  libvirt-daemon-system \
  qemu-system-x86 \
  qemu-utils \
  bridge-utils \
  osinfo-db

其中 virtinst 提供 virt-installqemu-utils 提供 qemu-img。如果只在服务器上使用命令行,可以不安装 virt-manager

systemctl enable --now libvirtd

# 非 root 用户管理虚拟机时使用,执行后需要重新登录
usermod -aG libvirt,kvm "$USER"

可以先确认宿主机是否支持硬件虚拟化:

lscpu | grep -i virtualization

默认 NAT 网络

libvirt 默认会创建一个名为 default 的 NAT 网络,虚拟机可以通过它访问外网。

virsh net-list --all

virsh net-start default

# 设置开机自动激活
virsh net-autostart default

如果需要查看默认网络的配置:

virsh net-dumpxml default

导入 qcow2 镜像创建虚拟机

这里适合导入已经能启动的系统盘,例如提前做好的 Debian qcow2 模板。--import 不会进入安装流程,而是直接把已有磁盘作为启动盘。

virt-install \
  --name instance \
  --memory 16384 \
  --vcpus 8 \
  --cpu host-passthrough \
  --disk path=/data/images/debian12_template_v2.qcow2,format=qcow2,bus=virtio \
  --import \
  --os-variant generic \
  --network network=default,model=virtio \
  --graphics vnc,listen=0.0.0.0 \
  --video virtio \
  --console pty,target_type=serial
Warning

--graphics vnc,listen=0.0.0.0 会让 VNC 监听所有网卡,生产环境需要配合防火墙、安全组或 SSH 隧道限制访问。

如果本机的 osinfo-db 能识别具体发行版,可以用更精确的 --os-variant

osinfo-query os | grep -i debian

常用检查命令:

# 查看虚拟机
virsh list --all

# 查看 VNC 端口
virsh vncdisplay instance

# 关机、启动、重启
virsh shutdown instance
virsh start instance
virsh reboot instance

创建并挂载数据盘

先创建一个 qcow2 数据盘:

qemu-img create -f qcow2 /data/images/vm/hw-902c-arm-1-data.qcow2 100G

挂载到虚拟机:

virsh attach-disk hw-902c-arm-1 \
  /data/images/vm/hw-902c-arm-1-data.qcow2 \
  vdb \
  --driver qemu \
  --subdriver qcow2 \
  --targetbus virtio \
  --cache none \
  --persistent

如果是批量创建,可以用变量保留原始命名习惯:

for i in 1 2 3; do
  vm_name="hw-902c-arm-${i}"
  data_disk="/data/images/vm/${vm_name}-data.qcow2"

  qemu-img create -f qcow2 "$data_disk" 100G

  virsh attach-disk "$vm_name" \
    "$data_disk" \
    vdb \
    --driver qemu \
    --subdriver qcow2 \
    --targetbus virtio \
    --cache none \
    --persistent
done

常用维护命令

# 查看虚拟机配置
virsh dumpxml instance

# 编辑虚拟机配置
virsh edit instance

# 分离数据盘
virsh detach-disk hw-902c-arm-1 vdb --persistent

# 删除虚拟机定义,不删除磁盘文件
virsh undefine instance