Clear Memory Cache in Linux

Linux has a memory management system that will use free RAM as cache. This section of memory should be freely available to be taken over when something else needs it, but it seems like Linux is not releasing it because it thinks it is being used and this causes problems. I monitor our servers and recently I’ve been having issues with memory showing critical.

Whenever this happens, we would usually wait until it get’s really slow and then restart. I got tired of restarting the server every time so I set out researching and found an easy way.

Log into your troubled machine and become root

sudo -i

Run one of the following, I use the echo 3 option:

  • To free pagecache:
echo 1 > /proc/sys/vm/drop_caches
  • To free dentries and inodes:
echo 2 > /proc/sys/vm/drop_caches
  • To free pagecache, dentries and inodes:
echo 3 > /proc/sys/vm/drop_caches

Automating it

Log into your troubled machine and create a script called clearcache.sh with the following content:

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

Setup a crontab entry:

sudo -i
crontab -e

Scroll to the bottom of the file and enter the following line

0 * * * * /path/to/clearcache.sh

Create a file in ‘/root’ called ‘clearcache.sh’ with the following content

Once you have saved this file, the job is complete!

Every hour the cron job will run this command and clear any memory cache that was built up.



Share your thoughts

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s