Understanding Linux Memory
Linux uses available RAM for caching. "Used" memory isn't always bad. Check:
free -h
free -h -w # Shows cache separately
Output example:
total used free shared buff/cache available
Mem: 3.9G 1.2G 200M 50M 2.5G 2.4G
Available is the real free memory. If cache is high but available is low, you have a problem.
Find Memory-Hungry Processes
ps aux --sort=-%mem | head -10
sudo apt install smem -y
sudo smem -r -k -t
Common High RAM Culprits
1. MySQL/MariaDB
mysql -e "SHOW VARIABLES LIKE 'innodb_buffer_pool_size';"
Reduce to 60-70% of total RAM:
sudo nano /etc/mysql/my.cnf
# innodb_buffer_pool_size = 1G (for 2GB VPS)
2. PHP-FPM
ps --no-headers -o "rss,cmd" -C php-fpm | awk '{ sum+=$1 } END { printf "%d%s
", sum/NR/1024, "MB" }'
sudo nano /etc/php/*/fpm/pool.d/www.conf
# pm.max_children = (Total RAM - 1GB) / Process Memory per child
3. Apache (Prefork MPM)
sudo a2dismod mpm_prefork
sudo a2enmod mpm_event
sudo systemctl restart apache2
4. Node.js Applications
node --max-old-space-size=512 app.js
5. Memory Leaks
watch -n 5 "ps aux --sort=-%mem | head -5"
sudo systemctl restart leaky-service
Free Up Memory Without Reboot
sudo sync && echo 1 > /proc/sys/vm/drop_caches
sudo sync && echo 2 > /proc/sys/vm/drop_caches
sudo sync && echo 3 > /proc/sys/vm/drop_caches
echo f > /proc/sysrq-trigger
💡 Swap usage indicates memory pressure. Add swap if needed.