There are several scenarios where a filesystem contained in a single file might come handy.
This post explains how to set up that kind of configuration on a Debian Linux system. The procedure explained here can also be applied to other Linux distros, such as Ubuntu.
A computer is usually equipped with one or more physical disks, each of which is divided into several partitions. Under Linux, each partition contains a file system of a given type (excluding the partitions used as swap areas, or other special purposes).
On a production system, we might not have the possibility to modify the configuration of disks, partitions and file systems, due to limitations imposed by our hosting provider, or to other reasons. But, by using a file as a “virtual” filesystem, we have complete freedom to create last generation filesystems such as zfs or btrfs, with advanced features such as encryption, data compression, etc.
Besides, having a whole filesystem in a file enhances the portability, because moving the information to a new system becomes a matter of copying a single file.
Create the container file
1. Create a 1 GB file named “linux.ex2” de 1 GB:
dd if=/dev/zero of=linux.ex2 bs=1024 count=1048576
2. Create the filesystem inside the container
In this example, the mke2fs command with adequate options is used to create the desired filesystem type
# mke2fs -i 8192 -j linux.ex2
mke2fs 1.41.12 (17-May-2010)
linux.ex2 is not a block special device.
Proceed anyway? (y,n) y
OS type: Linux
Block size=4096 (log=2)
Fragment size=4096 (log=2)
Stride=0 blocks, Stripe width=0 blocks
131072 inodes, 262144 blocks
13107 blocks (5.00%) reserved for the super user
First data block=0
Maximum filesystem blocks=268435456
8 block groups
32768 blocks per group, 32768 fragments per group
16384 inodes per group
Superblock backups stored on blocks:
32768, 98304, 163840, 229376
Writing inode tables: done
Creating journal (8192 blocks): done
Writing superblocks and filesystem accounting information: done
This filesystem will be automatically checked every 35 mounts or
180 days, whichever comes first. Use tune2fs -c or -i to override.
In the example above, the new filesystem has been created with 8 block groups of 16384 inodes, for a total of 131072 inodes. Besides, option “-j” resulted in the creation of a journaling filesystem.
Mount the filesystem
The same mount command used to mount filesystems created in physical disk partitions can be used with option ” -o loop=/dev/loop0″ to mount a filesystem created in a file container:
# mount linux.ex2 /mnt -o loop=/dev/loop0