If like me, you manage your own Linux server, it is essential to know how to release its cached memory. In a nutshell, Linux always tries to use RAM to speed up disk operations and uses available memory for buffers (file system metadata) and cache (pages with actual contents of files or block devices). This helps the system to run faster because disk information is already in memory which saves I/O operations. If space is needed by programs or applications like MySQL, Linux will free the buffers and cache to provide memory where it is needed.
However when it comes to cached memory, Linux, may at times, decide to latch-on to stored data because it thinks that they are being used. This can lead to memory related issues that may ultimately bog down your server. To fix this, you can force Linux to expunge the cached memory.
- sync writes any data buffered in memory out to disk. This can include (but is not limited to) modified superblocks, modified inodes, and delayed reads and writes. This must be implemented by the kernel;2
- free displays the total amount of free and used physical and swap memory in the system, as well as the buffers used by the kernel;3
- echo display a line of text.4
- crontab is a file that contains instructions to the cron daemon of the general form: “run this command at this time on this date”. Each user has their own crontab, and commands in any given crontab will be executed as the user who owns the crontab.
root@sam: free -m (This is used to display the current server memory information)
root@sam: sync (This synchronizes data on disk with memory)
root@sam: echo 1 > /proc/sys/vm/drop_caches (To free pagecache)
root@sam: echo 2 > /proc/sys/vm/drop_caches (To free dentries and inodes)
root@sam: echo 3 > /proc/sys/vm/drop_caches (To free pagecache, dentries and inodes)
Personally, I prefer “echo 3” because it clears all caches in one line.
Here’s how it looks like in real life:
To automate the process, we can create a little script that the Linux scheduler, cron,6 can run periodically. Here’s how:
- Create a file in your home folder, or any folder that you prefer, called “purge.sh.” The file should contain the text below:
sync; echo 3 > /proc/sys/vm/drop_caches
- At the shell prompt key-in the commands below:root@sam:
root@sam: crontab -e
- Scroll to the bottom of the cron file using the arrows key and enter the following line:
0 * * * * /home/purge.sh
For more information on cron parameters, please check the manual at http://linux.die.net/man/5/crontab.