「Linux」- 缩小 Ext4 分区(调整文件系统大小、缩小文件系统、扩大文件系统)

问题描述

环境信息:
1)/dev/mapper/dt-libvirt ext4 295G 101G 179G 37% /var/lib/libvirt
2)我们需要将其缩小到 110G 磁盘空间;
3)操作系统:Ubuntu 21.04

解决方案

注意事项

磁盘调整操作有风险,请注意数据**备份**!

为了校验数据一致性,在磁盘调整之前与之后,我们都会执行如下脚本,用于检查数据一致性:

# find ./ -type f -print0 | xargs -0 -i md5sum '{}'

第一步、缩小文件系统

systemctl stop libvirtd.service # 移除磁盘占用,否则无法 umount
umount /var/lib/libvirt

# e2fsck -f /dev/mapper/dt-libvirt
e2fsck 1.45.7 (28-Jan-2021)
Pass 1: Checking inodes, blocks, and sizes
Pass 2: Checking directory structure
Pass 3: Checking directory connectivity
Pass 4: Checking reference counts
Pass 5: Checking group summary information
/dev/mapper/dt-libvirt: 54/19660800 files (0.0% non-contiguous), 27925391/78643200 blocks

# resize2fs /dev/mapper/dt-libvirt 110G
resize2fs 1.45.7 (28-Jan-2021)
Resizing the filesystem on /dev/mapper/dt-libvirt to 28835840 (4k) blocks.
The filesystem on /dev/mapper/dt-libvirt is now 28835840 (4k) blocks long.

第二步、缩小分区

针对普通分区:通过 cfdisk 命令,重新创建分区表即可。

针对 LVM 环境:

# lvs
  LV      VG Attr       LSize   Pool Origin Data%  Meta%  Move Log Cpy%Sync Convert
  home    dt -wi-ao----  50.00g                                                    
  libvirt dt -wi-a----- 300.00g                                                    
  local   dt -wi-ao----  50.00g                                                    
  opt     dt -wi-ao----  50.00g                                                    
  srv     dt -wi-ao---- 200.00g                                                    

# lvreduce -L 110G /dev/dt/libvirt 
  WARNING: Reducing active logical volume to 110.00 GiB.
  THIS MAY DESTROY YOUR DATA (filesystem etc.)
Do you really want to reduce dt/libvirt? [y/n]: y
  Size of logical volume dt/libvirt changed from 300.00 GiB (76800 extents) to 110.00 GiB (28160 extents).
  Logical volume dt/libvirt successfully resized.

# lvs
  LV      VG Attr       LSize   Pool Origin Data%  Meta%  Move Log Cpy%Sync Convert
  home    dt -wi-ao----  50.00g                                                    
  libvirt dt -wi-a----- 110.00g                                                    
  local   dt -wi-ao----  50.00g                                                    
  opt     dt -wi-ao----  50.00g                                                    
  srv     dt -wi-ao---- 200.00g  

参考文献

LVM Resize – How to Decrease an LVM Partition
How to Shrink an ext2/3/4 File system with resize2fs – Red Hat Customer Portal
partitioning – Shrinking ext4 partition on command line – Ask Ubuntu
How to Resize a Partition using fdisk – Red Hat Customer Portal