In my last tutorial, “KVM Virtual Machines 101” we learned how to create a VM using virt-manager. I emphasize learning the command line interface (CLI) for LXD and Docker on the channel and so the KVM CLI is also valuable to learn. In this tutorial we will learn how to use the command line to create a new virtual machine with “virt-install”.
I started the tutorial by showing it is important to create a “bridge” device for your KVM host so that it can present VM’s with an address on your LAN. See my other videos to learn how to do this in detail and so I do not cover it here.
Make sure you have KVM installed and your username is added to the kvm and the libcirt groups as discussed in the last video.
The command we used to create an Ubuntu 22.04 server VM from the command line.
sudo virt-install --name=ubuntu-test \ --description "Test Server" \ --os-variant=ubuntu22.04 \ --vcpus=2 \ --ram=4096 \ --disk path=/var/lib/libvirt/images/ubuntu-server.qcow2,format=qcow2,bus=virtio,size=15 \ --vnc \ --cdrom="/mnt/MondoSeagate/Distros/ubuntu-22.04-live-server-amd64.iso" \ --network bridge:bridge0
To connect to the console of the machine.
virt-viewer --connect qemu:///system --wait ubuntu-test
As a bonus, we installed the “nala” package manager which is a front end to the “apt” package manager.
echo "deb [arch=amd64,arm64,armhf] http://deb.volian.org/volian/ scar main" | sudo tee /etc/apt/sources.list.d/volian-archive-scar-unstable.list wget -qO - https://deb.volian.org/volian/scar.key | sudo tee /etc/apt/trusted.gpg.d/volian-archive-scar-unstable.gpg > /dev/null sudo apt update && sudo apt install nala
To view all virtual machines, running or not:
virsh list --all
To shutdown a VM:
virsh shutdown ubuntu-test
To start a VM:
virsh start ubuntu-test
A virtual machine consists of the disk image file located in /var/lib/libvirt/images and the XML file that defines the VM. To dump a copy of a VM’s XML into a file to port it to another machine:
virsh dumpxml ubuntu-test > ubuntu-test.xml
You will want to also copy the disk image file with the XML. To reload the VM make sure the disk image is in /var/lib/libvirt/images and that it is named the same as it was originally. Then execute the following:
virsh define ubuntu-test.xml
We also learned about KVM Snapshots. Here are the commands we used to manage snapshots:
virsh snapshot-create-as ubuntu-test --name initial-install virsh snapshot-list ubuntu-test virsh snapshot-revert ubuntu-test initial-install virsh snapshot-delete ubuntu-test added-neofetch
Finally, the command to delete a VM completely, including its disk image:
virsh undefine ubuntu-test --remove-all-storage