24.2. Creating and Installing Guests
A guest consists of a libvirt domain definition and the storage it boots from. The definition is XML stored by libvirt; the storage is one or more files, volumes, or block devices. Keeping those two artifacts separate makes backup, cloning, and recovery understandable: the XML says how to start the machine, and the disk holds the machine's state.
24.2.1. Virtual Disks, Storage Pools, and Image Formats
Libvirt storage pools give names to directories, LVM volume groups, iSCSI targets, and other storage sources. A directory pool is the simplest and is enough for this chapter. On virt1, in the root shell, create the directory and define the pool:
# install -d -m 755 /var/lib/libvirt/images/handbook
# virsh -c qemu:///system pool-define-as handbook dir --target /var/lib/libvirt/images/handbook
# virsh -c qemu:///system pool-build handbook
# virsh -c qemu:///system pool-start handbook
# virsh -c qemu:///system pool-autostart handbook
The five commands form one setup sequence. The first creates the directory;
pool-define-as records the pool in libvirt; pool-build prepares the
target; pool-start activates it now; pool-autostart makes it active
after the next boot. Each virsh subcommand prints a one-line
confirmation; a captured example of the same sequence appears with the
tiny pool in Section 24.5.3. Check the pool:
# virsh -c qemu:///system pool-info handbook
Name: handbook
UUID: 56c97997-c13d-4c01-988e-31e8282f1903
State: running
Persistent: yes
Autostart: yes
Capacity: 97.87 GiB
Allocation: 2.24 GiB
Available: 95.63 GiB
The capacity is the filesystem's capacity, not a reservation for libvirt.
Allocation counts the files the pool can see, and Available is what
remains. A qcow2 file can grow up to its virtual size, so a pool with
plenty of Available can still fill if several guests are provisioned with
large virtual disks.
Download the Debian 13 cloud image that the practice guest uses as its base. On virt1, in the root shell:
# curl -fL --retry 3 -o /var/lib/libvirt/images/handbook/debian-13-genericcloud-amd64.qcow2 https://cloud.debian.org/images/cloud/trixie/latest/debian-13-genericcloud-amd64.qcow2
The command prints a progress meter while it downloads. Verify the download against the checksums published beside the image on cloud.debian.org before using it, following the verification procedure of Chapter 2.
Two image formats dominate. Raw images map guest sectors directly to file offsets: simple, fast, and fully allocated unless the file is sparse. qcow2 images store metadata and copy-on-write clusters: they support backing files, snapshots, compression, and thin allocation, at some CPU and fragmentation cost. A comparison for a virtualization host:
| Property | raw | qcow2 |
|---|---|---|
| Allocation | Full virtual size unless the file is sparse | Grows with written clusters |
| Backing files | Not supported | Supported, including chains |
| Snapshots | External only, managed by the host | Internal and external; libvirt uses both |
| Compression | No native compression | zlib or zstd compression per cluster |
| Performance | Slightly lower overhead; predictable layout | More metadata; allocation and discard costs |
| Repair | No image-level checker | qemu-img check can detect and repair some damage |
| Best fit | Preallocated volumes, LVM, SAN LUNs, simple backups | Lab guests, clones, snapshots, thin storage |
The base cloud image is never written to. A writable overlay records only
changes, with the base as its backing file. qemu-img create is the tool;
the options used here:
| Option | Description |
|---|---|
-f FMT |
Format of the new image, such as qcow2 |
-b FILE |
Backing file the new image records |
-F FMT |
Format of the backing file |
size |
Virtual size, given as the final argument |
On virt1, as john:
$ sudo qemu-img create -f qcow2 -F qcow2 -b /var/lib/libvirt/images/handbook/debian-13-genericcloud-amd64.qcow2 /var/lib/libvirt/images/handbook/handbook-web.qcow2 10G
Formatting '/var/lib/libvirt/images/handbook/handbook-web.qcow2', fmt=qcow2 cluster_size=65536 extended_l2=off compression_type=zlib size=10737418240 backing_file=/var/lib/libvirt/images/handbook/debian-13-genericcloud-amd64.qcow2 backing_fmt=qcow2 lazy_refcounts=off refcount_bits=16
-F qcow2 states the backing file's format; without it, QEMU may refuse to
open the image when probing is disabled for security. The virtual size is
10 GiB, but the file starts nearly empty. Debian's libvirt runs QEMU
processes as the unprivileged libvirt-qemu user. When a domain starts,
libvirt's security driver relabels the disk files that the domain opens to
that user, and it records the previous owners and restores them when the
domain stops, so an image created outside libvirt - by root, with
qemu-img - does not need to be chowned by hand before the guest can use
it. Ownership still matters for tools you run yourself: an ordinary user
cannot inspect a root-owned image, and the relabeling only happens through
libvirt. qemu-img info shows what the file contains, and its -U form
also works while a guest has the image open. The capture below was taken
after the guest of Section 24.2.2 had booted and cloud-init had installed
its packages, so the overlay has grown from the near-empty state of a
freshly created image:
$ sudo qemu-img info -U /var/lib/libvirt/images/handbook/handbook-web.qcow2
image: /var/lib/libvirt/images/handbook/handbook-web.qcow2
file format: qcow2
virtual size: 10 GiB (10737418240 bytes)
disk size: 351 MiB
cluster_size: 65536
backing file: /var/lib/libvirt/images/handbook/debian-13-genericcloud-amd64.qcow2
backing file format: qcow2
Format specific information:
compat: 1.1
compression type: zlib
lazy refcounts: false
refcount bits: 16
corrupt: false
extended l2: false
Child node '/file':
filename: /var/lib/libvirt/images/handbook/handbook-web.qcow2
protocol type: file
file length: 351 MiB (367591424 bytes)
disk size: 351 MiB
Without -U, qemu-img info may refuse to read a locked image, which is
why the option belongs in the command above. disk size is the host space
consumed so far; virtual size is what the guest sees. With the guest shut
down, the closed image can also be checked for consistency:
$ sudo qemu-img check /var/lib/libvirt/images/handbook/handbook-web.qcow2
No errors were found on the image.
5598/163840 = 3.42% allocated, 4.45% fragmented, 0.00% compressed clusters
Image end offset: 367919104
qemu-img check requires the image to be closed, which is why it follows a
shutdown rather than running beside info. A nonzero exit status or a leak
report from qemu-img check is a reason to stop and restore from backup
before starting the guest. qemu-img check -r all can repair some metadata
damage, but repair is not a substitute for a known-good copy; it may
discard clusters whose references are broken.
Figure 24.2. The read-only base image, the writable overlay, and an external snapshot overlay form a chain. Reads that the overlay does not contain fall through to the layer below.
A chain is only as portable as its paths. Moving or renaming a backing file
breaks the overlay unless the XML and the qcow2 header are updated
together. Relative backing paths are resolved from the overlay's directory,
which helps when a pool is moved as a unit; absolute paths are simpler but
require rewriting on migration. Keep the base image in the same pool and do
not delete it while any overlay references it. Additional data disks are
created with the same qemu-img create command - -f raw makes a
preallocated raw volume, the better choice for a latency-sensitive guest on
LVM or a separate SSD-backed pool; Section 24.4.2 attaches a qcow2 data disk
to the running guest.
24.2.2. Installing Debian with virt-install or virt-manager
There are two normal installation paths. virt-manager is a graphical
application that guides you through choosing an installation source,
memory, CPU count, storage, and network, then opens a console for the
installer. virt-install is the command-line equivalent and is the path
used on headless servers and in automation. Both create the same libvirt
domain XML; the difference is the interface and the amount of typing.
On a workstation, start virt-manager, choose File > New Virtual
Machine, select Local install media (ISO image or CDROM), and choose a
Debian netinst or DVD image. On the next page allocate memory and CPUs,
then create or select storage. Keep Enable storage for this virtual
machine selected and choose qcow2 for a lab or raw/LVM for a
preallocated volume. On the network page choose the libvirt network or
bridge. The final page offers Finish and, with Start installation
selected, opens a graphical console. The Debian installer then runs exactly
as it would on physical hardware; the guest sees virtio disks and NICs,
which Debian's installer supports natively.
For a remote host, connect virt-manager to
qemu+ssh://john@virt1/system through File > Add Connection. The SSH
user needs access to the system connection on the host. The console travels
through the SSH tunnel; a separate VNC port does not need to be exposed.
The command-line installer needs a source, a name, memory, vCPUs, storage, and a network. The options used in this chapter:
| Option | Meaning |
|---|---|
--connect URI |
Libvirt connection to use; qemu:///system for host guests |
--name NAME |
Domain name, unique on the connection |
--memory MiB |
Initial and maximum memory in MiB unless maxmemory is given |
--vcpus N[,maxvcpus=M] |
Current vCPUs and the maximum for hotplug |
--disk path=...,format=...,bus=virtio |
Disk file, format, and bus |
--disk ...,device=cdrom,readonly=on |
Read-only CD-ROM, used for the cloud-init seed |
--cdrom PATH |
Installation ISO; mutually exclusive with --import |
--import |
Boot an existing disk instead of running an OS installer |
--osinfo ID |
Operating-system profile from libosinfo, such as debian13 |
--network network=NAME,model=virtio |
Libvirt network and NIC model |
--graphics none or --graphics vnc |
Console type; none for headless import |
--video vga |
Emulated display adapter for the guest |
--channel ... |
Add a virtio serial channel, used by the guest agent |
--noautoconsole |
Do not open a console after creating the domain |
An ISO installation on virt1, as john, would begin with a command like this one; the cloud-image path below is the one the chapter's exercises use, and it shares these options:
$ sudo virt-install --connect qemu:///system --name debian-install --memory 2048 --vcpus 2 --disk size=20,format=qcow2,bus=virtio --cdrom /home/john/debian-handbook/virtualization/debian-13.7.0-amd64-netinst.iso --osinfo debian13 --network network=default,model=virtio --graphics vnc
The ISO path is spelled out in full because virt-install runs elevated
and a root shell expands ~ to /root; place the ISO where the daemon can
read it. After the installer finishes and the guest reboots,
virsh domstate debian-install reports running, and the guest's disk is
in the pool selected by the --disk option. If virt-install opens a VNC
console instead of a text console, connect with
virt-viewer --connect qemu:///system debian-install; a text console can be
opened with virsh console debian-install and left with Ctrl+].
The cloud-image path avoids the interactive installer. The practice guest
is created from the overlay prepared above, a NoCloud seed ISO, and an
explicit virtio disk and network. If you are following along, build the
seed ISO first: Section 24.2.4 shows the two YAML files it is built from
and the cloud-localds command that assembles them. On virt1, as john:
$ sudo virt-install --connect qemu:///system --name handbook-web --memory 1024 --vcpus 1,maxvcpus=2 --disk path=/var/lib/libvirt/images/handbook/handbook-web.qcow2,format=qcow2,bus=virtio --disk path=/var/lib/libvirt/images/handbook/handbook-web-seed.iso,device=cdrom,readonly=on --import --osinfo debian13 --network network=handbook-nat,model=virtio --video vga --graphics none --channel unix,target.type=virtio,target.name=org.qemu.guest_agent.0 --noautoconsole
Starting install...
Creating domain... | 00:00
Domain creation completed.
--import tells libvirt that the first disk is already bootable, so no
installer media is booted; the domain is both defined and started, and the
guest boots immediately with cloud-init running on first boot.
--noautoconsole keeps the command from attaching a console and makes it
suitable for a script. The second disk is a read-only CD-ROM carrying
cloud-init's seed data, built in Section 24.2.4. maxvcpus=2 records a
hotplug ceiling while starting with one vCPU, which the resource exercises
later use.
While the guest boots, its devices can be listed from the host. On virt1, as john:
$ virsh -c qemu:///system domblklist handbook-web
Target Source
------------------------------------------------------------------
vda /var/lib/libvirt/images/handbook/handbook-web.qcow2
sda /var/lib/libvirt/images/handbook/handbook-web-seed.iso
vda is the virtio block disk; sda is the emulated SATA CD-ROM. The
target letters are assigned by the bus, not by the order in which you
created the files. domiflist shows the network:
$ virsh -c qemu:///system domiflist handbook-web
Interface Type Source Model MAC
------------------------------------------------------------------
vnet1 network handbook-nat virtio 52:54:00:ec:63:66
The vnet1 interface is a host tap device created by libvirt for this run
of the guest; the vnetN name is assigned by the host when the guest
starts, while the MAC is generated once for the domain and is persistent. A
cloned guest that keeps its MAC will confuse DHCP and the host's neighbor
table.
virt-install is convenient, but it is not a configuration manager. The
domain XML it produces should be treated as the source of truth after
creation; later changes belong in virsh edit or in the libvirt API, not in
a re-run of the original command. Re-running virt-install with the same
name fails with "Guest name is already in use" rather than modifying the
existing domain.
24.2.3. Virtio Devices, Guest Agents, and Guest Drivers
Virtio is the paravirtualized device family designed for KVM. The guest sees a simple, standardized device and the host handles I/O through shared memory rings instead of emulating real hardware registers. Debian's kernel includes the virtio drivers, so a Debian guest uses them without installing extra packages. On the guest, as john, the PCI inventory shows the devices:
$ lspci -k | grep -A2 -i virtio
01:00.0 Ethernet controller: Red Hat, Inc. Virtio 1.0 network device (rev 01)
Subsystem: Red Hat, Inc. QEMU
Kernel driver in use: virtio-pci
02:00.0 USB controller: Red Hat, Inc. QEMU XHCI Host Controller (rev 01)
Subsystem: Red Hat, Inc. Device 1100
03:00.0 Communication controller: Red Hat, Inc. Virtio 1.0 console (rev 01)
Subsystem: Red Hat, Inc. QEMU
Kernel driver in use: virtio-pci
04:00.0 SCSI storage controller: Red Hat, Inc. Virtio 1.0 block device (rev 01)
Subsystem: Red Hat, Inc. QEMU
Kernel driver in use: virtio-pci
05:00.0 Unclassified device [00ff]: Red Hat, Inc. Virtio 1.0 balloon (rev 01)
Subsystem: Red Hat, Inc. QEMU
Kernel driver in use: virtio-pci
06:00.0 Unclassified device [00ff]: Red Hat, Inc. Virtio 1.0 RNG (rev 01)
Subsystem: Red Hat, Inc. QEMU
Kernel driver in use: virtio-pci
The network, console, block, balloon, and random-number devices are all
virtio and use the virtio-pci transport. The USB controller between them
is emulated hardware; grep -A2 prints it as trailing context after the
network device, not because it matched. The guest sees vda rather than
sda for the disk and enp1s0 rather than eth0 for the NIC; the names
follow the PCI topology, not the device model. Compare lsblk:
$ lsblk
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINTS
sr0 11:0 1 366K 1 rom
vda 254:0 0 10G 0 disk
├─vda1 254:1 0 9.9G 0 part /
├─vda14 254:14 0 3M 0 part
└─vda15 254:15 0 124M 0 part /boot/efi
The cloud image uses GPT with an EFI system partition and a root
partition. A BIOS installation would show a different layout but the same
vda name.
Virtio devices are faster than emulated IDE, e1000, or SATA devices, and they expose their capabilities to the guest. The trade-off is that very old guests or non-Linux systems may lack drivers. A comparison:
| Device | Guest driver | Performance and features | When to choose |
|---|---|---|---|
virtio-blk |
virtio_blk |
High throughput, simple queue, no SCSI features | Most Linux guests |
virtio-scsi |
virtio_scsi |
SCSI command set, discard, multiple queues, more devices | Guests needing SCSI or many disks |
virtio-net |
virtio_net |
High throughput, multiqueue, checksum offload | Linux and modern Windows |
| Emulated IDE/SATA | ata_piix/ahci |
Widely compatible, slower, limited queues | Legacy guests, recovery |
| Emulated e1000 | e1000 |
Compatible with old systems, slower | Legacy guests only |
The guest agent is a separate channel. qemu-guest-agent runs inside the
guest and lets the host ask for a clean shutdown, freeze filesystems for a
snapshot, report addresses, and execute limited commands. The channel is a
virtio serial port named org.qemu.guest_agent.0; the domain was created
with --channel
unix,target.type=virtio,target.name=org.qemu.guest_agent.0 in
Section 24.2.2, and the seed file in the next section installs and enables
the package. On the guest, as john:
$ systemctl is-active qemu-guest-agent
active
From the host, as john, ask the agent to answer a ping:
$ sudo virsh -c qemu:///system qemu-agent-command handbook-web '{"execute":"guest-ping"}'
{"return":{}}
An empty return object means the agent is reachable. libvirt uses the same
channel for shutdown and filesystem freeze; if the agent is missing,
virsh shutdown falls back to an ACPI power button, which the guest may
ignore, and --quiesce snapshots fail.
The agent also reports interface addresses, which is useful when DHCP has assigned an address you do not know. On virt1, as john:
$ sudo virsh -c qemu:///system domifaddr handbook-web --source agent
Name MAC address Protocol Address
-------------------------------------------------------------------------------
lo 00:00:00:00:00:00 ipv4 127.0.0.1/8
- - ipv6 ::1/128
enp1s0 52:54:00:ec:63:66 ipv4 192.168.236.117/24
- - ipv6 fe80::5054:ff:feec:6366/64
--source agent asks the guest; --source lease asks libvirt's DHCP
server, and --source arp reads the host's neighbor table. The agent
result includes loopback and IPv6 addresses, so filter for the interface
you expect. The address shown is a DHCP lease and will differ on another
installation.
Install the agent in guests that were installed without it. On the guest,
as john, the package is qemu-guest-agent; Debian enables the unit on
installation. The domain must have the virtio serial channel; adding the
package alone does not create it. A guest that has the channel but not the
package shows no agent response, and a guest with the package but no
channel has nowhere for the agent to listen. Check both sides when
diagnosing.
24.2.4. Automating Cloud Image Initialization with cloud-init
Cloud images expect a datasource that supplies an instance ID, hostname,
users, SSH keys, and first-boot commands. The NoCloud datasource reads that
data from a filesystem volume or an ISO with the label cidata. On a
libvirt host, cloud-localds builds the ISO from two YAML files, and
virt-install attaches it as a CD-ROM. The guest's cloud-init then runs
once and records completion under /var/lib/cloud.
The user-data file is a cloud-config document. A representative file for
the practice guest, stored at
~/debian-handbook/virtualization/cloud-init/user-data, is:
#cloud-config
hostname: handbook-web
manage_etc_hosts: true
users:
- name: john
gecos: Handbook Reader
shell: /bin/bash
sudo: ALL=(ALL) ALL
lock_passwd: false
passwd: "$6$REPLACE_WITH_A_GENERATED_HASH"
ssh_authorized_keys:
- ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAINMtSVtaATbXx3SWtxxeLvZ51DJxAQY8c7yzKqjKi3sa handbook-ch24-lab
package_update: true
packages:
- qemu-guest-agent
- sqlite3
- curl
- nftables
runcmd:
- systemctl enable --now qemu-guest-agent
- install -d -o john -g john /home/john/debian-handbook/virtualization
Replace the password hash with one generated on a trusted machine with
openssl passwd -6. The SSH public key is the administrator's key; the
private key stays on the workstation, and the exercises refer to it as
~/.ssh/ch24-lab. sudo: ALL=(ALL) ALL grants john administrative rights
through the normal sudo password prompt, not a passwordless policy; if your
site delegates administration differently, change this line rather than
copying the example literally.
The meta-data file supplies an instance ID and a local hostname. A minimal
file at ~/debian-handbook/virtualization/cloud-init/meta-data is:
instance-id: handbook-web-01
local-hostname: handbook-web
The instance ID must be unique for each new guest. Reusing it makes cloud-init believe it has already run and skip first-boot configuration; this is why cloned guests need the instance state cleared. Build the seed ISO on virt1, as john:
$ sudo cloud-localds /var/lib/libvirt/images/handbook/handbook-web-seed.iso ~/debian-handbook/virtualization/cloud-init/user-data ~/debian-handbook/virtualization/cloud-init/meta-data
The command is silent on success. The resulting ISO is small, typically
under a megabyte, and is attached read-only as sda in the domain. The
--disk ...,device=cdrom,readonly=on option in the virt-install command
is what makes it visible to the guest. The pool now holds every volume the
guest uses. On virt1, as john:
$ virsh -c qemu:///system vol-list handbook
Name Path
-----------------------------------------------------------------------------------------------------------
debian-13-genericcloud-amd64.qcow2 /var/lib/libvirt/images/handbook/debian-13-genericcloud-amd64.qcow2
handbook-web-seed.iso /var/lib/libvirt/images/handbook/handbook-web-seed.iso
handbook-web.qcow2 /var/lib/libvirt/images/handbook/handbook-web.qcow2
The base image, the seed ISO, and the guest overlay are all visible as pool volumes. libvirt does not require every file in a directory pool to be registered separately; the list is a view of the directory.
On the running guest, as john, verify that cloud-init finished:
$ cloud-init status --long
status: done
extended_status: done
boot_status_code: enabled-by-generator
last_update: Thu, 01 Jan 1970 00:01:00 +0000
detail: DataSourceNoCloud [seed=/dev/sr0]
errors: []
recoverable_errors: {}
status: done means the modules completed; errors: [] means none of the
recorded stages failed. The timestamp comes from the guest clock before NTP
has synchronized, so an early-1970 value is normal on a fresh cloud image.
DataSourceNoCloud confirms that cloud-init read the seed ISO rather than a
network metadata service.
Query the instance identity, the hostname, and the account cloud-init created. On the guest, as john:
$ cloud-init query instance-id
handbook-web-01
$ hostname
handbook-web
$ id john
uid=1000(john) gid=1000(john) groups=1000(john)
The instance ID matches meta-data; the hostname matches user-data; the
john account has been created. The guest still needs a login path. With
the public key from user-data, the first SSH connection from the host
must verify the guest's host key: obtain the fingerprint on a trusted
channel - for example from the guest's console, or by reading the host key
over the guest agent from the host side - and compare it with the
fingerprint ssh offers before accepting it; the known-hosts record then
covers later connections. Keeping a dedicated known-hosts file per practice
guest is one way to keep several records separate, and strict host-key
checking stays enabled either way. After the first accepted connection, an
ordinary ssh john@ADDRESS reaches the guest, and exit leaves it.
Cloud-init is a first-boot tool, not a configuration manager. After the
guest is running, edit files and services normally. To re-run cloud-init
for a new instance, remove the instance state under /var/lib/cloud and
change the instance ID; the exact cleanup depends on the image and should be
done on a clone or a shut-down guest, not on a production guest that still
needs its current identity.
| Cloud-init stage | What it configures | Where to look when it fails |
|---|---|---|
init-local |
Datasource detection, local networking | /var/log/cloud-init.log, cloud-init status --long |
init |
Network configuration, hostname | cloud-init query, ip addr, /etc/netplan |
config |
Users, SSH keys, packages, files | cloud-init query userdata, dpkg -l |
final |
runcmd, power_state, final messages |
cloud-init status --long, journal |