Using qemu-img
In most cases, you will install an operating system into your virtual machine. To be able to perform an installation, the guest system needs a virtual hard disk.
Creating a Virtual Machine Image
Whenever you create a new virtual machine, it is usually necessary to make a disk image for it. At first, this disk image is blank: there is nothing stored inside it beyond the basic metadata needed for the image file. Once you have created a new disk image, the typical next step is to install an operating system onto it by booting the virtual machine using a downloaded ISO file as a virtual CD-ROM disc. After installation, the virtual machine will run from the virtual hard disk.
IMPORTANT: Only use qemu-img to make a virtual hard disk when you first create a new virtual machine! If you run qemu-img and re-make the virtual hard disk after you’ve installed the guest operating system, the qemu-img command will happily overwrite your whole installation with a blank disk.
When using qemu-img, we usually want to use the qcow2 (QEMU copy-on-write version 2) disk image format. This format results in disk images that only take up as much space on the host system as the guest system is actually using on its hard drive. Using qcow2 saves space on your laptop or desktop system.
Remember that qemu-img is a command-line application. Once you start the command interpreter (terminal application in Linux/macOS or cmd or PowerShell in Windows), it is normally necessary to change the working directory to your virtual machine directory first. Use the cd command for this purpose, and verify the contents of your working directory with the ls command (Linux/macOS/PowerShell) or dir command (Windows command interpreter). If the disk image file you’re trying to create already exists in this directory, then you’re either in the wrong directory, or you have already created the image. Running the qemu-img command again will overwrite the existing image with a new, blank one.
By way of example, the following command creates a new disk image named “example.qcow2” that is able to grow up to 40 GB in size:
qemu-img create -f qcow2 example.qcow2 40G
Adjust the filename and maximum size as required for your virtual machine.
Other Uses of qemu-img
The qemu-img command is capable of performing many more operations than simply creating disk images. It can check existing images, resize existing images, and convert between virtual machine disk image formats, among other capabilities. One example use case occurs when downloading a preinstalled virtual machine from an online source. Typically, this type of virtual machine is shipped using the VMWare disk format (vmdk). A qcow2 disk image can be created from it by running:
qemu-img convert -f vmdk -O qcow2 input.vmdk output.qcow2
For other uses of qemu-img, read the QEMU disk image utility documentation.