This tutorial explains how to create a new KVM virtual machine on Ubuntu Linux using only the CLI (command line).
Host OS : Ubuntu Quantal Quetzal 12.04 with libvirtd
Networking : The KVM virtual machines are all connected to a OpenvSwitch bridge and are using RFC 1918 ip addresses. Since I only have a single external IP, my host runs a firewall that NATs certain ports towards the virtual machines.
Create the disk
You can create a sparse file with the following command. The reserved space will be 12 GB in size. This method is often called ‘thin provisioning’.
# truncate -s 12G disk.img
Optional : Extract xml from existing KVM virtual machine
If you already have other machines running, shutdown a machine and extract its xml file.
virsh dumpxml <existing_machine> > newmachine.xml
You can also use this xml file as a start. As you can see, I set the boot device to the cdrom and pointed the cdrom to a bootable iso image. Note that in this example, I made use of an OpenvSwitch bridge for network connectivity.
Adapt the xml file
- Change the uuid to a unique value.
# uuidgen 78dac724-9fdd-4202-a27e-52cdbf491ada
- Change the MAC address to a unique value.
# echo 52:54:$(dd if=/dev/urandom count=1 2>/dev/null | md5sum | sed 's/^\(..\)\(..\)\(..\)\(..\).*$/\1:\2:\3:\4/') 52:54:f6:65:52:39
Create the new KVM virtual machine guest
Now we will import the xml file into our system. After importing it, you can remove the file.
# virsh create image.xml Domain lucid created from image.xml
Please verify if you got the same output. Errors will be printed at this point. Please do not proceed until you ran this command successfully.
After running this command, the new KVM virtual machine guest will be running.
Connect to the interface
At this point, a vnc server should be running on a port on our host system. That vnc server can be used to manage/install the guest. Since the port is dynamically allocated, we have to use the following command to get the port.
# virsh dumpxml image | grep vnc <graphics type='vnc' port='5907' autoport='yes' listen='127.0.0.1'>
In this case, the dynamic port is 5907. We can connect from the local machine to that port using vncviewer.
# vncviewer localhost 5907
After installing the machine, don’t forget configuration to make sure the system boots from the hard disc.
# virsh edit image
For ‘boot dev’, change ‘cdrom’ into ‘hd’.
Optional : Autostart the new KVM virtual machine
If you want to start the guest whenever the hosts system boots, issue this command.
# virsh autostart image