Storing Files/Directories In Memory With tmpfs
Author: Falko Timme
Last edited 11/27/2008
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!
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/
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/www.example.com/cache. Of course, it would be good to have this cache in memory. Here's how:
First create the cache directory:
mkdir -p /var/www/www.example.com/cache
(If needed by your cache, you can change its ownership, e.g. like this:
chown proxy:proxy /var/www/www.example.com/cache
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/www.example.com/cache
Take a look at
... and you should see this:
tmpfs on /var/www/www.example.com/cache 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...
... and add something like this to the file:
[...] tmpfs /var/www/www.example.com/cache tmpfs size=100M,mode=0755 0 0 [...]
- Wikipedia entry about tmpfs: http://en.wikipedia.org/wiki/TMPFS