Shrinking a Logical Volume (LVM)
Today I will be going through the process of shrinking a logical volume to free up space on a particular volume group (vg0) in Linux's Logical Volume Manager (LVM). This same/similar process can also be used for expanding volumes, albeit much less dangerous.
We will be shrinking /dev/vg0/onodera-web
— that is, the logical volume onodera-web, which is a part of the volume group vg0. Its current size is 300.0GiB, however, I need space for other things, so it needs to be trimmed a bit.
Currently, we only have about ~66GiB free on vg0. After the resize, we should have well over 100GiB to play with:
root@onodera ~ # vgs
VG #PV #LV #SN Attr VSize VFree
vg0 2 1 0 wz--n- 366.63g 66.63g
Unmount and initial check
First, make sure any running programs or processes that utilize data from this mountpoint have been stopped— in my case, I needed to stop nginx and pm2 (Node.js). Then unmount the volume, and run an fsck against it. You can use -f
to force a check, even if the volume is marked clean. The -C0
option outputs status information to fd 0 (stdout).
umount /dev/vg0/onodera-web
fsck -C0 -f /dev/vg0/onodera-web
If you are running a website or other service from your LV, and would like to minimize downtime for large volumes while scanning, you can remount the filesystem in read-only mode prior to running fsck via
mount -o remount,ro /dev/vg0/onodera-web
— just be sure to unmount once the fsck finished successfully.
If the filesystem was modified, I would recommend re-running fsck once again. Once you've confirmed all is clean, time to move on.
I would also recommend saving information about the LV prior to resizing (such as the exact size of the volume), in case you should need to revert your changes, or the post-resize fsck fails:
lvdisplay --units=b /dev/vg0/onodera-web > preshrink.log
Filesystem resize (resize2fs)
We will now perform the actual resizing of the filesystem-- in this case, the filesystem type is ext4 (resize2fs can be used for any of the Extended filesystems: ext2/ext3/ext4).
resize2fs -p /dev/vg0/onodera-web 250G
If all went well, you should see a message such as: The filesystem on /dev/vg0/onodera-web is now 65536000 (4k) blocks long. (Note: 65536000 blocks * 4096 = 268435456000 bytes = exactly 250.0 GiB)
Logical volume resize (lvreduce)
Now to resize the logical volume to match the filesize:
lvreduce -L 250G /dev/vg0/onodera-web
Final check & remount
fsck -C0 -f /dev/vg0/onodera-web
If the check returned happily, you should now be able to safely remount the volume (note that you may need to adjust the next command if this volume is not in your fstab)
mount /dev/vg0/onodera-web
Now we can check our newly liberated free space:
root@onodera ~ # vgs
VG #PV #LV #SN Attr VSize VFree
vg0 2 1 0 wz--n- 366.63g 116.63g
And that's it! Good luck ^_~