Virtual Hard Disk (VHD) is a disk image file format which represents a virtual hard disk drive, capable of storing the complete contents of a physical hard drive. It’s a container file that acts similar to a physical hard drive. The disk image replicates an existing hard drive and includes all data and structural features.

Just like a physical hard drive, a VHD can contains a file system, and you can use it to store and run an operating system, applications, as well as store data. One of the typical uses of VHDs in VirtualBox Virtual Machines (VMs) to store operating systems and application, and data.

In this article, we will demonstrate how to create a virtual hard disk volume using a file in Linux. This guide is useful for creating VHDs for testing purposes in your IT environment. For the purpose of this guide, we will create a VHD volume of size 1GB, and format it with EXT4 file system type.

Create a New Image to Hold Virtual Drive Volume

There are number of ways you can do this, but the most easiest way is using the following dd command. In this example, we will be creating a VHD volume of size 1GB image.

$ sudo dd if=/dev/zero of=VHD.img bs=1M count=1200

Where:

  • if=/dev/zero: input file to provide a character stream for initializing data storage
  • of=VHD.img: image file to be created as storage volume
  • bs=1M: read and write up to 1M at a time
  • count=1200: copy only 1200M (1GB) input blocks
Create VHD Image File in Linux
Create VHD Image File in Linux

Next, we need to format the EXT4 file system type in the VHD image file with the mkfs utility. Answer y, when prompted that /media/VHD.img is not a block special device as shown in the following screenshot.

$ sudo mkfs -t ext4 /media/VHD.img
Format VHD Image
Format VHD Image

In order to access the VHD volume, we need to mount to a directory (mount point). Run these commands to create the mount point and mount the VHD volume, respectively. The -o is used to specify options for mounting, here, the option loop indicates the device node under the /dev/ directory.

$ sudo mkdir /mnt/VHD/
$ sudo mount -t auto -o loop /media/VHD.img /mnt/VHD/

Note: The VHD filesystem will only remain mounted until the next reboot, to mount it at system boot, add this entry in the /etc/fstab file.

/media/VHD.img /mnt/VHD/ ext4 defaults 0 0

Now you can verify the newly created VHD filesystem with mount point using the following df command.

$ df -hT
Check VHD Filesystem
Check VHD Filesystem

Removing Virtual Drive Volume

If you don’t need the VHD volume anymore, run the following commands to unmount the VHD filesystem, then delete the image file:

$ sudo umount /mnt/VHD/
$ sudo rm /media/VHD.img

Using the same idea, you can also create a swap area/space using a file in Linux.

That’s all! In this guide, we have demonstrated how to create a virtual hard disk volume using a file in Linux. If you have any thoughts to share or questions to ask, reach us via the comment form below.

Similar Posts