How to use Nginx for in-memory caching⚓
This article will discuss requirements needed to add in-memory caching for all Nginx configuration files.
What is in-memory caching?⚓
In-memory caching is a technique that allows Nginx to cache content to memory instead of a disk. Because memory is faster than disk, the cached content can be served that much faster.
How to Utilize in-memory caching⚓
In order to utilize in-memory caching through Nginx, you first need to determine how much free RAM you have available. This will help with figuring out how much RAM can be allocated towards caching. This can be found by running
free -h in a terminal.
On my VPS on DigitalOcean, I currently have 1gb of RAM allocated for caching, amounting to 25% of my total RAM. The mileage may vary depending on the amount of RAM available.
Once the amount of available RAM has been determined, the Nginx config files will need to be modified in order to utilize
tmpfs, which is a file system that lives in memory. Because this is being configured for Nginx, we'll be using the
tmpfs already exists, we need to mount it in RAM. This can be done with the following command:
This will create the RAM storage, but in it's current state, it won't persist after a reboot. In order to do this,
tmpfs needs to be added to the
/etc/fstab file. This can be done with the following steps:
- Navigate to
sudo nano /etc/fstab.
- Add the following to the bottom of the file:
- Save and exit
This will now allow
tmpfs to persist in RAM after a reboot.
Modifying Nginx Configs⚓
tmpfs not created in RAM, Nginx can be be configured to utilize the space.
Since all services utilizing Nginx are currently configured to use either fast_cgi or proxy_pass, the following steps can be taken in order to properly configure Nginx:
- Navigate to
- Within the Nginx config file, either add the following line at the top of the config file or modify the cache_path:
- Ensure the following exists within the PHP location block:
- Save and exit, then restart Nginx
Once this has been completed, Nginx will automatically use the mounted storage for cache.