How to Manage Virtual Machines Using `virsh` on Debian 12 Bookworm

How to Manage Virtual Machines Using virsh on Debian 12 Bookworm

Virtualization has become a cornerstone of modern IT infrastructure, enabling efficient resource usage and greater flexibility. On Debian 12 Bookworm, one of the most powerful tools for managing virtual machines (VMs) is virsh, a command-line utility provided by the libvirt package. virsh allows administrators to manage VMs and perform tasks such as creating, starting, stopping, and modifying virtual machines—without needing a graphical interface.

This article provides a comprehensive guide to managing virtual machines using virsh on a Debian 12 Bookworm system. It is intended for system administrators, developers, and power users who are comfortable working in the terminal.

1. Introduction to virsh and libvirt

virsh is a CLI utility used to manage VMs on systems that use libvirt as the virtualization API. It supports several hypervisors, but is most commonly used with KVM/QEMU on Linux.

Why use virsh?

  • Scriptable and automatable
  • No GUI required
  • Full VM lifecycle control
  • Works well on headless servers
  • Strong integration with other tools like virt-install and virt-manager

2. Installing the Necessary Packages

Before using virsh, you need to install the libvirt ecosystem and KVM/QEMU for virtualization support. On Debian 12 Bookworm, use the following commands:

sudo apt update
sudo apt install qemu-kvm libvirt-daemon-system libvirt-clients bridge-utils virtinst virt-manager
  • qemu-kvm: The actual hypervisor
  • libvirt-daemon-system: Allows system-wide access to libvirt
  • libvirt-clients: Contains virsh
  • virtinst: Includes virt-install for creating VMs
  • virt-manager: Optional GUI manager for VMs

You can verify the installation by checking if your user is part of the libvirt group:

groups $USER

If not, add your user:

sudo usermod -aG libvirt $USER

Then reboot or relogin to apply group changes.


3. Enabling and Starting libvirtd

The libvirtd service must be running for virsh to function:

sudo systemctl enable libvirtd
sudo systemctl start libvirtd

Check the status:

sudo systemctl status libvirtd

You can now connect to the default system URI:

virsh connect qemu:///system

If successful, you’ll enter an interactive virsh shell. To exit, type exit.


4. Understanding Virtualization Concepts

Before diving into virsh, it’s essential to understand some foundational virtualization terms:

  • Domain: In libvirt terms, a VM is called a “domain.”
  • Snapshot: A saved state of a VM that can be restored later.
  • Volume: A virtual disk, usually stored in a storage pool.
  • Storage pool: A directory or physical disk that holds VM volumes.
  • Network: A virtual bridge or NAT network assigned to VMs.

These concepts are all managed using virsh commands.


5. Basic virsh Commands Overview

Here are some commonly used virsh commands:

TaskCommand
List VMsvirsh list --all
Start a VMvirsh start <vm-name>
Shutdown a VMvirsh shutdown <vm-name>
Force-off a VMvirsh destroy <vm-name>
Undefine a VMvirsh undefine <vm-name>
Suspend/Resumevirsh suspend/resume <vm-name>
Autostart a VMvirsh autostart <vm-name>
View VM Infovirsh dominfo <vm-name>

6. Creating and Managing Virtual Machines

Creating a VM with virt-install

virsh alone doesn’t create VMs, but it manages them. Use virt-install to create a VM:

sudo virt-install \
--name debian-vm \
--ram 2048 \
--disk path=/var/lib/libvirt/images/debian-vm.img,size=10 \
--vcpus 2 \
--os-type linux \
--os-variant debian12 \
--network network=default \
--graphics none \
--console pty,target_type=serial \
--location 'http://deb.debian.org/debian/dists/bookworm/main/installer-amd64/' \
--extra-args 'console=ttyS0,115200n8'

This creates a Debian VM with 2GB RAM, 2 CPUs, and a 10GB virtual disk.

Viewing and Interacting with the VM

To view VMs:

virsh list --all

To connect to the VM console:

virsh console debian-vm

To reboot the VM:

virsh reboot debian-vm

7. Managing VM Storage and Snapshots

Creating and Managing Storage Pools

To list available storage pools:

virsh pool-list --all

To define a new storage pool:

virsh pool-define-as \
default dir --target /var/lib/libvirt/images
virsh pool-start default
virsh pool-autostart default

Managing VM Disks

To create a new disk:

qemu-img create -f qcow2 /var/lib/libvirt/images/mydisk.qcow2 20G

Attach to a VM:

virsh attach-disk debian-vm /var/lib/libvirt/images/mydisk.qcow2 vdb --persistent

Snapshots

Create a snapshot:

virsh snapshot-create-as --domain debian-vm snapshot1 "Initial install" --disk-only --atomic

List snapshots:

virsh snapshot-list debian-vm

Revert to a snapshot:

virsh snapshot-revert debian-vm --snapshotname snapshot1

8. Network Configuration and Virtual Interfaces

Libvirt uses virtual bridges for networking.

Listing Available Networks

virsh net-list --all

To create a new virtual bridge network:

virsh net-define bridge-net.xml
virsh net-start bridge-net
virsh net-autostart bridge-net

Sample bridge-net.xml:

<network>
  <name>bridge-net</name>
  <bridge name='virbr1' stp='on' delay='0'/>
  <ip address='192.168.100.1' netmask='255.255.255.0'>
    <dhcp>
      <range start='192.168.100.2' end='192.168.100.254'/>
    </dhcp>
  </ip>
</network>

9. Automating VM Management Tasks

You can create scripts to automate common tasks. For example:

VM Backup Script

#!/bin/bash
VM_NAME="debian-vm"
DATE=$(date +%F)
BACKUP_DIR="/backup/$VM_NAME"

mkdir -p $BACKUP_DIR

virsh snapshot-create-as $VM_NAME "$VM_NAME-snapshot-$DATE"
virsh dumpxml $VM_NAME > $BACKUP_DIR/$VM_NAME.xml
cp /var/lib/libvirt/images/$VM_NAME.img $BACKUP_DIR/$VM_NAME-$DATE.img

Make it executable and run it periodically using cron.


10. Troubleshooting and Useful Tips

  • Permission Errors: Make sure your user is in the libvirt group.
  • VM won’t start: Use virsh dominfo <vm> and virsh start <vm> with --console for logs.
  • Networking Issues: Check iptables rules and ensure virbr0 exists.
  • Stuck Console: Use Ctrl+] to exit from virsh console.
  • Storage Pool Unavailable: Check permissions and whether the directory exists.

Useful command to get the full XML configuration of a VM:

virsh dumpxml debian-vm

This can be edited and redefined with:

virsh define debian-vm.xml

11. Conclusion

Managing virtual machines with virsh on Debian 12 Bookworm offers a powerful, flexible, and scriptable approach to virtualization. While the learning curve can be steep, especially without a GUI, the command-line control provided by virsh is unparalleled for automation and advanced configurations.

Whether you’re running a homelab, managing cloud-based virtual machines, or automating development environments, learning virsh gives you the tools to confidently handle VMs in a professional and scalable way.

With Debian 12 Bookworm offering stable and up-to-date packages, it’s an ideal base for building virtualized environments using KVM and libvirt.