How To Clear Cache / Buffer memory automatically on a Linux

Common in Linux than a set of cache which stores frequently accessed pages on the server. If any data is requested by RAM, the configuration is set up so that the cache memory checks for available data and serves it from there. By doing this, servers can use their resources more efficiently and respond more quickly.

A Linux or Unix server’s cache/buffer memory can be flushed in different ways.

How to clear cache/buffer memory on a Linux server?

Option 1:
To clear page cache, directories & inodes i.e. flush all from the cache memory

sync; echo 3 > /proc/sys/vm/drop_caches

Option 2:
To clear only inodes anddirectories from the cache memory

sync; echo 2 > /proc/sys/vm/drop_caches

Option 3:
To clear only page cache from the cache memory

sync; echo 1 > /proc/sys/vm/drop_caches

How to set a cron job to clear cache memory in Linux?

It may be necessary to clear the cache memory and free up disk space at regular intervals. By using crontab, one can automatically clear the cache memory by creating a cron job.

Step 1:Access the Virtual Machine

Access the desired server through the shell as a root or sudo user.

Step 2:Create a shell script

Create a shell script lets say “” under the root (/root) partition with following commands

sync; echo 3 > /proc/sys/vm/drop_caches

Step 3:Set the permission

Set the permission of “” script to 755

chmod 755 /root/

Step 4:Edit the system crontab file

Edit the system crontab file using the below command

crontab -e

Step 5: Set cron jobs

Enter the following line in the crontab file to set cron job for clearing cache memory automatically

0 * * * * /root/

The above cron job will execute the “” script every hour of first second.

Step 6: Restart Crontab

Restart cron service

/etc/init.d/cron reload

Note: One should be a root user or sudo user to perform the above-mentioned operations.

Is it necessary to remove cache memory from RAM periodically?

Well, it depends on the situation. Generally, it is not advisable to clear cache at regular intervals on production servers as this will force the server to serve by disk if the cache is not being built up, thus increasing the server’s load and resources.

Check out How to Install WordPress with OpenLiteSpeed on Ubuntu 20.04.

Hopefully, after consulting this website, you will get a good understanding of the Linux cache.

Please let us know your feedback, queries by posting in the comment section.

Leave a Comment