Virtual Loopback Filesystem: Building A Linux Filesystem From An Ordinary File

Unix / Linux has a great inbuilt simplicity to it where you can create file systems on any block set . Now .. a file is a block  set so technically and truly at it’s core a file system can be built on a file and mounted :

I need a 100MB partition for some tests :

Using ofcourse Google as my calculator {pfsssst !!! obviously .. DUH}. I tried 100MB / 512 bytes and got

(100 megabytes) / (512 bytes) = 204 800

[root@localhost admin]# dd if=/dev/zero of=disk-image count=204800
204800+0 records in
204800+0 records out
104857600 bytes (105 MB) copied, 41.8633 s, 2.5 MB/s
[root@localhost admin]#

This command leaves me with a 105MB file in which to create my etx3 fs like so :

[root@localhost admin]# ls -al disk-image 
-rw-r--r--. 1 root root 104857600 Jul 13 18:17 disk-image
[root@localhost admin]#

Once this file is created I will use the mkfs to format over the disk-image file:

[root@localhost admin]# /sbin/mkfs -t ext3 -q disk-image
disk-image is not a block special device.
Proceed anyway? (y,n) y
[root@localhost admin]#

Thus a filesystem now resides on my file named disk-image.

We can now use a loopback device to mount the disk-image anywhere we need it:

[root@localhost admin]# mkdir /mnt/test1
[root@localhost admin]# mount
/dev/sda2 on / type ext4 (rw)
proc on /proc type proc (rw)
sysfs on /sys type sysfs (rw)
devpts on /dev/pts type devpts (rw,gid=5,mode=620)
tmpfs on /dev/shm type tmpfs (rw,rootcontext="system_u:object_r:tmpfs_t:s0")
/dev/sda1 on /boot type ext4 (rw)
none on /proc/sys/fs/binfmt_misc type binfmt_misc (rw)
[root@localhost admin]# mount disk-image /mnt/test1/
mount: /home/admin/disk-image is not a block device (maybe try `-o loop'?)
[root@localhost admin]# mount -o loop disk-image /mnt/test1/
[root@localhost admin]# cd /mnt/test1/
[root@localhost test1]# ls
lost+found
[root@localhost test1]# df -h
Filesystem            Size  Used Avail Use% Mounted on
/dev/sda2              18G  2.7G   14G  16% /
tmpfs                 504M  768K  503M   1% /dev/shm
/dev/sda1             291M   50M  226M  19% /boot
/home/admin/disk-image
                       97M  5.6M   87M   7% /mnt/test1

[root@localhost test1]# touch file1
[root@localhost test1]# mkdir -p top1/bottom1
[root@localhost test1]# tree
.
+-- file1
+-- lost+found
+-- top1
    +-- bottom1

3 directories, 1 file
[root@localhost test1]#

Thus a new file system is now running inside the file.

Backing up that file or moving it to another system would entail now quiescing any applications/scripts working with the file, unmounting the loopback fs system, doing your thing then replace all the cards on the deck 🙂

Write a Reply or Comment

Your email address will not be published.