How to check memory usage with free

How to Check Memory Usage with Free The `free` command is one of the most essential tools for monitoring system memory usage on Linux and Unix-like operating systems. Whether you're a system administrator troubleshooting performance issues, a developer optimizing applications, or a Linux enthusiast learning system management, understanding how to effectively use the `free` command is crucial for maintaining healthy system performance. This comprehensive guide will walk you through everything you need to know about the `free` command, from basic usage to advanced monitoring techniques, helping you master memory management on your Linux systems. Table of Contents 1. [Introduction to Memory Management](#introduction-to-memory-management) 2. [Prerequisites](#prerequisites) 3. [Understanding the Free Command](#understanding-the-free-command) 4. [Basic Free Command Syntax](#basic-free-command-syntax) 5. [Interpreting Free Command Output](#interpreting-free-command-output) 6. [Free Command Options and Parameters](#free-command-options-and-parameters) 7. [Practical Examples and Use Cases](#practical-examples-and-use-cases) 8. [Advanced Memory Monitoring](#advanced-memory-monitoring) 9. [Common Issues and Troubleshooting](#common-issues-and-troubleshooting) 10. [Best Practices and Professional Tips](#best-practices-and-professional-tips) 11. [Integration with Other Tools](#integration-with-other-tools) 12. [Conclusion](#conclusion) Introduction to Memory Management Memory management is a critical aspect of system administration and performance optimization. Understanding how your system utilizes RAM helps you make informed decisions about resource allocation, application deployment, and system tuning. The `free` command provides a quick snapshot of your system's memory usage, displaying information about physical RAM, swap space, and various memory categories. Modern Linux systems employ sophisticated memory management techniques, including caching, buffering, and virtual memory. The `free` command helps you understand these mechanisms and their impact on system performance. Prerequisites Before diving into the `free` command, ensure you have: - Operating System: Linux or Unix-like system (Ubuntu, CentOS, Debian, RHEL, etc.) - Access Level: Basic user access (no root privileges required for viewing memory information) - Terminal Access: Command-line interface or SSH access to the target system - Basic Knowledge: Fundamental understanding of Linux command-line operations System Requirements The `free` command is typically pre-installed on most Linux distributions as part of the `procps` or `procps-ng` package. To verify installation: ```bash which free ``` If not installed, you can install it using your distribution's package manager: ```bash Ubuntu/Debian sudo apt-get install procps CentOS/RHEL/Fedora sudo yum install procps-ng or sudo dnf install procps-ng ``` Understanding the Free Command The `free` command reads memory information from the `/proc/meminfo` file and presents it in a user-friendly format. It displays information about: - Physical RAM: Total, used, and available memory - Swap Space: Virtual memory stored on disk - Buffers: Memory used for I/O operations - Cache: Memory used for caching frequently accessed data - Shared Memory: Memory shared between processes Understanding these categories is essential for accurate memory analysis and system optimization. Basic Free Command Syntax The basic syntax of the `free` command is: ```bash free [options] ``` Simple Usage Examples ```bash Display memory information in default format free Display memory in human-readable format free -h Display memory in megabytes free -m Display memory in gigabytes free -g ``` Interpreting Free Command Output Let's examine a typical `free` command output: ```bash $ free -h total used free shared buff/cache available Mem: 7.7G 2.1G 3.2G 256M 2.4G 5.1G Swap: 2.0G 0B 2.0G ``` Understanding Each Column Memory Row (Mem:) - total: Total installed physical RAM - used: Memory currently used by processes - free: Completely unused memory - shared: Memory used by shared libraries and tmpfs - buff/cache: Memory used for buffers and cache - available: Estimation of memory available for starting new applications Swap Row (Swap:) - total: Total swap space available - used: Currently used swap space - free: Available swap space Key Concepts Explained Available vs. Free Memory: The "available" column is more important than "free" because it includes memory that can be reclaimed from buffers and cache when needed by applications. Buffer/Cache Memory: This memory appears "used" but is actually available for applications when needed. Linux aggressively caches data to improve performance. Free Command Options and Parameters Display Format Options ```bash Human-readable format (KB, MB, GB) free -h Display in bytes free -b Display in kilobytes (default) free -k Display in megabytes free -m Display in gigabytes free -g Display in terabytes free --tera ``` Continuous Monitoring ```bash Update every 2 seconds (default) free -s 2 Update every 5 seconds free -s 5 Display 10 iterations with 3-second intervals free -s 3 -c 10 ``` Additional Options ```bash Show totals for RAM and swap free -t Wide mode (useful for large numbers) free -w Show low and high memory statistics (older kernels) free -l Combine multiple options free -h -s 2 -c 5 ``` Practical Examples and Use Cases Example 1: Basic Memory Check ```bash $ free -h total used free shared buff/cache available Mem: 16G 4.2G 8.1G 512M 3.7G 11G Swap: 4.0G 0B 4.0G ``` Analysis: This system has 16GB RAM with 11GB available for new applications. No swap is being used, indicating healthy memory usage. Example 2: Continuous Monitoring During Load ```bash $ free -h -s 1 -c 10 ``` This command displays memory usage every second for 10 iterations, useful for monitoring memory consumption during application startup or heavy workloads. Example 3: Detailed Memory Analysis ```bash $ free -h -w -t total used free shared buffers cache available Mem: 32G 8.2G 18G 1.2G 256M 5.5G 22G Swap: 8.0G 0B 8.0G Total: 40G 8.2G 26G ``` The `-w` option separates buffers and cache into distinct columns, providing more detailed information. Example 4: Scripting with Free ```bash #!/bin/bash Memory monitoring script THRESHOLD=80 USED_PERCENT=$(free | grep Mem | awk '{printf "%.0f", ($3/$2) * 100}') if [ $USED_PERCENT -gt $THRESHOLD ]; then echo "Warning: Memory usage is ${USED_PERCENT}%" free -h else echo "Memory usage is normal: ${USED_PERCENT}%" fi ``` Example 5: Memory Usage Alert System ```bash #!/bin/bash Advanced memory monitoring with email alerts EMAIL="admin@example.com" MEMORY_THRESHOLD=90 SWAP_THRESHOLD=50 Get memory usage percentage MEM_USAGE=$(free | awk 'NR==2{printf "%.2f", $3*100/$2}') SWAP_USAGE=$(free | awk 'NR==3{if($2>0) printf "%.2f", $3*100/$2; else print "0"}') Check thresholds and send alerts if (( $(echo "$MEM_USAGE > $MEMORY_THRESHOLD" | bc -l) )); then echo "High memory usage: ${MEM_USAGE}%" | mail -s "Memory Alert" $EMAIL fi if (( $(echo "$SWAP_USAGE > $SWAP_THRESHOLD" | bc -l) )); then echo "High swap usage: ${SWAP_USAGE}%" | mail -s "Swap Alert" $EMAIL fi ``` Advanced Memory Monitoring Combining Free with Other Commands Memory Usage by Process ```bash Top memory-consuming processes ps aux --sort=-%mem | head -10 Memory usage with free summary echo "=== Memory Summary ===" && free -h && echo -e "\n=== Top Processes ===" && ps aux --sort=-%mem | head -5 ``` Historical Memory Tracking ```bash Log memory usage to file while true; do echo "$(date): $(free -h | grep Mem)" >> /var/log/memory.log sleep 300 # Log every 5 minutes done ``` Creating Memory Reports ```bash #!/bin/bash Comprehensive memory report echo "=== System Memory Report ===" echo "Generated: $(date)" echo "" echo "=== Current Memory Status ===" free -h -t echo "" echo "=== Memory Usage Percentage ===" free | awk 'NR==2{printf "Memory Usage: %.2f%%\n", $3*100/$2}' free | awk 'NR==3{if($2>0) printf "Swap Usage: %.2f%%\n", $3*100/$2}' echo "" echo "=== Top Memory Consumers ===" ps aux --sort=-%mem | head -10 | awk '{print $11, $4"%"}' echo "" echo "=== System Load ===" uptime ``` Common Issues and Troubleshooting Issue 1: High Memory Usage Symptoms: Available memory is consistently low, system performance is sluggish. Diagnosis: ```bash Check current memory status free -h Identify memory-hungry processes ps aux --sort=-%mem | head -10 Check for memory leaks cat /proc/meminfo | grep -E "(MemTotal|MemFree|MemAvailable|Buffers|Cached)" ``` Solutions: - Restart memory-intensive applications - Clear system caches: `sudo sync && sudo echo 3 > /proc/sys/vm/drop_caches` - Increase swap space if necessary - Optimize application memory usage Issue 2: Swap Usage Issues Symptoms: High swap usage, system slowdown. Diagnosis: ```bash Check swap usage free -h swapon --show Monitor swap activity vmstat 1 5 ``` Solutions: - Identify processes using swap: `sudo cat /proc/*/status | grep VmSwap | sort -k2 -n` - Adjust swappiness: `sudo sysctl vm.swappiness=10` - Add more physical RAM - Optimize memory-intensive applications Issue 3: Inaccurate Memory Readings Symptoms: Memory usage doesn't match expectations. Diagnosis: ```bash Compare different memory tools free -h cat /proc/meminfo htop ``` Solutions: - Understand the difference between used and available memory - Consider buffer/cache as available memory - Use multiple tools for comprehensive analysis Issue 4: Free Command Not Available Symptoms: Command not found error. Solutions: ```bash Install procps package sudo apt-get install procps # Ubuntu/Debian sudo yum install procps-ng # CentOS/RHEL Alternative memory checking methods cat /proc/meminfo vmstat ``` Best Practices and Professional Tips Memory Monitoring Best Practices 1. Regular Monitoring: Establish baseline memory usage patterns 2. Automated Alerts: Set up notifications for memory thresholds 3. Documentation: Keep records of memory usage trends 4. Proactive Management: Address memory issues before they impact performance Professional Tips Tip 1: Understanding Available Memory ```bash The "available" column is your friend free -h | awk 'NR==2{print "Available Memory: " $7}' ``` Tip 2: Memory Usage Percentage Calculation ```bash Quick memory usage percentage free | awk 'NR==2{printf "Memory Usage: %.2f%%\n", ($2-$7)*100/$2}' ``` Tip 3: Monitoring Memory Trends ```bash Create a simple memory trend monitor watch -n 5 'date; free -h; echo "---"' ``` Tip 4: Memory Optimization Commands ```bash Clear page cache, dentries, and inodes sudo sync && sudo sysctl vm.drop_caches=3 Reset drop_caches sudo sysctl vm.drop_caches=0 ``` Performance Optimization Guidelines 1. Monitor Regularly: Use `free` in scripts and monitoring systems 2. Set Appropriate Thresholds: Typically 80-85% for memory usage alerts 3. Understand Your Workload: Different applications have different memory patterns 4. Plan for Growth: Monitor trends to predict future memory requirements Integration with Other Tools Combining Free with System Monitoring With htop ```bash Terminal 1: Continuous free output watch -n 2 free -h Terminal 2: Process monitoring htop ``` With vmstat ```bash Comprehensive memory and system statistics vmstat 2 5 && free -h ``` With sar (System Activity Reporter) ```bash Memory usage over time sar -r 1 10 Compare with free output free -h ``` Integration in Monitoring Systems Nagios Plugin Example ```bash #!/bin/bash Nagios memory check plugin WARNING=80 CRITICAL=90 MEMORY_USAGE=$(free | awk 'NR==2{printf "%.0f", ($2-$7)*100/$2}') if [ $MEMORY_USAGE -ge $CRITICAL ]; then echo "CRITICAL - Memory usage: ${MEMORY_USAGE}%" exit 2 elif [ $MEMORY_USAGE -ge $WARNING ]; then echo "WARNING - Memory usage: ${MEMORY_USAGE}%" exit 1 else echo "OK - Memory usage: ${MEMORY_USAGE}%" exit 0 fi ``` Zabbix Integration ```bash Custom Zabbix user parameter UserParameter=memory.usage,free | awk 'NR==2{printf "%.2f", ($2-$7)*100/$2}' UserParameter=memory.available,free -b | awk 'NR==2{print $7}' ``` Advanced Use Cases Memory Capacity Planning ```bash #!/bin/bash Memory capacity planning script echo "=== Memory Capacity Analysis ===" TOTAL_MEM=$(free -b | awk 'NR==2{print $2}') USED_MEM=$(free -b | awk 'NR==2{print $3}') AVAILABLE_MEM=$(free -b | awk 'NR==2{print $7}') echo "Total Memory: $(($TOTAL_MEM / 1024 / 1024 / 1024))GB" echo "Used Memory: $(($USED_MEM / 1024 / 1024 / 1024))GB" echo "Available Memory: $(($AVAILABLE_MEM / 1024 / 1024 / 1024))GB" USAGE_PERCENT=$((($TOTAL_MEM - $AVAILABLE_MEM) * 100 / $TOTAL_MEM)) echo "Memory Usage: ${USAGE_PERCENT}%" if [ $USAGE_PERCENT -gt 75 ]; then echo "Recommendation: Consider memory upgrade" elif [ $USAGE_PERCENT -lt 25 ]; then echo "Recommendation: Memory usage is low, current capacity is sufficient" else echo "Recommendation: Memory usage is normal" fi ``` Container Memory Monitoring ```bash Monitor memory in containerized environments docker stats --format "table {{.Container}}\t{{.MemUsage}}\t{{.MemPerc}}" Host system memory free -h ``` Troubleshooting Common Scenarios Scenario 1: Application Performance Issues Investigation Steps: 1. Check overall memory usage: `free -h` 2. Identify memory-hungry processes: `ps aux --sort=-%mem | head -10` 3. Monitor memory usage over time: `free -s 1 -c 60` 4. Check for memory leaks: Monitor specific process memory usage Scenario 2: System Slowdown Investigation Steps: 1. Check swap usage: `free -h | grep Swap` 2. Monitor I/O wait: `vmstat 1 5` 3. Verify available memory: `free -h | awk 'NR==2{print $7}'` 4. Check system load: `uptime` Scenario 3: Out of Memory Errors Investigation Steps: 1. Check kernel messages: `dmesg | grep -i "out of memory"` 2. Review memory limits: `ulimit -v` 3. Analyze memory usage patterns: `free -h -s 1` 4. Check for memory overcommitment: `cat /proc/sys/vm/overcommit_memory` Security Considerations Access Control - The `free` command doesn't require special privileges - Memory information is generally safe to expose - Consider restricting access to detailed process information Monitoring Security ```bash Check for suspicious memory usage patterns ps aux --sort=-%mem | head -5 | awk '{if($4>50) print "High memory process:", $11, $4"%"}' ``` Conclusion The `free` command is an indispensable tool for Linux system administrators, developers, and power users. Mastering its usage enables you to effectively monitor system memory, diagnose performance issues, and optimize resource utilization. Key takeaways from this comprehensive guide: 1. Understanding Output: The "available" memory column is more important than "free" memory for determining system capacity 2. Regular Monitoring: Implement continuous monitoring to establish baselines and detect anomalies 3. Integration: Combine `free` with other tools for comprehensive system analysis 4. Automation: Use scripting to automate memory monitoring and alerting 5. Troubleshooting: Follow systematic approaches to diagnose and resolve memory-related issues Next Steps To further enhance your memory monitoring capabilities: 1. Explore Advanced Tools: Learn about `htop`, `vmstat`, and `sar` for more detailed analysis 2. Implement Monitoring: Set up automated memory monitoring in your environment 3. Study Memory Management: Deepen your understanding of Linux memory management concepts 4. Practice Optimization: Experiment with memory optimization techniques in test environments 5. Stay Updated: Keep up with new memory monitoring tools and techniques By following the practices and techniques outlined in this guide, you'll be well-equipped to maintain optimal system performance through effective memory monitoring and management. Remember that memory monitoring is not a one-time task but an ongoing process that requires regular attention and analysis. The `free` command, while simple in appearance, provides powerful insights into your system's memory utilization. Combined with the knowledge and techniques presented in this guide, you now have the tools necessary to become proficient in Linux memory management and system optimization.