When your server’s RAM usage reaches 90%, it’s crucial to identify the processes or services consuming the most memory and take steps to optimize or reduce their usage. Here’s how to diagnose and mitigate high RAM usage on a Linux server:
—
1. Check RAM Usage
View Total and Used RAM
Use the free
command to get an overview of RAM usage:
free -h
- Mem: Displays total, used, and available memory.
- Swap: Shows swap memory usage (if available).
Check Real-Time RAM Usage by Processes
Use top
or htop
:
top
Look for processes consuming the most memory under the %MEM column.
Alternatively, if htop
is installed:
htop
It provides a more user-friendly interface to sort processes by memory usage.
—
2. Find High-Memory Processes
Using ps
To list processes sorted by memory usage:
ps aux --sort=-%mem | head -n 10
This lists the top 10 memory-consuming processes.
Using smem
For detailed memory usage by processes:
sudo apt install smem # Install if not available
smem -t -k | head -n 10
—
3. Free Up RAM
Kill Resource-Intensive Processes
After identifying a high-memory process, terminate it if it’s not critical:
sudo kill <PID>
Replace <PID>
with the process ID of the offending process.
To forcefully kill:
sudo kill -9 <PID>
Restart Services
Restarting a service can sometimes release memory leaks:
sudo systemctl restart <service-name>
Clear Cached RAM
The Linux kernel caches data in RAM for better performance, but this can sometimes use excessive memory. To free up cached RAM:
sudo sync; echo 3 > /proc/sys/vm/drop_caches
This clears page cache, dentries, and inodes. Use cautiously, as it might impact performance temporarily.
—
4. Optimize Resource Usage
Use Swap Space
If you don’t have swap configured or it’s too small, consider adding swap to prevent out-of-memory errors:
- Create a swap file:
sudo fallocate -l 1G /swapfile
- Set the correct permissions:
sudo chmod 600 /swapfile
- Format the file as swap:
sudo mkswap /swapfile
- Enable the swap:
sudo swapon /swapfile
To make it persistent across reboots, add this line to /etc/fstab
:
/swapfile none swap sw 0 0
Optimize Applications and Services
Investigate Memory Leaks
If a service consistently uses excessive RAM, it may have a memory leak. Check logs or update the software to the latest version.
—
5. Monitor RAM Usage
Set up monitoring tools to keep track of memory usage and alerts:
—
By identifying the root cause of high memory usage and applying these optimizations, you can maintain server stability and performance. Let me know if you’d like specific guidance!