How to Monitor and Optimize Memory Usage on Ubuntu: Complete Guide for Beginners and Intermediate Users

1. Introduction

Ubuntu is widely supported by users as a lightweight and feature-rich Linux distribution. However, after long periods of use, the system may become slow. One of the causes is increased memory usage. This is especially noticeable in environments where multiple processes run simultaneously, such as development tasks or data processing. Understanding and properly managing memory usage is essential.

This article explains how to check memory usage on Ubuntu, manage it efficiently, and troubleshoot related issues. It covers everything from beginner to intermediate-level techniques, so feel free to use it as your reference.

Why Memory Management Matters in Ubuntu

Memory is a vital resource that directly affects system performance. If memory becomes insufficient, applications may slow down or crash. Furthermore, excessive swap usage increases read/write operations on the disk, resulting in a noticeable decline in overall performance. Therefore, monitoring memory usage helps ensure efficient system operation.

Purpose of This Article

This article covers the following:

  • Basic commands for checking memory usage
  • How to view detailed memory usage across the system and per process
  • Ways to optimize and use memory efficiently
  • Tools for troubleshooting and long-term monitoring

By understanding these concepts, you can maintain a smoother Ubuntu working environment.

2. How to Check Memory Usage: Basic Commands

Ubuntu provides several built-in commands for checking memory usage. In this section, we will explain how to use these basic commands in a clear and beginner-friendly way.

free Command

The free command is a fundamental tool to check overall system memory usage.

Example:

free -m

Main Options:

  • -m: Display memory usage in megabytes
  • -g: Display memory usage in gigabytes
  • -h: Human-readable format (auto-adjust MB/GB)

Example Output:

              total        used        free      shared  buff/cache   available
Mem:           7989        2340         987         432        4661        5016
Swap:          2048          12        2036

How to Read the Output:

  • total: Total system memory
  • used: Currently used memory
  • free: Unused memory
  • buff/cache: Memory used for buffers and cache
  • available: Memory available for applications

This simple and intuitive command is the first method you should try.

top Command

The top command displays real-time memory usage per process.

Example:

top

Sample Output:

PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND
  1 root      20   0  225672   8956   5924 S   0.0  0.1   0:01.23 systemd
1234 user      20   0  135256  12320   8940 S   0.3  0.2   0:00.15 gnome-terminal

Key Indicators:

  • PID: Process ID
  • %MEM: Memory usage percentage
  • COMMAND: Running process name

htop Command

htop is an enhanced version of top with a more visual and user-friendly interface.

Installation:

sudo apt update
sudo apt install htop

Usage:

htop

Features:

  • Color-coded memory visualization
  • Selectable processes using arrow keys
  • Simple filtering and sorting

vmstat Command

The vmstat command monitors system resources in real time.

Example:

vmstat 5

Explanation:

  • 5: Update every 5 seconds

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     12  98736  43256 467321    0    0     3     5   55   99  2  0 97  0  0

Key Items:

  • free: Free memory
  • buff: Buffer memory
  • cache: Cached memory
  • si/so: Swap in/out values

ps Command

The ps command displays detailed information about specific processes.

Example:

ps aux --sort=-%mem

This shows processes sorted by memory usage in descending order.

3. Detailed Memory Usage Analysis

Ubuntu offers methods to obtain deeper insights into memory usage beyond basic commands. This section explains tools for analyzing per-process memory usage, useful for system administrators and advanced users.

pmap Command

The pmap command displays memory mapping details for a process.

Example:

pmap <ProcessID>

Sample Output:

5600:   /usr/bin/python3
000055e45d7a2000   4K r-- /usr/bin/python3.8
000055e45d7a3000 124K r-x /usr/bin/python3.8
...

Reading the Output:

  • The left column shows memory address ranges.
  • The right column shows usage details such as shared libraries.

Checking /proc/[PID]/smaps

The /proc/[PID]/smaps file stores detailed memory usage for each process. This is useful for advanced troubleshooting, including memory leak detection.

Example:

cat /proc/<ProcessID>/smaps

Main Metrics:

  • Size: Total allocated memory
  • Rss: Actual memory in RAM
  • Pss: Shared memory split between processes

Checking /proc/meminfo

This virtual file contains system-wide memory statistics, including swap and cache usage.

Example:

cat /proc/meminfo

Analyzing History with sar

The sar command records and analyzes resource usage history.

sudo apt install sysstat
sar -r

It lets you identify when memory-related problems occurred.

4. How to Optimize Memory Usage

To maintain a comfortable working environment on Ubuntu, it’s important to manage and optimize memory usage effectively.

Stopping Unnecessary Processes

Unneeded processes may consume memory. Identify and stop them as follows:

  1. Check processes using top or htop
  • Locate high-memory processes.
  1. Stop a specific process
sudo kill <ProcessID>
sudo kill -9 <ProcessID>
  1. Disable unnecessary services
sudo systemctl disable <ServiceName>

5. Long-Term Memory Monitoring and Automation

Regularly monitoring memory usage and understanding usage trends is essential for maintaining system performance. This section explains how to monitor and automate memory tracking over extended periods on Ubuntu.

Using Monitoring Tools

Glances

Glances is a lightweight, comprehensive monitoring tool that displays real-time information about system resources, making it suitable for long-term memory monitoring.

Installation:

sudo apt update
sudo apt install glances

Usage:

glances

Features:

  • Displays memory, CPU, disk, and network usage at a glance
  • Supports a web interface for remote monitoring

Nagios

Nagios is a powerful infrastructure monitoring tool that can monitor memory usage along with other resources and notify you when issues occur.

Installation Notes:
Refer to the official documentation for detailed installation steps.

Main Features:

  • Alert system for abnormal memory usage
  • Customizable configurations for monitoring various resources

Automating Memory Monitoring with Scripts

Monitoring Using a Bash Script

You can use a simple Bash script to record memory usage at regular intervals.

Sample Script:

#!/bin/bash
# Memory usage logging script

LOG_FILE="/var/log/memory_usage.log"
DATE=$(date "+%Y-%m-%d %H:%M:%S")
MEM_INFO=$(free -m)

echo "[$DATE]" >> $LOG_FILE
echo "$MEM_INFO" >> $LOG_FILE
echo "------------------------" >> $LOG_FILE

How to Configure:

  1. Save the script as memory_monitor.sh
  2. Grant execute permission
chmod +x memory_monitor.sh
  1. Set up periodic execution with crontab
crontab -e

Add the following line to run it every 5 minutes:

*/5 * * * * /path/to/memory_monitor.sh

Checking Logs and Analyzing Trends

Review the stored log file to analyze memory consumption patterns. This allows you to identify recurring spikes or performance degradation at specific times.

Automating Alert Notifications

If memory usage exceeds a defined threshold, you can configure automated notifications to quickly address issues.

Example: Email Notification Script

#!/bin/bash
# Memory monitoring and alert script

THRESHOLD=90
USED_MEMORY=$(free | awk '/^Mem:/ {printf "%.0f", $3/$2 * 100}')

if [ $USED_MEMORY -gt $THRESHOLD ]; then
  echo "Memory usage has reached $USED_MEMORY%!" | mail -s "Memory Alert" user@example.com
fi

Setup:

  1. Save the script and grant execute permission
  2. Schedule execution using crontab

Long-Term Data Storage and Visualization

By integrating with powerful monitoring tools, you can graphically visualize memory metrics over time.

  • Prometheus: Collects time-series memory usage data
  • Grafana: Connects to Prometheus to visualize memory metrics with real-time dashboards

Using these tools, you can automate long-term memory tracking and identify trends efficiently.

6. FAQ (Frequently Asked Questions)

This section answers common questions regarding memory management on Ubuntu, providing practical solutions for daily operations.

Q1: What should I check first if memory usage seems high?

A1:
Use the following commands to examine memory usage at the system and process levels:

  • free -m: Check overall memory usage
  • top or htop: Identify processes consuming high memory

Then stop unnecessary processes or clear caches if needed.

Q2: Is increased swap usage a problem?

A2:
Not always, but frequent swap usage indicates insufficient physical memory. To address this:

  1. Check swap usage with free -m
  2. Consider increasing physical RAM or expanding swap space
  3. Stop memory-heavy or unnecessary processes

Q3: Are there ways to detect memory leaks?

A3:
Yes. Use these tools:

  • valgrind: Detects memory leaks in applications
  • /proc/<PID>/smaps: Shows detailed per-process memory usage

Q4: How can I monitor memory usage over long periods?

A4:
Use any of the following:

  • Monitoring tools: Glances or Nagios
  • Logging scripts: Periodically store results from free or vmstat

Q5: Can I automatically detect high memory usage and receive alerts?

A5:
Yes. Use a script to detect high usage and send email notifications.

#!/bin/bash
THRESHOLD=80
MEMORY_USAGE=$(free | awk '/^Mem:/ {printf "%.0f", $3/$2 * 100}')

if [ $MEMORY_USAGE -gt $THRESHOLD ]; then
  echo "Memory usage has reached $MEMORY_USAGE%!" | mail -s "Memory Alert" user@example.com
fi

Q6: Does clearing cache have risks?

A6:
Clearing cache may temporarily reduce performance, as cache helps speed up access to frequently used data. Clear it only when memory is low:

sudo sync; echo 3 | sudo tee /proc/sys/vm/drop_caches

Q7: What should I do if applications crash due to memory issues?

A7:

  1. Identify and stop high-memory processes
  2. Increase physical memory if required
  3. Review application resource configurations

Q8: Can I reset memory usage entirely?

A8:
There is no direct “reset,” but you can:

  1. Stop unused processes and services
  2. Clear cache
  3. Restart the system if necessary

7. Conclusion

This article provided a comprehensive overview of memory management in Ubuntu—from basic monitoring to detailed analysis, optimization methods, and long-term automation. Below is a summary of key points:

Summary of Key Concepts

  • Use free, top, and htop to check memory usage
  • Analyze details with vmstat, pmap, and /proc/[PID]/smaps
  • Stop unnecessary processes, manage swap, and clear caches when needed
  • Use tools like Glances, Nagios, Prometheus, and Grafana for automated monitoring

The Importance of Memory Management

Proper memory management ensures stable performance and prevents system slowdowns, especially when:

  • The system feels slow
  • Swap usage increases frequently
  • Certain applications consume excessive memory

Next Steps

Apply what you learned:

  • Use basic commands regularly to review memory usage
  • Introduce monitoring tools if you manage multiple servers
  • Automate tasks using scripts to improve efficiency

Final Thoughts

With the right knowledge and monitoring strategy, you can significantly improve productivity and system stability in your Ubuntu environment. Use this guide as your reference to keep your system running smoothly.