24.4. Operating Virtual Machines

Day-to-day operation is mostly a small set of libvirt verbs. The important distinction is between the running state and the persistent definition: start, shutdown, and destroy change the running state; define, undefine, and edit change what will happen next time. A change made only to the running domain is lost at shutdown, and a change made only to the definition does not affect a running guest.

24.4.1. Starting, Stopping, Autostarting, and Inspecting Guests

virsh list --all shows both running and stopped domains; it was shown in Section 24.1.3 with the practice guest running. dominfo gives a compact summary of identity, state, CPU, memory, and security label. On virt1, as john:

$ sudo virsh -c qemu:///system dominfo handbook-web
Id:             2
Name:           handbook-web
UUID:           ab5858e3-cede-433a-bdbf-048d6eed522c
OS Type:        hvm
State:          running
CPU(s):         1
CPU time:       120.3s
Max memory:     1048576 KiB
Used memory:    1048576 KiB
Persistent:     yes
Autostart:      disable
Autostart Once: disable
Managed save:   no
Security model: apparmor
Security DOI:   0
Security label: libvirt-ab5858e3-cede-433a-bdbf-048d6eed522c (enforcing)
Messages:       tainted: custom guest agent control commands issued

The numeric Id is assigned by the host at each start, so it differs from the 1 seen when the guest was first created. Persistent: yes means the domain has a stored definition. Autostart: disable means it will not start when the host boots. The AppArmor label is generated from the domain UUID; libvirt confines QEMU to the files and devices the domain needs, which is one reason not to disable AppArmor casually.

Enable autostart so the guest returns after a host reboot. On virt1, as john:

$ sudo virsh -c qemu:///system autostart handbook-web
Domain 'handbook-web' marked as autostarted

The result appears in dominfo:

$ sudo virsh -c qemu:///system dominfo handbook-web | grep -i autostart
Autostart:      enable
Autostart Once: disable

autostart creates a symlink under /etc/libvirt/qemu/autostart/; it does not start the guest immediately. Use --disable to remove it. A domain whose disk or network is unavailable at boot will still fail to start; the symlink only asks libvirt to try.

Shut down a guest gracefully with shutdown. On virt1, as john:

$ sudo virsh -c qemu:///system shutdown handbook-web
Domain 'handbook-web' is being shutdown

The command returns before the guest has finished; poll the state:

$ sudo virsh -c qemu:///system domstate handbook-web
shut off

shutdown sends an ACPI request or asks the guest agent, depending on the configuration. A guest that ignores ACPI or lacks the agent may stay running. destroy removes power immediately and is appropriate only when the guest is hung or the data loss is acceptable; it is the virtual equivalent of pulling the power cord. reboot asks the guest to reboot, reset resets it immediately, suspend pauses it, and resume continues it.

virsh subcommand Effect on running guest Effect on definition
start NAME Boots it None
shutdown NAME Requests graceful poweroff None
destroy NAME Removes power immediately None
reboot NAME Requests graceful reboot None
reset NAME Resets immediately None
suspend NAME / resume NAME Pauses and continues execution None
autostart NAME None now Creates boot-time autostart link
undefine NAME Guest must be stopped Removes the stored definition, not the disk

undefine does not delete disk images. That is deliberate: deleting the XML is recoverable if the disk survives, while deleting the disk is not. Use --remove-all-storage only when you are certain the data is disposable, and check the volumes it reports first.

24.4.2. Changing CPU, Memory, and Disk Resources

Resource changes have different constraints depending on the device and the guest. Memory can often be changed with the balloon driver, vCPUs can be hot-added if the domain's maximum allows it and the guest onlines them, and disks can be attached or resized online if the bus and guest support it. Shrinking a disk is not generally safe online, and removing a vCPU is not supported by many guests.

Inspect the current vCPU placement. On virt1, as john:

$ sudo virsh -c qemu:///system vcpuinfo handbook-web
VCPU:           0
CPU:            0
State:          running
CPU time:       121.4s
CPU Affinity:   yy

The yy affinity mask shows that both host CPUs are eligible for the vCPU; no explicit pinning is set. Memory statistics come from the balloon driver:

$ sudo virsh -c qemu:///system dommemstat handbook-web
actual 1048576
swap_in 0
swap_out 0
major_fault 353
minor_fault 72461
unused 835292
available 990856
usable 797784
last_update 1795421323
disk_caches 61156
hugetlb_pgalloc 0
hugetlb_pgfail 0
rss 404916

actual is the current balloon size in KiB - the guest currently holds the full 1 GiB - and rss is the host resident set of the guest process. unused is memory the guest is not using. A guest with a balloon driver can give memory back to the host under pressure, but the host does not automatically reclaim it unless a memory policy asks for it.

Reduce the guest to 768 MiB while it runs. On virt1, as john:

$ sudo virsh -c qemu:///system setmem handbook-web 768M --live

The command is silent on success. On the guest, as john, free reports the new total:

$ free -m | head -2
               total        used        free      shared  buff/cache   available
Mem:             906         231         686           0         117         675

The head -2 filter keeps the header and the Mem row. The guest's reported total has fallen from its original 1 GiB but sits at 906 MiB at the moment of the check rather than exactly 768 MiB: the balloon hands pages back over a short interval, and the guest's own accounting keeps some regions counted. Ballooning is not a substitute for correct sizing: a guest that touches all of its memory cannot give it back, and a host that overcommits will still OOM.

Restore the memory to 1 GiB:

$ sudo virsh -c qemu:///system setmem handbook-web 1G --live

The command is silent on success, and dommemstat reports actual returning to 1048576. Add a second vCPU. The domain was created with maxvcpus=2, so the ceiling allows it:

$ sudo virsh -c qemu:///system setvcpus handbook-web 2 --live

The command is silent. Adding a vCPU does not necessarily online it in the guest; the guest kernel may keep it offline until told. On the guest, as john:

$ sudo sh -c 'echo 1 > /sys/devices/system/cpu/cpu1/online'

The sh -c shell runs the whole command, including the redirection, under sudo, because the write must come from root; the command prints nothing. Check the result:

$ nproc
2

nproc reports the number of online CPUs. If the guest does not support hotplug or the vCPU was not defined as hotpluggable, the host command fails with an error instead of adding a CPU. Check virsh dumpxml for the <vcpu ... current="1"> element and the guest kernel's cpu1/online file before troubleshooting elsewhere.

Attach a data disk. On virt1, as john:

$ sudo qemu-img create -f qcow2 /var/lib/libvirt/images/handbook/handbook-data.qcow2 1G
Formatting '/var/lib/libvirt/images/handbook/handbook-data.qcow2', fmt=qcow2 cluster_size=65536 extended_l2=off compression_type=zlib size=1073741824 lazy_refcounts=off refcount_bits=16

Attach the disk as vdb with virtio. On virt1, as john:

$ sudo virsh -c qemu:///system attach-disk handbook-web /var/lib/libvirt/images/handbook/handbook-data.qcow2 vdb --targetbus virtio --subdriver qcow2 --persistent --live
Disk attached successfully

--targetbus virtio selects the virtio-blk controller; --subdriver qcow2 tells libvirt the image format so it does not have to probe. --persistent records the disk in the domain XML; --live attaches it now. The guest sees the new block device. On the guest, as john:

$ 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
vdb     254:16   0    1G  0 disk

The disk has no partition table or filesystem. Create one inside the guest with mkfs and mount it, as in Chapter 11 and Chapter 12; the host does not format guest data disks.

Resize the root disk online with blockresize. On virt1, as john:

$ sudo virsh -c qemu:///system blockresize handbook-web vda 12G
Block device 'vda' is resized

This changes the size visible to the guest, not the partition table or the filesystem. On the guest, as john, lsblk shows the larger disk:

$ lsblk /dev/vda
NAME    MAJ:MIN RM  SIZE RO TYPE MOUNTPOINTS
vda     254:0    0   12G  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 partition still ends at the old boundary. Growing the partition and filesystem requires guest-side tools (growpart, resize2fs, or xfs_growfs) and is covered in Chapter 14. blockresize cannot shrink a disk below the guest's current use, and shrinking a filesystem is a separate, filesystem-specific operation.

Detach the data disk when it is no longer needed. On virt1, as john:

$ sudo virsh -c qemu:///system detach-disk handbook-web vdb --persistent --live
Disk detached successfully

The file remains in the pool; detaching removes the device, not the data. Never delete a disk file while a guest has it open. Check domblklist before removing a volume, and unmount it inside the guest first.

Change Command Online? Persistent flag Main constraint
Memory setmem Usually --config separately Guest balloon driver
vCPU add setvcpus N --live Sometimes --config separately maxvcpus, guest hotplug
vCPU remove setvcpus N --live Rarely --config separately Guest and architecture support
Disk attach attach-disk Usually --persistent Free target name, bus support
Disk detach detach-disk Usually --persistent Guest must release it
Disk grow blockresize Usually --config for definition Partition/filesystem grow separately

24.4.3. Cloning Guests Without Duplicating Host Identities

A clone copies a disk and a domain definition. Copying the disk alone is not enough, and copying the definition without changing identity creates two machines with the same name, UUID, MAC, machine ID, SSH host keys, and often the same DHCP client identity. The result is duplicate addresses, SSH host-key warnings, and services that cannot tell the machines apart.

virt-clone copies a stopped domain and assigns a new name, UUID, and MAC by default. On virt1, first shut down the source guest, then as john:

$ sudo virsh -c qemu:///system shutdown handbook-web
Domain 'handbook-web' is being shutdown

The command returns immediately. Check that the guest has finished:

$ sudo virsh -c qemu:///system domstate handbook-web
shut off

Create the clone. The copy reads the whole allocated disk, so give it time on a large guest. On virt1, as john:

$ sudo virt-clone --connect qemu:///system --original handbook-web --name handbook-clone --auto-clone
Allocating 'handbook-clone.qcow2'                           |  12 GB  00:19

Clone 'handbook-clone' created successfully.

Selected output; virt-clone redraws its progress meter in place while the disk copies, so the terminal shows a single updating line rather than a list, and the capture is shown in its final state. --auto-clone generates disk paths and MAC addresses. The clone's identity is new at the libvirt level. On virt1, as john, check the domain name, UUID, and MACs:

$ sudo virsh -c qemu:///system dumpxml handbook-clone | grep -E '<name>|<uuid>|<mac address'
  <name>handbook-clone</name>
  <uuid>0e221fab-dab6-4561-9a18-6016f2f0cfb8</uuid>
      <mac address='52:54:00:4a:21:83'/>
      <mac address='52:54:00:2e:de:c4'/>
      <mac address='52:54:00:96:ef:a1'/>

The clone has three MACs because the source had accumulated NAT, bridge, and isolated interfaces. Each is new. The guest's internal identity is still the source's: /etc/machine-id, SSH host keys, hostname, DHCP client lease, udev naming rules, and cloud-init instance state. virt-sysprep resets the parts it knows about. The options used for offline guest editing:

Option Tool Effect
-d NAME both Operate on the named shut-off domain
--enable LIST virt-sysprep Run only the listed operations
--hostname NAME virt-customize Set the guest's hostname
--run-command CMD virt-customize Run a command inside the offline guest
--upload SRC:DST virt-customize Copy a file into the guest image

On virt1, as john:

$ sudo virt-sysprep -d handbook-clone --enable machine-id,ssh-hostkeys,net-hostname,dhcp-client-state,udev-persistent-net,net-hwaddr
[   0.0] Examining the guest ...
[  22.6] Performing "dhcp-client-state" ...
[  22.6] Performing "machine-id" ...
[  22.7] Performing "net-hostname" ...
[  22.7] Performing "net-hwaddr" ...
[  22.8] Performing "ssh-hostkeys" ...
[  22.8] Performing "udev-persistent-net" ...

The log order is the order the operations completed, not necessarily the order in the --enable list. virt-sysprep works offline; the clone must be shut down. It removes or regenerates the selected identity files, but it does not know about application data, database users, or a cloud-init datasource that still points at the old instance.

Set the clone's hostname and clear cloud-init's record of the old instance:

$ sudo virt-customize -d handbook-clone --hostname handbook-clone --run-command 'rm -rf /var/lib/cloud/instances /var/lib/cloud/instance'
[   0.0] Examining the guest ...
[  16.6] Setting a random seed
[  16.6] Setting the machine ID in /etc/machine-id
[  16.6] Setting the hostname: handbook-clone
[  18.5] Running: rm -rf /var/lib/cloud/instances /var/lib/cloud/instance
[  18.6] SELinux relabelling
[  19.1] Finishing off

virt-customize also regenerates the machine ID and sets a random seed. Removing /var/lib/cloud/instances makes cloud-init treat the next boot as a new instance; if the seed ISO is still attached, it will read the old instance ID again unless the seed is changed or detached. The practice clone keeps its original seed, so the netplan file is replaced directly to avoid a stale MAC match from the old guest:

$ sudo virt-customize -d handbook-clone --upload ~/debian-handbook/virtualization/cloud-init/clone-netplan.yaml:/etc/netplan/50-cloud-init.yaml
[   0.0] Examining the guest ...
[  16.3] Setting a random seed
[  16.3] Uploading: /home/john/debian-handbook/virtualization/cloud-init/clone-netplan.yaml to /etc/netplan/50-cloud-init.yaml
[  16.4] SELinux relabelling
[  16.7] Finishing off

The netplan fragment matches the interface by name rather than the old MAC:

network:
  version: 2
  ethernets:
    enp1s0:
      dhcp4: true
      dhcp6: true
      set-name: "enp1s0"

Start the clone. On virt1, as john:

$ sudo virsh -c qemu:///system start handbook-clone
Domain 'handbook-clone' started

The clone gets its own DHCP lease. Verify its host key - it has new SSH host keys after sysprep, so the fingerprint must be confirmed again through a trusted channel - and record it in a dedicated known-hosts file. The login then shows the new identity. On virt1, as john:

$ ssh -i ~/.ssh/ch24-lab -o UserKnownHostsFile=~/.ssh/known_hosts_ch24_clone -o StrictHostKeyChecking=yes john@192.168.236.102 'hostname; cat /etc/machine-id; id john'
handbook-clone
e779074e81f94489cc9a3586d45a9a35
uid=1000(john) gid=1000(john) groups=1000(john)

The hostname and machine ID differ from the source. The address is the clone's own lease; do not assume it will be adjacent to the source's address. The clone's application data is a copy of whatever the source had at the moment of cloning. Here that is nothing: the practice database is created later, on the source, so an inspection on the clone comes back empty. On the clone, as john:

$ sqlite3 ~/debian-handbook/virtualization/app.db 'select * from notes;'
Error: in prepare, no such table: notes

The clone's disk image predates the database, so sqlite3 opens an empty file and the query finds no table. If an application has its own replication, cluster identity, or license tied to a host ID, reset that separately; virt-sysprep does not know about it.

Clone method Disk usage Time Identity handling Best use
virt-clone --auto-clone Full copy of allocated blocks Proportional to data New name, UUID, MAC; sysprep separately Independent guests
qcow2 overlay with base Only new writes Nearly instant New name, UUID, MAC; shared base Lab copies, disposable tests
Template plus cloud-init Base image plus overlay Fast cloud-init creates identity Automated fleets

A linked clone that shares a base must never modify the base, and deleting the base breaks every overlay that references it. For production clones, prefer a full copy or a properly managed template with per-instance cloud-init.

24.4.4. Snapshots and Application Consistency

A libvirt snapshot records the domain state at a point in time. A disk-only snapshot creates a new qcow2 overlay and leaves the previous disk as a backing file; the guest keeps running. A system checkpoint also saves RAM and device state, so it can resume exactly where it stopped, but it consumes more space and is more fragile across host or QEMU changes. A snapshot is not a backup: it lives in the same pool as the disk and is lost with the host or the pool.

For an application-consistent disk snapshot, the guest must flush its filesystem and the application must quiesce its writes. The QEMU guest agent implements fsfreeze; libvirt's --quiesce asks the agent to freeze filesystems around the snapshot. This protects filesystem metadata, but it does not make a running database transactionally consistent. Use the application's own backup or flush mechanism for databases, and test the restore.

On the guest, as john, create a marker row in a small SQLite database so the snapshot's effect is visible:

$ sqlite3 ~/debian-handbook/virtualization/app.db 'create table if not exists notes(id integer primary key, body text); insert into notes(body) values ("before snapshot");'

The command writes silently. Read the table back:

$ sqlite3 ~/debian-handbook/virtualization/app.db 'select * from notes;'
1|before snapshot

Take a quiesced disk-only snapshot. On virt1, as john:

$ sudo virsh -c qemu:///system snapshot-create-as handbook-web before-update 'before application update' --disk-only --quiesce --atomic
Domain snapshot before-update created

The options:

Option Effect
--disk-only Snapshot the disks only; save no RAM state
--quiesce Ask the guest agent to freeze filesystems first
--atomic Create the snapshot completely or not at all

The snapshot name is before-update; the description is optional. List snapshots:

$ sudo virsh -c qemu:///system snapshot-list handbook-web
 Name            Creation Time               State
------------------------------------------------------------
 before-update   2026-11-23 08:18:13 +0000   disk-snapshot

Change the database after the snapshot. On the guest, as john:

$ sqlite3 ~/debian-handbook/virtualization/app.db 'insert into notes(body) values ("after snapshot");'

The insert is silent. Read the table:

$ sqlite3 ~/debian-handbook/virtualization/app.db 'select * from notes;'
1|before snapshot
2|after snapshot

Everything the guest writes after this point - including the row just inserted - is discarded if the snapshot is reverted to. Revert to the snapshot. On virt1, as john:

$ sudo virsh -c qemu:///system snapshot-revert handbook-web before-update
Domain snapshot before-update reverted

A disk-only revert rewinds the guest's disks and leaves the domain shut off, so start it again:

$ sudo virsh -c qemu:///system start handbook-web
Domain 'handbook-web' started

After the guest is reachable again, the database shows the snapshot state. On the guest, as john:

$ sqlite3 ~/debian-handbook/virtualization/app.db 'select * from notes;'
1|before snapshot

The second row is gone. This demonstrates disk state, not application consistency: SQLite was idle at the snapshot and its file was flushed by the freeze. A database with uncommitted transactions or a write-back cache can still need recovery after a revert.

Shut the guest down before finishing with the snapshot. On virt1, as john:

$ sudo virsh -c qemu:///system shutdown handbook-web
Domain 'handbook-web' is being shutdown

Wait until domstate reports shut off, then remove the snapshot record. Because the revert has already rewound the disks, only libvirt's metadata remains to clean up:

$ sudo virsh -c qemu:///system snapshot-delete handbook-web before-update --metadata
Domain snapshot before-update deleted

--metadata discards libvirt's snapshot record without touching the disk chain. A full snapshot-delete without --metadata also merges the snapshot's overlay back into its parent image and removes the overlay file, returning the domain to the parent disk; the parent must be present for that merge, and libvirt relabels it for QEMU as part of the operation. When the merge is not what you want - as after the revert here, where the overlay is already abandoned - --metadata leaves the chain exactly as it is; snapshot-list --tree shows parent and child relationships when several snapshots exist.

The seed CD-ROM is no longer needed now that first boot is complete, so detach it from the persistent definition:

$ sudo virsh -c qemu:///system detach-disk handbook-web sda --config
Disk detached successfully

Confirm the result on both sides:

$ virsh -c qemu:///system domblklist handbook-web
 Target   Source
---------------------------------------------------------------
 vda      /var/lib/libvirt/images/handbook/handbook-web.qcow2
$ virsh -c qemu:///system snapshot-list handbook-web
 Name   Creation Time   State
-------------------------------

The domain has a single disk and no snapshot records; the abandoned snapshot overlay is no longer referenced by the domain, and the next section backs up the image named in its XML.

Snapshot kind Saves RAM Disk cost Guest downtime Use
Internal disk snapshot No Changed clusters in the same qcow2 None Quick rollback on a simple image
External disk-only No New overlay, previous disk retained None with quiesce Backups, cloning, rollback
System checkpoint Yes Disk overlay plus RAM state Brief pause Exact resume of a running guest
Application backup No Application-defined Application-defined Databases, mail stores, consistent exports

Snapshots accumulate. Each external snapshot adds a layer that every read must traverse, and deleting a middle layer requires a block commit that can take time and temporary space. Keep a small number of named snapshots, and use a real backup for retention.