Shrink qcow2 disk for Linux VM in Proxmox

August 27, 2016 by

While qcow2 is a “thin-provisioning” image format, over time qcow2 images tend to expand and use up more space than necessary. For example, if you have a small Linux VM in which the base install only takes up 2GB on disk, but you have allotted 8GB to the VM, if you download a large installer file, like a 1GB tarball, which then needs to be extracted and installed inside the VM, it will possibly add 1GB to your VM and then an additional 1GB (or more) once you extract it. Just deleting the tarball afterwards won’t give you back 1GB of your underlying disk space. The qcow2 disk your VM is using has now likely grown to over 4GB. You can however trim away any “wasted” space by using the procedure below, effectively regaining some of your underlying disk space.

Inside of the VM, run:

dd if=/dev/zero of=/zerofile

After a while, when it runs out of disk space in the VM, it will fail with output similar to:

dd: writing to ‘/zerofile’: No space left on device

Now, just go ahead and delete the /zerofile, like so:

rm -f /zerofile

Then, shut down VM:

shutdown -h now

On your Proxmox node, go find the directory in which the qcow2 file is stored (usually in /var/lib/vz/images/<VMID>/) and change the name of the qcow2 file:

mv vm-<VMID>-disk-1.qcow2 vm-<VMID>-disk-1.qcow2.orig

Use qemu-img to convert and compress the file:

qemu-img convert -O qcow2 vm-<VMID>-disk-1.qcow2.orig vm-<VMID>-disk-1.qcow2

Check the size difference between the original file and the newly created one.

When the conversion is complete, start up the VM again to make sure it’s all working correctly. If it works, you can safely delete the backup file with the .orig extension.

Leave a Reply