ramfs, another option is the
/dev/ram0 block device. On recent Ubuntu versions, this device does not exist by default, but can be created via
This approach is more predictable since it creates a real
ext4 filesystem and never exceeds the limit you specify. But it takes more steps to set up, and uses RAM less efficiently.
Using brd kernel module (/dev/ram0)
To create and initialize a 4GB RAM disk:
modprobe brd rd_nr=1 rd_size=$((4 * 1048576))
mount /dev/ram0 /ramdisk
rd_nr parameter specifies how many RAM disks to create (by default, it creates 16, i.e.
rd_size parameter is size in kilobytes. The
$(( ... )) syntax lets you do arithmetic in the shell.
To deallocate the RAM disk, unmount it and remove the
brd kernel module:
modprobe -r brd
Creating a block device inside
Alternatively, you can create a block device inside of
mkdir /ramdisk-storage /ramdisk
mount -t ramfs ramfs /ramdisk-storage
truncate -s 4G /ramdisk-storage/ramdisk.img
mount /ramdisk-storage/ramdisk.img /ramdisk
truncate command creates an empty file of a given size such that it is initialized (i.e. consumes memory) on-demand.
To deallocate the RAM disk, umount it and delete the disk image:
ramfs are more efficient than using a block device, below are some of their downsides.
tmpfs may swap to disk. This is more efficient, but there may be times you want a pure RAM disk:
- The files you are working with are sensitive (e.g. files from an encrypted partition).
- You are doing performance testing and you don't want disk I/O to be a factor (SSD write times can vary a lot).
- You are unpacking a large file and you don't want to wear out your SSD.
ramfs is easy to set up, reclaims space once you delete files, and uses RAM more efficiently (the system does not buffer the files because it knows they are in RAM). But it has its own downsides and surprises:
df utility does not report space usage:
root@cello-linux:~# df -h /ramdisk
Filesystem Size Used Avail Use% Mounted on
ramfs 0 0 0 - /ramdisk
There is no size limit parameter. If you put too much in the ramdisk, your system will hang.
Sparse files can become unsparse when you least expect it. This morning, I copied a VM image (150G, but 49G used on disk) to
ramfs (I have 128G of RAM). That worked. But when I copied from the
ramfs to the destination, my system became unresponsive. The
cp utility apparently filled the holes on read, but not on write.
ramfs may behave differently than a real
ext4 filesystem. Creating a block device in RAM and initializing it with
ext4 avoids this.
For a more in-depth comparison: https://www.kernel.org/doc/Documentation/filesystems/ramfs-rootfs-initramfs.txt