How to resize a Xen and KVM image?

Resize Xen Image

The steps to resize a xen image are as following:

  1. Enlarge image file.

(Put a chunk(maybe 1mb) at the end of image with new size in order to get the real space.)

  1. Resize file system.
  2. Validate file system.
Resize a xen image to 10GB, sample image: gentoo.img
dd if=/dev/zero of=gentoo.img bs=1024k count=1 seek=10k
resize2fs gentoo.img 10G
e2fsck -pf gentoo.img

Resize KVM Image

WARNNING! This script, resize kvm image, will modify the partition table of image file. Please backup your data before you try my script!

VM in xen uses image partition, like /dev/sda1, to be its root file system. But in KVM, VM need attach disk image to, like /dev/sda, and makes its partitions by itself. So we need to do three more steps to handle the layer between disk and partition.
Steps are as following:

  1. Enlarge image file.
  2. Modify partition table to fit new image size.

    Changing the partition table will not destroy your data. Reformating file system (mkfs) will. That sector start position of partition changes will.

  3. Map the partition to loop device.

    For touching the file system in partition.

  4. Resize file system.

  5. Validate file system.

  6. Remove the mapping between partition and loop device.

    Remember to detach the loop device
# usage: 

# for resize your image named gentoo.img to 10GB

# $ sh gentoo.img 10


# enlarge the size of image file

dd if=/dev/zero of=$image bs=1024k seek=${gb}k count=1

# re-create partition to fit 

echo "d

" | fdisk $image 

# map partition to a loop device

kpartx -a $image
last_device=`ls /dev/mapper/loop* | tail -n 1`

# adjust file system to fit partition size

e2fsck -f $last_device
resize2fs $last_device ${gb}G

# delete map, remove loop device mapping 

kpartx -d $image

in fdisk, type d means delete your old partition. type n means create new partition. type p means select primary type partition. type 1 means choose the partition number as 1. Double new line means its default resizing is from 2048 th sector(first return) to max sectors(second return) it can detect. type w means write changes to disk.


  1. Using fdisk to delete and re-create partition doesn't destroy your data, except you change the sector start position of the partition.

  2. Partition tools make different partition sector start position. cfdisk uses 63 , parted uses 1 , and fdisk uses 2048 as start sector position. My script assumes you use fdisk to set up the VM image. Make sure your image prototype's start sector begins at 2048. (You can check the sector start position by typing fdisk $YOUR_IMAGE, then press p to print detail information.)

  3. In gentoo, please emerge sys-fs/multipath-tools to get kpartx tool. It map the partition inside your image file to loop device. Then you can resize the file system through /dev/mapper/loop{0~8}p1.

comments powered by Disqus