When shrinking dynamic virtual machine disk images (such as VirtualBox VDI, VMware VMDK, or QEMU QCOW2), zeroing out unused filesystem blocks is essential for effective host compression. Because Enterprise Linux distributions (CentOS 6/7, RHEL) do not ship zerofree in their default package repositories, compiling from source is the quickest solution.
1. Installing Build Headers and Compiling zerofree
Install the e2fsprogs development headers and compile:
yum install e2fsprogs-devel gcc make -y
cd /usr/src
wget http://frippery.org/uml/zerofree-1.0.3.tgz
tar -zxf zerofree-1.0.3.tgz
cd zerofree-1.0.3
make
cp zerofree /usr/bin/
2. Zeroing Out Unallocated Blocks
Important: Always remount the target filesystem in read-only mode prior to executing zerofree to prevent filesystem corruption:
# Remount filesystem as read-only:
mount -o remount,ro /
# Run zerofree on the target block partition:
zerofree -v /dev/sda1
Once complete, shut down the VM and run your hypervisor's disk compacting command (e.g. VBoxManage modifymedium --compact disk.vdi) on the host machine.