One of the best things you can do for your web apps is to create/activate a cache system to cache most accessed files or sections of your website. There are many types of cache, the most popular ones are PHP cache into static HTML and SQL cache for the most common MySQL queries. Today we will learn how to create a RAM directory to serve static cache files, mostly used for HTML files.
A RAM directory/folder is always much faster than a directory based on normal hard disk, but it can lost all data when you reboot the server, so the ideal is always to use this RAM directory to store cache files, that can easily re-created after the reboot.
I personally used this same method to speed up the cache files of Nginxtips.com and it’s working really great.
System requirements for this tutorial
- Dedicated server or VPS, I can only recommend the best companies for this:
- A Small Orange
- A2 Hosting
- At least 512MB or 1GB of extra RAM memory to use with this cache system.
- SSH and root access.
Create a tmpfs filesystem to cache the files on RAM
First, stop the webserver you are using:
service nginx stop
service httpd stop service apache2 stop
Tmpfs is a special filesystem type which was originally created for temporary files. On the following example I will configure the tmpfs new partition to serve everything inside the
mount -t tmpfs -o size=2G tmpfs /var/www/nginxtips.com/wp-content/cache
You can tweak the size of the partition depending on how much free RAM you have by altering the
-o option passed to the mount command.
Start the web server:
service nginx start service httpd start service apache2 start
Create a tmpfs filesystem to serve Nginx cache from RAM
You can do the same to improve Nginx performance by caching the
fastcgi_cache files into RAM, the only difference will be the cache directory in the mount point, that will depend on the
proxy_cache_path /var/cache/nginx keys_zone=one:10m;
fastcgi_cache_path /var/cache/nginx levels=1:2 keys_zone=one:10m;
On this case, the mount point will be:
mount -t tmpfs -o size=2G tmpfs /var/cache/nginx
Configure the cache directory to be re-created into RAM automatically after reboot
nano -w /etc/fstab
Add this line at the end:
tmpfs /var/www/nginxtips.com/wp-content/cache tmpfs defaults,size=2G 0 0
Test the RAM directory
[email@example.com:~]df -ah | grep tmpfs tmpfs 2.0G 29M 1996M 1% /var/www/nginxtips.com/wp-content/cache [firstname.lastname@example.org:~]
If you see it mounted with df then it’s working. Now the only thing left for you is to test something that involves those files hosted there, or maybe you can load a few files using your web browser.
Popular search terms:
- nginx create ram folder
- nginx ramdisk
- https://www scalescale com/tips/nginx/mount-directory-into-ram-memory-better-performance/
- nginx cache ram