Linux is designed to manage memory highly efficiently. Rather than letting unused RAM sit idle, the Linux kernel purposefully consumes free memory to aggressively cache frequently accessed files and filesystem structures (inodes and dentries). This drastically speeds up read times for applications.
While this is an excellent feature, there are times when you need to manually intervene. If you are conducting performance benchmarking, testing a heavy application, or troubleshooting a memory leak, you may need to force the kernel to dump these caches and free up physical RAM. This guide explains how to safely clear the PageCache, dentries, and inodes.
Understanding the Risks
It is important to note that clearing the system cache is a non-destructive action. It will not delete your files, kill running processes, or crash the server. However, it will temporarily reduce system performance, as the kernel will have to re-read data directly from the much slower hard drive the next time it is requested, rather than instantly serving it from the lightning-fast RAM cache.
You should not run these commands on a schedule (e.g., via a cron job) simply to make your “Free RAM” number look higher. Let the kernel do its job.
How to Clear the Caches
To clear the caches, you must pass specific numerical values into the /proc/sys/vm/drop_caches kernel interface. Because this is a core system operation, you must execute the commands as the root user.
First, it is highly recommended to run the sync command. This forces the system to write any pending data currently sitting in memory out to the physical hard drive, ensuring no data corruption occurs.
sync
Once the sync is complete, choose one of the following commands based on what you need to clear:
1. Clear Only the PageCache
The PageCache stores the actual file data. This is usually the largest consumer of cached memory.
sudo sh -c 'echo 1 > /proc/sys/vm/drop_caches'
2. Clear Dentries and Inodes
Dentries and inodes store the directory structure and file metadata (permissions, locations, etc.), rather than the file contents themselves.
sudo sh -c 'echo 2 > /proc/sys/vm/drop_caches'
3. Clear Everything (Most Common)
To completely flush all cached file data and directory metadata, freeing up the maximum amount of RAM possible, use the value `3`.
sudo sh -c 'echo 3 > /proc/sys/vm/drop_caches'
If you run the free -h command before and after executing option 3, you will likely see a massive drop in the “buff/cache” column and a corresponding spike in the “free” column.