Clear Memory Cache on Linux

By default the Linux OS has a very efficient memory management process that should be freeing any
cached memory on the machine that it is being run on. However when it comes to Cached memory the
Linux OS may at times decide that the Cached memory is being used and is needed which can lead to
memory related issues and ultimately rob your server of any potentially free memory. To combat this you
can force the Linux OS to free up and stored Cached memory.
Kernels 2.6.16 and newer provide a mechanism to have the kernel drop the page cache and/or inode and
dentry caches on command, which can help free up a lot of memory. Now you can throw away that script
that allocated a ton of memory just to get rid of the cache…
To use /proc/sys/vm/drop_caches, just echo a number to it.
To free pagecache:
# sync; echo 1 > /proc/sys/vm/drop_caches
To free dentries and inodes:
# sync; echo 2 > /proc/sys/vm/drop_caches
To free pagecache, dentries and inodes:
#sync; echo 3 > /proc/sys/vm/drop_caches
or
# echo 3 | tee /proc/sys/vm/drop_caches
This is a non-destructive operation and will only free things that are completely unused. Dirty objects will
continue to be in use until written out to disk and are not freeable. If you run sync first to flush them out
to disk, these drop operations will tend to free more memory.
1. At the shell prompt type crontab -e <enter> as this will allow you to edit cron jobs for the root
user.
2. Scroll to the bottom of the cron file using the arrows key and enter the following line:
0 * * * * /root/clearcache.sh
3. Create a file in ‘/root’ called ‘clearcache.sh’ with the following content:
#!/bin/sh
sync; echo 3 > /proc/sys/vm/drop_caches

4. Once you have saved this file, the job is complete!
Many times you may find the system is running out of memory. When checked you can see lots of
memory is assigned to buffers and caches.Allocating lots of memory to buffers and caches is not
necessary. If you are running mysql and oracle like softwares, they have their own buffers and caches. So
mostly you can free or drop this buffers and caches.This post explains how to drop caches in Linux. Also
the entry for sysctl.conf so that it will remember the action.
Or you can specify this in /etc/sysctl.conf
# echo "vm.drop_caches = 3" >> /etc/sysctl.conf
Now reload sysctl.conf
# sysctl -p