POC – Optimizing Windows Disk Images with QEMU: Reducing Storage Space While Maintaining Logical Size

Context and Objective

When preparing environments, it’s often necessary to manage storage space efficiently, especially when disk images are used by multiple containers. In this article, we will explore how to optimize Windows disk images using QEMU, to reduce storage space while maintaining the logical size of the image.

Initial Problem

We have an .img file representing a Windows installation and some applications, with a size of 20 GB, while only 14 GB are actually used within Windows. Our goal is to compress this disk image so that it only uses the necessary space (14 GB) while still presenting a logical size of 20 GB once the OS is started.

Solution with QEMU

QEMU, an open-source emulator and virtualizer used in the Dockurr project, offers tools to convert disk images using dynamic allocation, similar to VMware’s thin provisioning. Here are the steps to optimize a disk image with QEMU:

Step 1: Prepare the Disk Image

Before converting the image, it is recommended to clean the free space on the disk to improve conversion efficiency. On Linux, you can use zerofree, and on Windows, it’s helpful to defragment and zero out the free space.

Step 2: Install QEMU

If QEMU is not already installed on your system, you can install it with the following command:

sudo apt-get install qemu-utils

Step 3: Convert the Image Using the QCOW2 Format

Use the qemu-img convert command to convert your image to the QCOW2 format with dynamic allocation and compression:

qemu-img convert -O qcow2 -c data.img data.qcow2

In this command:

  • data.img is your source image file.
  • data.qcow2 is the new converted image file.
  • -O qcow2 specifies that the output format should be QCOW2.
  • -c enables compression to further reduce the physical size of the image.

Step 4: Check the Size of the Converted Image

After the conversion, you can check the physical size of the converted image, which should be only 7 GB. That’s great!

Result

In conclusion, after the conversion, we obtain a file that is only 7 GB on the host machine, while maintaining a logical size of 20 GB. This allows for more efficient use of storage space while providing the same functionality and capabilities to students. We now replace the old file in our source directory with the new one with the QCOW2 extension. We test the container deployment and… BAM, it works beautifully!

Conclusion

Using QEMU to convert disk images to the QCOW2 format with dynamic allocation and compression optimizes the use of storage space. This method is particularly useful in my project, where many temporary virtual machines are deployed for students. With this approach, we can provide flexible and isolated work environments while efficiently managing resources.