Shrink root partition

From Luniwiki
Jump to: navigation, search

Hook initramfs

you can shrink filesystem using initramfs while rebooting. You need to add resize2fs to initramfs and run it before mounting root.
We define the hook

cat /etc/initramfs-tools/hooks/resizefs
#!/bin/sh
set -e
PREREQS=""
prereqs() { echo "$PREREQS"; }
case $1 in
   prereqs)
       prereqs
       exit 0
   ;;
esac
. /usr/share/initramfs-tools/hook-functions
copy_exec /sbin/e2fsck
copy_exec /sbin/resize2fs
exit 0

We make it executable

chmod +x /etc/initramfs-tools/hooks/resizefs

Script to shrink, we put less than the definitive size

cat /etc/initramfs-tools/scripts/local-premount/resizefs
#!/bin/sh
set -e
PREREQS=""
prereqs() { echo "$PREREQS"; }
case "$1" in
   prereqs)
       prereqs
       exit 0
   ;;
esac
/sbin/e2fsck -yf /dev/mapper/vg-root
/sbin/resize2fs /dev/mapper/vg-root 9G
/sbin/e2fsck -yf /dev/mapper/vg-root

We make it executable

chmod +x /etc/initramfs-tools/scripts/local-premount/resizefs

Update initramfs

update-initramfs -u

Reboot the server

reboot

Check the size of the partition

df -h /dev/mapper/vg-root
/dev/mapper/rigel--vg-root  8.8G  2.6G  5.8G  31% /

Reduce the logical volume

lvreduce /dev/mapper/vg-root -L 10G
 WARNING: Reducing active and open logical volume to 10.00 GiB
 THIS MAY DESTROY YOUR DATA (filesystem etc.)
Do you really want to reduce root? [y/n]: y
 Size of logical volume vg/root changed from 29.02 GiB (7429 extents) to 10.00 GiB (2560 extents).
 Logical volume root successfully resized.

Extend the root partition

We extend the root partition from 9GB to the full size of the logical volume (10GB).

resize2fs /dev/mapper/vg-root
resize2fs 1.42.13 (17-May-2015)
Filesystem at /dev/mapper/vg-root is mounted on /; on-line resizing required
old_desc_blocks = 1, new_desc_blocks = 1
The filesystem on /dev/mapper/vg-root is now 2621440 (4k) blocks long.

Remove hook scripts

rm /etc/initramfs-tools/hooks/resizefs
rm /etc/initramfs-tools/scripts/local-premount/resizefs
update-initramfs -u
update-initramfs: Generating /boot/initrd.img-4.4.0-134-generic

And we reboot the server

reboot

Check the size of the partition

df -h /dev/mapper/vg-root
/dev/mapper/rigel--vg-root  9.8G  2.6G  6.7G  28% /

References

Daniel Simao (talk) 23:59, 30 August 2018 (EDT)