DEV Community

Brandon Rozek
Brandon Rozek

Posted on • Originally published at brandonrozek.com on

Playing with ZFS using Virtual Disks

Have you wanted to play with ZFS or any other filesystem without creating a dedicated partition or device? We can do this through virtual disks!

First, we need to create a sparse file called scratch.img with some max capacity. Let’s say 2G.

truncate -s 2G $HOME/scratch.img

Enter fullscreen mode Exit fullscreen mode

Now the file is only sparse, if your filesystem supports it. To see, run du -sh $HOME/scratch.img. If it says that the size is 0 then your filesystem supports sparse files. Otherwise it does not.

Then, we can format the file with any filesystem we will like. One popular tool is mkfs which depending on your operating system can support bfs, cramfs, ext2, ext3, ext4, fat, minix, msdos, ntfs, vfat, reiserfs, etc.

To format with ext4,

mkfs -t ext4 $HOME/scratch.img

Enter fullscreen mode Exit fullscreen mode

Then we can create the mount-point /mnt/scratch and mount scratch.img to it.

sudo mkdir /mnt/scratch
sudo mount -t auto -o loop $HOME/scratch.img /mnt/scratch

Enter fullscreen mode Exit fullscreen mode

With this, we now have a mounted ext4 filesystem on /mnt/scratch. cd into it and have a blast!

Resizing the Virtual Disk

To resize the virtual disk, we will first need to unmount the virtual disk so we don’t create inconsistencies.

sudo umount /mnt/scratch

Enter fullscreen mode Exit fullscreen mode

Now we can extend or shrink the drive with truncate.

Extend by 1G: truncate -s +1G $HOME/scratch.img

Shrink by 1G: truncate -s -1G $HOME/scratch.img

Check the filesystem to make sure that no inconsistencies occurred. With ext(2/3/4) we can do this with the e2fsck command.

e2fsck $HOME/scratch.img

Enter fullscreen mode Exit fullscreen mode

Then we need to tell the filesystem to resize itself. For ext(2/3/4) you can do this with the resize2fs command.

resize2fs $HOME/scratch.img

Enter fullscreen mode Exit fullscreen mode

Now the virtual disk is successfully resized! We can mount it back with the previous mount command.

sudo mount -t auto -o loop $HOME/scratch.img /mnt/scratch

Enter fullscreen mode Exit fullscreen mode

Removing the Virtual Disk

To remove the virtual disk, we first need to unmount the virtual drive

sudo umount /mnt/scratch

Enter fullscreen mode Exit fullscreen mode

Then we can remove the mount-point and file.

sudo rm -r /mnt/scratch
rm $HOME/scratch.img

Enter fullscreen mode Exit fullscreen mode

Conclusion

With virtual disks we can experiment with different types of filesystems and perhaps try out snapshoting in supported filesystems. If we create virtual disks on tmpfs, then we can have a super fast file system as well!

Top comments (0)