If the case is remote server without console, you can shrink filesystem using initramfs while rebooting. You need to add resize2fs to initramfs and run it before mounting root.
Debian/Ubuntu example:
/etc/initramfs-tools/hooks/resizefs (executable):
#!/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
/etc/initramfs-tools/scripts/local-premount/resizefs (executable)
#!/bin/sh
set -e
PREREQS=""
prereqs() { echo "$PREREQS"; }
case "$1" in
prereqs)
prereqs
exit 0
;;
esac
# simple device example
/sbin/e2fsck -yf /dev/sda1
/sbin/resize2fs /dev/sda1 5G # see size info below
/sbin/e2fsck -yf /dev/sda1
# complex device example
# activate md-raid containing FS/PV
#/sbin/mdadm -A /dev/md0
# activate VG containing FS
#/sbin/lvm vgchange -ay vg0
# resize
#/sbin/e2fsck -yf /dev/vg0/root # or /dev/md0
#/sbin/resize2fs /dev/vg0/root 5G
#/sbin/e2fsck -yf /dev/vg0/root
Now run update-initramfs -u -k kernel-name
to update initramfs for the kernel kernel-name
which is set as default in your bootloader (grub). In case of boot failure - you can boot with another unmodified healthy kernel/initramfs. Or you can use all
to update all kernels, but then you have no way back.
Check that you do not have any tools in your system that grow filesystem automatically (e.g. cloud-init - comment resizefs
in /etc/cloud/cloud.cfg
).
Reboot. Check filesystem size. Remove initramfs scripts and run update-intiramfs -u -k kernel-name
again.
Now you can shrink underlying device with parted resizepart
/ mdadm --grow --size=
/ lvresize -L
. The size of the device should be bigger then the size of filesystem from the scripts. The simplest way to make no mistakes: if planned device size - 6G. set fs size in the script to 5G. after fs is resized - resize device to 6G, then grow fs to maximum online with resize2fs /dev/sda1
. Now your fs fits perfectly in your device.
For dracut (Fedora,CentOS) use the same logic (/usr/lib/dracut/modules.d).
This is very usefull for crypting or moving rootfs, with no free space available for the new partition.