Shrink Virtual Harddisk Size

From Kicksecure

Free disk space. Decrease the size of a virtual disk. Decrease virtual machine storage capacity.

VirtualBox[edit]

Undocumented. Unspecific to Kicksecure ™. Free Support Principle applies.

KVM[edit]

Over the course of many system upgrades, logging, etc. the image files can grow substantially. Deletion of obsolete files does not automatically shrink the disk size back as it has “grown” to accommodate the data needed.

A tool called zerofree free is needed to shrink the backing virtual disk file. Since the default are ext4 partitions, the process might be bit involved:

Inside the VM:

1. Install the package zerofree in the virtual machine you want to shrink.

Install zerofree. To accomplish that, the following steps A. to D. need to be done.

A. Update the package lists.

sudo apt update

B. Upgrade the system.

sudo apt full-upgrade

C. Install the zerofree package.

Using apt command line parameter --no-install-recommends is in most cases optional.

sudo apt install --no-install-recommends zerofree

D. Done.

The procedure of installing zerofree is complete.

2. Erase what you need in the VM, run apt-get purge, apt-get autoremove, apt-get clean, etc. as needed.

3. Reboot your virtual machine in recovery mode.

4. At the command prompt, type

systemctl stop systemd-journald.socket && systemctl stop systemd-journald.service && mount -o remount,ro / && zerofree -v /dev/vda1 && shutdown now

5. Shut down the VM.

On the host:

6. Open a terminal on the host.

7. Switch to root.

sudo -s

8. Change directory to the /var/lib/libvirt/images folder.

cd /var/lib/libvirt/images

9. View files inside the /var/lib/libvirt/images folder.

ls

10. Create a back up of the disk you want to shrink by moving YourVirtualMachineDisk.qcow2 to YourVirtualMachineDisk.qcow2.backup.

Note:

  • Replace YourVirtualMachineDisk.qcow2 with the actual name of your virtual harddisk.
  • Replace YourVirtualMachineDisk.qcow2.backup with the actual name of your virtual harddisk.

mv YourVirtualMachineDisk.qcow2 YourVirtualMachineDisk.qcow2.backup

11. Shrink the disk using qemu-img.

qemu-img convert -o qcow2 -p YourVirtualMachineDisk.qcow2.backup YourVirtualMachineDisk.qcow2

12. Boot up the VM and see if it is working. If it is, you can delete the backup of the qcow file.

There are ways you can get more creative with this using thin provisioned images that are based on a static qcow2 backing file, a preferred method. However the above is a basic method for getting a shrunken qcow2 disk file. [1]

See Also[edit]

Footnotes[edit]



Unfinished: This wiki is a work in progress. Please do not report broken links until this notice is removed, use Search Engines First and contribute improving this wiki.