Extending a disk image file (of a KVM guest for example) is a tricky operation, especially if we haven't enough disk space to keep a backup of the image we will working on. So I write a little howto for the next time we have to do this operation.
Prerequisites
First, you need to have the following packages installed: qemu-utils kpartx
parted
.
Make sure your VM is halted and no processes have opened the file:
# lsof $img
Note: for following commands, I assume $img
contains the path to your image file.
Extend the image file
Pretty easy step, you can simply use qemu-img tool:
# qemu-img resize $img +50G
Image resized.
You can mount the image and check that it has the correct size:
# kpartx -v -a $img
add map loop0p1 (254:13): 0 195318207 linear /dev/loop0 63
# fdisk -l /dev/loop0
Disk /dev/loop0: 214.7 GB, 214748364800 bytes
[...]
Extend the partition
Then, you have to extend the partition. That supposes of course either the disk image contains only one partition (which could be a LVM PV) or the partition you want to extend is at the end of the image.
Before all, backup your partition table:
# sfdisk -d /dev/loop0 >~/loop0.parts
(It could be restored with sfdisk /dev/loop0 <~/loop0.parts
).
And remove and recreate the partition using all free space with parted:
# parted /dev/loop0 print
Model: (file)
Disk /dev/loop0: 215GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos
Number Start End Size Type File system Flags
1 32.3kB 100GB 100GB primary ext3
..
# parted /dev/loop0 rm 1
# parted /dev/loop0 mkpart primary ext3 32.3kB 215GB
# parted /dev/loop0 print
Remount the image to see her new size:
# kpartx -d $img
loop deleted : /dev/loop0
# kpartx -v -a $img
add map loop0p1 (254:13): 0 419430337 linear /dev/loop0 63
Extend the filesystem
We are almost there, remaining the filesystem. First, this is a good thing to run a fsck before all:
# e2fsck -f /dev/mapper/loop0p1
e2fsck 1.42.5 (29-Jul-2012)
/dev/mapper/loop0p1: recovering journal
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/loop0p1: 41753/6111232 files (9.1% non-contiguous), 23479003/24414775 blocks
Then, resize the filesystem:
# resize2fs /dev/mapper/loop0p1
resize2fs 1.42.5 (29-Jul-2012)
Resizing the filesystem on /dev/mapper/loop0p1 to 52428792 (4k) blocks.
The filesystem on /dev/mapper/loop0p1 is now 52428792 blocks long.
It's done! We can check if we see the correct size after mounting the partition:
# mount /dev/mapper/loop0p1 /mnt
# df -h /mnt
Filesystem Size Used Avail Use% Mounted on
/dev/mapper/loop0p1 197G 89G 109G 45% /mnt
# umount /mnt
Finally, unmount the image:
# kpartx -d $img
loop deleted : /dev/loop0