Working with QCOW2 disk images

For separation purposes and also gaming I use virtual machines. During the years I have some difficulties with opening and editing the disk images of my virtual machines. So I would like to share my experiences…

Let’s start with a relatively easy one:

Expanding a QCOW2 container

$ qemu-img resize disk.qcow2 +10G

This will add 10 GB of free space to your virtual disk.

Shrinking a QCOW2 container

This is not so straightforward because you have to do a few steps before you starting to reduce the size of the disk image. You have to do two things before:

  1. Reduce the size of the partition inside virtual machine
  2. Write zeros to the unpartitioned space

You can do both with MiniTool Partition Wizard on Windows. On a Linux virtual machine, well, it’s bit more difficult:

$ dd if=/dev/zero of=zerofile bs=1M
$ rm zerofile

After shutting down the VM you should do the following on the host:

$ qemu-img convert -f raw -O qcow2 guest.img guest-copy.qcow2

Attention! It will make a reduce-sized copy of your disks so you should have plenty of free space for this step. After the completion of the process you should remove the original file (of course after checking everything is right with the new one).

Attach a QCOW2 container to your filesystem as a block device

$ modprobe nbd max_part=8
$ qemu-nbd --connect=/dev/nbd1 /media/yourfolder/disk.qcow2
$ mkdir /media/diskname
$ mount /dev/nbd1p1 /media/diskname

Basically you are setting the maximum number of partition with first line and with the second you are attaching your disk image and finally you are mounting it to your filesystem.

Detach a QCOW2 container

$ umount /media/diskname
$ rmdir /media/diskname
$ qemu-nbd --disconnect /dev/nbd1
$ rmmod nbd

This article is for more advance users because it assumes that you have a basic understanding how to work with QCOW2 containers and virtual machines. These methods are not so straightforward so I wrote them down.

Sources in order to create this guide and to solve my previous problems related to this article:

If you are new in this topic and you would like to get a basic understanding about this subject:


Categories: