Storing Files/Directories In Memory With tmpfs

Version 1.0
Author: Falko Timme

You probably know that reading from RAM is a lot of faster than reading files from the hard drive, and reduces your disk I/O. This article shows how you can store files and directories in memory instead of on the hard drive with the help of tmpfs (a file system for creating memory devices). This is ideal for file caches and other temporary data (such as PHP's session files if you are using session.save_handler = files) because the data is lost when you power down or reboot the system.

I do not issue any guarantee that this will work for you!


Using tmpfs

There's a standard memory device on each Linux system (except for some virtual machines - depends on the virtualization technology) - /dev/shm.

When you run


you should see something like this:

tmpfs on /dev/shm type tmpfs (rw,nosuid,nodev)

By default it's about half the size of the system's memory (you can check it's actual size by running

df -h /dev/shm

) - so if you have 4GB of RAM, its size will be about 2GB.

You can use /dev/shm as if it was a normal hard drive, for example, you can copy a file to it:

cp -af test.tar.gz /dev/shm/ 

Et voilà, the file is stored in memory:

ls -la /dev/shm/

server1:/# ls -la /dev/shm/
total 316
drwxrwxrwt 18 root root    380 2008-11-27 16:06 .
drwxr-xr-x 12 root root   3780 2008-11-27 15:33 ..
-rw-r--r--  1 root root 311636 2003-04-02 20:00 test.tar.gz

(Please keep in mind that the file will be lost when you power down or reboot the system!)

If you like, you can resize /dev/shm, for example as follows:

mount -o remount,size=3G /dev/shm

(Grow with care - if you make it too big and use all that space, then less RAM will be left for the rest of the system. This could cause all kinds of unwanted behaviours!)

Now let's assume you want to create some kind of file cache for your high-traffic web site in the directory /var/www/ Of course, it would be good to have this cache in memory. Here's how:

First create the cache directory:

mkdir -p /var/www/

(If needed by your cache, you can change its ownership, e.g. like this:

chown proxy:proxy /var/www/


Now we mount that directory as a memory device (with a size of 100MB and permissions of 755):

mount -t tmpfs -o size=100M,mode=0755 tmpfs /var/www/ 

Take a look at


... and you should see this:

tmpfs on /var/www/ type tmpfs (rw,size=100M,mode=0755)

That's it - now you can cache files directly in memory.

If you want to have that directory mounted at boot time, edit /etc/fstab...

vi /etc/fstab

... and add something like this to the file:

tmpfs /var/www/ tmpfs size=100M,mode=0755 0 0


Share this page:

9 Comment(s)