This article provides a comprehensive guide on how to monitor your Linux server's resources using the top, htop, df, and du commands, as well as the free command for memory usage. These tools are essential for system administrators to keep track of CPU, RAM, and disk space utilization.

Monitoring CPU and Memory with top

The top command is a standard utility in Linux that provides real-time information about the running processes and system resource usage. It displays details such as CPU usage, memory usage, swap usage, and process activity.

  1. Open your terminal and type top, then press Enter to start monitoring.
  2. To sort processes by CPU usage, press P.
  3. To sort processes by memory usage, press M.
  4. To kill a process, find its Process ID (PID) and type k, then enter the PID followed by Enter.
  5. Press q to quit top.

Enhanced Monitoring with htop

htop is an interactive process viewer that provides a more user-friendly interface compared to top. It includes features like full-color support, mouse interaction, and the ability to scroll through processes.

Installing htop

To install htop, use your package manager. For Debian-based systems (like Ubuntu), use:

sudo apt-get update
sudo apt-get install htop

For Red Hat-based systems (like CentOS), use:

sudo yum install epel-release
sudo yum install htop

Using htop

  1. Open your terminal and type htop, then press Enter.
  2. To kill a process, use the arrow keys to select it and press F9.
  3. To sort processes by CPU or memory usage, use the arrow keys to navigate to the desired column header and press Enter.
  4. Press F10 to quit htop.

Monitoring Disk Usage with df and du

The df command reports file system disk space usage, while the du command estimates file space usage.

Using df

  1. To view disk usage in a human-readable format, type df -h.
  2. This will display the total size, used space, available space, and use percentage for each mounted file system.

Using du

  1. To check the disk usage of a specific directory, type du -sh /path/to/directory.
  2. The -s option summarizes the total size, and the -h option makes it human-readable.

Monitoring Memory Usage with free

The free command displays system memory usage, including physical and swap memory.

  1. To view memory usage in a human-readable format, type free -h.
  2. This will show the total, used, and free memory along with buffers/cache information.

Troubleshooting

  • top or htop not installed: Ensure you have installed the necessary packages as described in the installation sections.
  • No permissions to kill a process: You may need superuser privileges. Try using sudo top or sudo htop.
  • df shows unexpected disk usage: Check for large files or directories that might be consuming space. Use du -sh /path/to/directory to investigate.

By regularly monitoring your server's resources with these tools, you can ensure optimal performance and quickly address any issues that arise.