How to check memory usage in Linux
How to Check Memory Usage in Linux
Memory management is a crucial aspect of Linux system administration. Whether you're troubleshooting performance issues, optimizing resource allocation, or monitoring server health, understanding how to check memory usage in Linux is an essential skill. This comprehensive guide will walk you through various methods to monitor RAM usage, from basic command-line tools to advanced monitoring techniques.
Table of Contents
- [Understanding Linux Memory Management](#understanding-linux-memory-management)
- [Using the free Command](#using-the-free-command)
- [Monitoring Memory with top and htop](#monitoring-memory-with-top-and-htop)
- [Examining /proc/meminfo](#examining-procmeminfo)
- [Process-Specific Memory Monitoring](#process-specific-memory-monitoring)
- [Advanced Memory Monitoring Tools](#advanced-memory-monitoring-tools)
- [Interpreting Memory Usage Data](#interpreting-memory-usage-data)
- [Troubleshooting Common Memory Issues](#troubleshooting-common-memory-issues)
- [Best Practices for Memory Monitoring](#best-practices-for-memory-monitoring)
Understanding Linux Memory Management
Before diving into the tools, it's important to understand how Linux manages memory. Linux uses a sophisticated memory management system that includes:
- Physical RAM: The actual hardware memory installed in your system
- Virtual Memory: A combination of RAM and swap space
- Buffer Cache: Memory used for caching file system metadata
- Page Cache: Memory used for caching file contents
- Swap Space: Disk space used as virtual memory when RAM is full
Linux memory appears in several categories:
- Used: Memory currently allocated to processes
- Free: Completely unused memory
- Available: Memory available for new processes (includes cached memory that can be freed)
- Cached: Memory used for caching files and data
- Buffer: Memory used for system buffers
Using the free Command
The `free` command is the most straightforward tool for checking memory usage in Linux. It provides a quick overview of total, used, and available memory.
Basic free Command Usage
```bash
free
```
This displays memory usage in kilobytes by default:
```
total used free shared buff/cache available
Mem: 8147928 1234567 5678901 123456 1234560 6543210
Swap: 2097148 0 2097148
```
free Command Options
To make the output more readable, use these common options:
```bash
Display in human-readable format
free -h
Display in megabytes
free -m
Display in gigabytes
free -g
Continuous monitoring (update every 2 seconds)
free -s 2
Show total line
free -t
```
Example output with human-readable format:
```bash
free -h
```
```
total used free shared buff/cache available
Mem: 7.8G 1.2G 5.4G 120M 1.2G 6.2G
Swap: 2.0G 0B 2.0G
```
Understanding free Command Output
- total: Total installed RAM
- used: Memory used by processes
- free: Unused memory
- shared: Memory used by tmpfs filesystems
- buff/cache: Memory used for buffers and cache
- available: Estimate of memory available for new processes
Monitoring Memory with top and htop
The `top` and `htop` commands provide real-time monitoring of system resources, including memory usage per process.
Using top Command
```bash
top
```
The top section shows overall system memory usage:
```
Tasks: 234 total, 1 running, 233 sleeping, 0 stopped, 0 zombie
%Cpu(s): 2.3 us, 1.1 sy, 0.0 ni, 96.4 id, 0.2 wa, 0.0 hi, 0.0 si, 0.0 st
MiB Mem : 7956.0 total, 5542.5 free, 1205.7 used, 1207.8 buff/cache
MiB Swap: 2048.0 total, 2048.0 free, 0.0 used. 6436.2 avail Mem
```
Key top Commands for Memory Monitoring
- Press `M` to sort processes by memory usage
- Press `P` to sort by CPU usage
- Press `q` to quit
Using htop (Enhanced Alternative)
First, install htop if it's not available:
```bash
Ubuntu/Debian
sudo apt install htop
CentOS/RHEL/Fedora
sudo yum install htop # or dnf install htop
```
Then run:
```bash
htop
```
htop provides a more user-friendly interface with:
- Color-coded memory and CPU usage bars
- Mouse support
- Tree view of processes
- Easy process management
Process Memory Columns in top/htop
- VIRT: Virtual memory size
- RES: Resident memory size (physical memory currently used)
- SHR: Shared memory size
- %MEM: Percentage of RAM used by the process
Examining /proc/meminfo
The `/proc/meminfo` file contains detailed information about memory usage. This virtual file provides the most comprehensive view of system memory.
```bash
cat /proc/meminfo
```
Sample output:
```
MemTotal: 8147928 kB
MemFree: 5678901 kB
MemAvailable: 6543210 kB
Buffers: 234567 kB
Cached: 1000000 kB
SwapCached: 0 kB
Active: 1500000 kB
Inactive: 800000 kB
Active(anon): 600000 kB
Inactive(anon): 100000 kB
Active(file): 900000 kB
Inactive(file): 700000 kB
```
Key /proc/meminfo Fields
- MemTotal: Total usable RAM
- MemFree: Free memory
- MemAvailable: Available memory for new processes
- Buffers: Memory used for file buffers
- Cached: Memory used for page cache
- Active: Recently used memory
- Inactive: Memory that could be reclaimed
Filtering Specific Information
```bash
Show only memory total and free
grep -E 'MemTotal|MemFree|MemAvailable' /proc/meminfo
Show swap information
grep -i swap /proc/meminfo
Show cache information
grep -i cache /proc/meminfo
```
Process-Specific Memory Monitoring
Using ps Command
Check memory usage for specific processes:
```bash
Show memory usage for all processes
ps aux --sort=-%mem | head -20
Show memory usage for specific process
ps -p -o pid,ppid,cmd,%mem,%cpu
Find processes using most memory
ps aux | sort -nrk 4 | head -10
```
Using pmap Command
The `pmap` command shows memory mapping of a process:
```bash
Show memory mapping for process ID
pmap
Show extended format with more details
pmap -x
Show device information
pmap -d
```
Example:
```bash
pmap -x 1234
```
Using smem Tool
Install and use `smem` for advanced memory reporting:
```bash
Install smem
sudo apt install smem # Ubuntu/Debian
Show processes with memory usage
smem
Show memory usage by user
smem -u
Show total memory usage
smem -t
```
Advanced Memory Monitoring Tools
vmstat Command
The `vmstat` command provides virtual memory statistics:
```bash
Show current memory statistics
vmstat
Continuous monitoring (every 2 seconds)
vmstat 2
Show statistics 5 times with 1-second intervals
vmstat 1 5
```
Sample output:
```
procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----
r b swpd free buff cache si so bi bo in cs us sy id wa st
1 0 0 5678901 234567 1000000 0 0 12 8 45 78 2 1 97 0 0
```
Using sar Command
The `sar` command (part of sysstat package) provides system activity reporting:
```bash
Install sysstat if needed
sudo apt install sysstat
Show memory usage
sar -r
Show memory usage with timestamps
sar -r 2 5
Show swap usage
sar -S
```
Graphical Tools
For desktop environments, consider:
- System Monitor (GNOME)
- KSysGuard (KDE)
- htop with mouse support
Interpreting Memory Usage Data
Understanding Available vs Free Memory
In modern Linux systems, the "available" memory is more important than "free" memory:
```bash
free -h
```
- Free: Completely unused memory
- Available: Memory that can be allocated to processes (includes cache that can be freed)
When to Be Concerned
Monitor these indicators:
1. Available memory < 10% of total: System may experience performance issues
2. Swap usage increasing: Indicates RAM pressure
3. High cache usage: Usually normal, but monitor trends
4. Memory leaks: Processes with constantly increasing memory usage
Memory Usage Calculation
```bash
Calculate actual memory usage percentage
free | grep Mem | awk '{printf("Memory Usage: %.2f%\n", ($3/$2) * 100.0)}'
Show available memory percentage
free | grep Mem | awk '{printf("Available Memory: %.2f%\n", ($7/$2) * 100.0)}'
```
Troubleshooting Common Memory Issues
High Memory Usage
1. Identify memory-hungry processes:
```bash
ps aux --sort=-%mem | head -10
```
2. Check for memory leaks:
```bash
Monitor specific process over time
watch -n 5 'ps -p -o pid,ppid,cmd,%mem,%cpu'
```
3. Clear caches if necessary (use with caution):
```bash
Clear page cache
sudo sync && echo 1 | sudo tee /proc/sys/vm/drop_caches
Clear dentries and inodes
sudo sync && echo 2 | sudo tee /proc/sys/vm/drop_caches
Clear page cache, dentries, and inodes
sudo sync && echo 3 | sudo tee /proc/sys/vm/drop_caches
```
Swap Usage Issues
1. Check swap usage:
```bash
swapon --show
cat /proc/swaps
```
2. Monitor swap activity:
```bash
vmstat 1 10
```
3. Adjust swappiness (controls swap usage tendency):
```bash
Check current swappiness
cat /proc/sys/vm/swappiness
Temporarily change swappiness (0-100, lower = less swap usage)
sudo sysctl vm.swappiness=10
Permanently change in /etc/sysctl.conf
echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf
```
Out of Memory (OOM) Issues
1. Check OOM killer logs:
```bash
dmesg | grep -i "killed process"
journalctl | grep -i "out of memory"
```
2. Monitor OOM score:
```bash
Check OOM score for all processes
for proc in /proc/*/oom_score; do
[ -r $proc ] && printf "%d %s\n" "$(cat $proc)" "$(cat ${proc%/*}/comm)"
done | sort -nr | head -10
```
Best Practices for Memory Monitoring
Regular Monitoring
1. Set up automated monitoring:
```bash
Create a simple memory monitoring script
#!/bin/bash
save as memory_check.sh
THRESHOLD=90
USAGE=$(free | grep Mem | awk '{printf("%.0f", ($3/$2) * 100.0)}')
if [ $USAGE -gt $THRESHOLD ]; then
echo "Memory usage is ${USAGE}% - exceeds threshold!"
# Add notification or logging here
fi
```
2. Schedule regular checks:
```bash
Add to crontab for hourly monitoring
crontab -e
Add line: 0 /path/to/memory_check.sh
```
Documentation and Logging
1. Log memory usage trends:
```bash
Create daily memory usage log
echo "$(date): $(free -h | grep Mem)" >> /var/log/memory_usage.log
```
2. Document baseline memory usage for your systems
3. Set up alerts for critical memory thresholds
Performance Optimization
1. Regularly review memory-intensive processes
2. Optimize application configurations to reduce memory usage
3. Consider adding more RAM if consistently high usage
4. Implement proper swap configuration based on workload
Conclusion
Monitoring memory usage in Linux is essential for maintaining system performance and stability. From simple commands like `free` and `top` to advanced tools like `htop`, `vmstat`, and `/proc/meminfo`, Linux provides numerous ways to track memory consumption.
Key takeaways:
- Use `free -h` for quick memory overview
- Monitor with `htop` or `top` for real-time process-level information
- Examine `/proc/meminfo` for detailed memory statistics
- Focus on "available" memory rather than just "free" memory
- Set up automated monitoring for proactive system management
- Understand the difference between normal cache usage and memory pressure
Regular memory monitoring helps prevent performance issues, identifies resource bottlenecks, and ensures optimal system operation. By combining these tools and techniques, you can effectively manage and troubleshoot memory usage on any Linux system.
Remember that some memory usage for caching is beneficial and normal in Linux systems. The key is understanding your baseline usage patterns and recognizing when memory consumption becomes problematic for your specific workload and requirements.