How to clear RAM memory Cache in Linux

Whether for your VPS or your PC manually clearing RAM cache on your Linux system without rebooting can be useful.

RAM image
Photo by Possessed Photography / Unsplash

Linux is a robust system built with memory management like all other systems. However Linux gives you granular control in freeing the cache. You might sometime find yourself in a situation where a software is consuming more RAM than expected and you just want to free the RAM.

A RAM is a type of volatile storage used to store running apps data and instruction sets. Unlike your other types of storage such as hard disk or SSD which are non-volatile a ram is extremely faster however on power loss all data is cleared.

First method - Rebooting

Now the  understanding of what a RAM is this technically means the first way/method to clear your RAM is rebooting your Linux system.

Second Method - Clearing memory yourself

So you run a VPS or a critical infrastructure and a reboot of your system would cause unnecessary down time. In Linux it is possible to manually clear RAM cache.

The command for clearing cache is sync. We usually append ";" in front of the command so that the command run's sequentially. The final part is writing to drop_cache this is necessary so we can clean the cache without killing any running application/service because that would be a nightmare.

NB: If the commands don't run as sudo run them as root user. To do that run "su -"
su - command

Clearing page cache

A page cache is a type cache that emanates from I/O operations on the hard disk / SSD. This is a cache from operations such as read(),write() and mmap().

Clearing inodes and dentries

Inodes are data structures that represent a file while dentries data structures that represent file or folder.

sync; echo 2 > /proc/sys/vm/drop_caches
clearing inodes and dentries cache.

Clearing page cache, inodes and dentries

sync; echo 3 > /proc/sys/vm/drop_caches
clearing page cache, inodes and dentries

Conclusion

Whether for your VPS or your PC you can manually clear RAM cache on your Linux system without rebooting.  You can automate the task by writing a shell script and run the shell script periodically using crontabs.

#!/bin/bash
echo "echo 3 > /proc/sys/vm/drop_caches"
shell script

Subscribe to Bluedoa Digest

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
Enter your email
Subscribe