๐ System Monitoring with Glances in AlmaLinux: Real-Time Dashboard
Ever wished you had X-ray vision for your server? ๐ Like, seeing EVERYTHING thatโs happening in real-time? Thatโs exactly what Glances gives you! I discovered Glances after struggling with multiple terminal windows running top, iotop, netstat, and df simultaneously. It was chaos! Then someone showed me Glances - one tool that displays EVERYTHING in a gorgeous, color-coded dashboard. Today Iโm teaching you how to monitor your AlmaLinux system like a pro with Glances. No more blind spots! ๐
๐ค Why Glances is a Game-Changer
Forget juggling multiple monitoring tools! Hereโs why Glances rocks:
- ๐ฏ All-in-One View - CPU, RAM, disk, network in one screen
- ๐ Color-Coded Alerts - Green = good, red = panic!
- ๐ฑ Web Interface - Monitor from anywhere
- ๐ Plugin System - Docker, sensors, GPU monitoring
- ๐ Export Data - Send to InfluxDB, Prometheus, CSV
- โก Lightweight - Uses minimal resources
I once caught a memory leak in production just by glancing at Glances (pun intended)! Saved the day! ๐ช
๐ฏ What You Need
Before we fire up this monitoring beast, check you have:
- โ AlmaLinux system running
- โ Root or sudo access
- โ Python 3 installed
- โ 10 minutes to revolutionize your monitoring
- โ Coffee (monitoring is serious business! โ)
๐ Step 1: Installing Glances
Letโs get Glances up and running!
Install via Package Manager
# Enable EPEL repository
sudo dnf install -y epel-release
# Install Glances
sudo dnf install -y glances
# Verify installation
glances --version
# Install additional dependencies
sudo dnf install -y python3-psutil python3-bottle
Install via pip (Latest Version)
# Install pip if needed
sudo dnf install -y python3-pip
# Install latest Glances
sudo pip3 install glances
# Install optional dependencies
sudo pip3 install bottle netifaces pysnmp zeroconf influxdb
# For Docker monitoring
sudo pip3 install docker
# For GPU monitoring (NVIDIA)
sudo pip3 install pynvml
Install from Source (Bleeding Edge)
# Clone repository
git clone https://github.com/nicolargo/glances.git
cd glances
# Install
sudo python3 setup.py install
# Or use development mode
sudo python3 setup.py develop
๐ง Step 2: Basic Glances Usage
Time to see your system like never before!
Launch Glances
# Basic launch
glances
# With 1-second refresh
glances -t 1
# Disable some sections
glances --disable-network --disable-disk
# Minimal mode
glances -1 # One line per CPU
# Full mode
glances -4 # Full stats
# Process view sorted by CPU
glances --sort-processes cpu_percent
# Process view sorted by memory
glances --sort-processes memory_percent
Understanding the Interface
# Color codes:
# GREEN = OK (< 50% usage)
# BLUE = CAREFUL (50-70% usage)
# VIOLET = WARNING (70-90% usage)
# RED = CRITICAL (> 90% usage)
# Keyboard shortcuts:
# h = Help
# q = Quit
# 1 = Global CPU
# 2 = Per-CPU
# 3 = CPU stats disable
# d = Disk I/O
# f = File system
# n = Network
# s = Sensors
# l = Show/hide logs
# w = Delete warning logs
# x = Delete warning and critical logs
# z = Show/hide processes
# / = Search process
# a = Auto sort processes
# c = Sort by CPU
# m = Sort by MEM
# p = Sort by name
# i = Sort by I/O
# t = Sort by TIME
# u = Show/hide cumulative network
Configuration File
# Generate default config
glances --export-graph
# Edit config
nano ~/.config/glances/glances.conf
# Example configuration:
[global]
refresh=2
check_update=false
[cpu]
disable=False
steal_critical=10
[memory]
disable=False
careful=50
warning=70
critical=90
[network]
disable=False
rx_careful=70
rx_warning=80
rx_critical=90
[diskio]
disable=False
[processlist]
disable=False
cpu_careful=50
cpu_warning=70
cpu_critical=90
[alert]
disable=False
duration=5
๐ Step 3: Advanced Monitoring Features
Letโs unlock Glancesโ full potential!
Web Server Mode
# Start web server
glances -w
# Custom port
glances -w --port 8080
# Bind to specific IP
glances -w --bind 192.168.1.100
# With authentication
glances -w --username admin --password
# Access from browser:
# http://localhost:61208
# http://server-ip:61208
# Secure with reverse proxy (nginx)
sudo nano /etc/nginx/conf.d/glances.conf
server {
listen 443 ssl;
server_name monitor.example.com;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
location / {
proxy_pass http://127.0.0.1:61208;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
Client/Server Mode
# On server:
glances -s
# Glances server started on 0.0.0.0:61209
# On client:
glances -c server-ip
glances -c 192.168.1.100
# With password
glances -s --password
glances -c server-ip --password
# Monitor multiple servers
glances --browser
Export to Time Series Database
# Export to InfluxDB
glances --export influxdb
# Configure InfluxDB export
nano ~/.config/glances/glances.conf
[influxdb]
host=localhost
port=8086
user=glances
password=secret
db=glances
prefix=server1
tags=datacenter:dc1,environment:prod
# Export to Prometheus
glances --export prometheus
# Export to CSV
glances --export csv --export-csv-file /var/log/glances.csv
# Export to JSON
glances --export json --export-json-file /var/log/glances.json
โ Step 4: Custom Monitoring Scripts
Create powerful monitoring automation!
System Health Monitor
#!/bin/bash
# Automated system health monitoring with Glances
THRESHOLD_CPU=80
THRESHOLD_MEM=90
THRESHOLD_DISK=85
ALERT_EMAIL="[email protected]"
check_system_health() {
echo "๐ฅ System Health Check - $(date)"
echo "================================"
# Get Glances data in JSON
glances_data=$(glances --stdout cpu,mem,diskio,network --time 1 --quiet)
# Parse CPU usage
cpu_usage=$(glances --stdout cpu --time 1 --quiet | grep -oP '"total":\K[0-9.]+')
echo "CPU Usage: ${cpu_usage}%"
if (( $(echo "$cpu_usage > $THRESHOLD_CPU" | bc -l) )); then
echo "โ ๏ธ HIGH CPU USAGE: ${cpu_usage}%"
echo "Top CPU processes:"
glances --stdout processlist --time 1 --quiet | \
jq -r '.[] | select(.cpu_percent > 10) | "\(.name): \(.cpu_percent)%"'
# Send alert
echo "CPU Alert: ${cpu_usage}% usage on $(hostname)" | \
mail -s "โ ๏ธ High CPU Alert" "$ALERT_EMAIL"
fi
# Check memory
mem_usage=$(glances --stdout mem --time 1 --quiet | grep -oP '"percent":\K[0-9.]+')
echo "Memory Usage: ${mem_usage}%"
if (( $(echo "$mem_usage > $THRESHOLD_MEM" | bc -l) )); then
echo "โ ๏ธ HIGH MEMORY USAGE: ${mem_usage}%"
echo "Top memory processes:"
glances --stdout processlist --time 1 --quiet | \
jq -r '.[] | select(.memory_percent > 5) | "\(.name): \(.memory_percent)%"'
fi
# Check disk
disk_usage=$(df -h / | awk 'NR==2 {print $5}' | sed 's/%//')
echo "Disk Usage: ${disk_usage}%"
if [ "$disk_usage" -gt "$THRESHOLD_DISK" ]; then
echo "โ ๏ธ HIGH DISK USAGE: ${disk_usage}%"
du -sh /* 2>/dev/null | sort -rh | head -5
fi
echo "================================"
echo "โ
Health check complete"
}
# Run check
check_system_health
# Add to cron for regular checks
# */5 * * * * /usr/local/bin/health-check.sh
Performance Logger
#!/bin/bash
# Log performance metrics over time
LOG_DIR="/var/log/glances-metrics"
mkdir -p "$LOG_DIR"
log_performance() {
timestamp=$(date +%Y%m%d-%H%M%S)
log_file="$LOG_DIR/metrics-$timestamp.json"
echo "๐ Logging performance metrics to $log_file"
# Capture 60 seconds of data
glances --export json \
--export-json-file "$log_file" \
--time 1 \
--stop-after 60 \
--quiet
# Analyze the data
echo "๐ Analysis:"
# Average CPU
avg_cpu=$(jq -r '[.[] | .cpu.total] | add/length' "$log_file")
echo " Average CPU: ${avg_cpu}%"
# Peak memory
peak_mem=$(jq -r '[.[] | .mem.percent] | max' "$log_file")
echo " Peak Memory: ${peak_mem}%"
# Network traffic
total_rx=$(jq -r '[.[] | .network[0].rx // 0] | add' "$log_file")
total_tx=$(jq -r '[.[] | .network[0].tx // 0] | add' "$log_file")
echo " Network RX: $((total_rx / 1024 / 1024)) MB"
echo " Network TX: $((total_tx / 1024 / 1024)) MB"
# Compress old logs
find "$LOG_DIR" -name "*.json" -mtime +7 -exec gzip {} \;
# Delete very old logs
find "$LOG_DIR" -name "*.gz" -mtime +30 -delete
}
log_performance
Container Monitoring
#!/bin/bash
# Monitor Docker containers with Glances
monitor_containers() {
echo "๐ณ Docker Container Monitor"
echo "==========================="
# Check if Docker plugin is available
if ! glances --stdout docker --time 1 2>/dev/null; then
echo "Docker plugin not available. Installing..."
sudo pip3 install docker
fi
# Get container stats
glances --stdout docker --time 5 --quiet | \
jq -r '.[] | "Container: \(.name)
Status: \(.status)
CPU: \(.cpu.total)%
Memory: \(.memory.usage_percent)%
Network RX: \(.io.network_rx) bytes
Network TX: \(.io.network_tx) bytes
---"'
# Alert on unhealthy containers
unhealthy=$(docker ps --filter health=unhealthy -q | wc -l)
if [ "$unhealthy" -gt 0 ]; then
echo "โ ๏ธ WARNING: $unhealthy unhealthy containers detected!"
docker ps --filter health=unhealthy
fi
# Check container resource limits
echo -e "\n๐ Container Resource Usage:"
docker stats --no-stream --format "table {{.Container}}\t{{.CPUPerc}}\t{{.MemPerc}}\t{{.NetIO}}"
}
monitor_containers
๐ฎ Quick Examples
Example 1: Custom Alert System ๐จ
#!/bin/bash
# Real-time alert system using Glances
setup_alerts() {
cat > /usr/local/bin/glances-alerts.py << 'EOF'
#!/usr/bin/env python3
import json
import subprocess
import time
import smtplib
from email.mime.text import MIMEText
def get_glances_data():
"""Get current system stats from Glances"""
cmd = ["glances", "--stdout", "cpu,mem,disk,network", "--time", "1", "--quiet"]
result = subprocess.run(cmd, capture_output=True, text=True)
return json.loads(result.stdout) if result.stdout else {}
def check_thresholds(data):
"""Check if any metrics exceed thresholds"""
alerts = []
# CPU check
if data.get('cpu', {}).get('total', 0) > 80:
alerts.append(f"CPU usage critical: {data['cpu']['total']}%")
# Memory check
if data.get('mem', {}).get('percent', 0) > 90:
alerts.append(f"Memory usage critical: {data['mem']['percent']}%")
# Disk check
for disk in data.get('fs', []):
if disk.get('percent', 0) > 85:
alerts.append(f"Disk {disk['mnt_point']} critical: {disk['percent']}%")
return alerts
def send_alerts(alerts):
"""Send email alerts"""
if not alerts:
return
message = "System Alert!\n\n" + "\n".join(alerts)
print(f"๐จ {message}")
# Send email (configure SMTP settings)
# msg = MIMEText(message)
# msg['Subject'] = 'System Alert'
# msg['From'] = '[email protected]'
# msg['To'] = '[email protected]'
# smtp = smtplib.SMTP('localhost')
# smtp.send_message(msg)
# smtp.quit()
def monitor_loop():
"""Main monitoring loop"""
print("๐ Glances Alert Monitor Started")
while True:
try:
data = get_glances_data()
alerts = check_thresholds(data)
if alerts:
send_alerts(alerts)
time.sleep(300) # Wait 5 minutes before next alert
else:
print("โ
All systems normal")
time.sleep(10) # Check every 10 seconds
except KeyboardInterrupt:
print("\n๐ Monitor stopped")
break
except Exception as e:
print(f"โ Error: {e}")
time.sleep(30)
if __name__ == "__main__":
monitor_loop()
EOF
chmod +x /usr/local/bin/glances-alerts.py
echo "โ
Alert system installed: /usr/local/bin/glances-alerts.py"
}
setup_alerts
Example 2: Web Dashboard Generator ๐
#!/bin/bash
# Generate custom HTML dashboard from Glances data
generate_dashboard() {
cat > /var/www/html/monitor.html << 'EOF'
<!DOCTYPE html>
<html>
<head>
<title>System Monitor</title>
<meta http-equiv="refresh" content="5">
<style>
body {
font-family: 'Segoe UI', Arial;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 20px;
}
.container { max-width: 1200px; margin: 0 auto; }
.metric {
background: rgba(255,255,255,0.1);
border-radius: 10px;
padding: 20px;
margin: 10px;
display: inline-block;
min-width: 200px;
}
.value { font-size: 48px; font-weight: bold; }
.label { font-size: 14px; opacity: 0.8; }
.chart { width: 100%; height: 200px; margin-top: 20px; }
.critical { color: #ff6b6b; }
.warning { color: #ffd93d; }
.good { color: #6bcf7f; }
</style>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<div class="container">
<h1>๐ฅ๏ธ System Monitor - $(hostname)</h1>
<p>Last Update: $(date)</p>
<div id="metrics">
EOF
# Get Glances data
cpu=$(glances --stdout cpu --time 1 --quiet | jq -r '.total // 0')
mem=$(glances --stdout mem --time 1 --quiet | jq -r '.percent // 0')
swap=$(glances --stdout memswap --time 1 --quiet | jq -r '.percent // 0')
# Determine colors based on values
cpu_class="good"
[ $(echo "$cpu > 70" | bc) -eq 1 ] && cpu_class="warning"
[ $(echo "$cpu > 90" | bc) -eq 1 ] && cpu_class="critical"
mem_class="good"
[ $(echo "$mem > 70" | bc) -eq 1 ] && mem_class="warning"
[ $(echo "$mem > 90" | bc) -eq 1 ] && mem_class="critical"
cat >> /var/www/html/monitor.html << EOF
<div class="metric">
<div class="label">CPU Usage</div>
<div class="value $cpu_class">${cpu}%</div>
</div>
<div class="metric">
<div class="label">Memory Usage</div>
<div class="value $mem_class">${mem}%</div>
</div>
<div class="metric">
<div class="label">Swap Usage</div>
<div class="value">${swap}%</div>
</div>
EOF
# Add process list
echo '<h2>Top Processes</h2><table border="1" style="width:100%">' >> /var/www/html/monitor.html
echo '<tr><th>Process</th><th>CPU%</th><th>MEM%</th></tr>' >> /var/www/html/monitor.html
glances --stdout processlist --time 1 --quiet | \
jq -r '.[] | select(.cpu_percent > 1) |
"<tr><td>\(.name)</td><td>\(.cpu_percent)%</td><td>\(.memory_percent)%</td></tr>"' | \
head -10 >> /var/www/html/monitor.html
echo '</table></div></body></html>' >> /var/www/html/monitor.html
echo "โ
Dashboard updated: http://$(hostname)/monitor.html"
}
# Run every minute via cron
generate_dashboard
Example 3: Capacity Planning Report ๐
#!/bin/bash
# Generate capacity planning reports from Glances data
capacity_report() {
REPORT_FILE="/var/log/capacity-report-$(date +%Y%m).txt"
echo "๐ CAPACITY PLANNING REPORT" | tee "$REPORT_FILE"
echo "Generated: $(date)" | tee -a "$REPORT_FILE"
echo "========================================" | tee -a "$REPORT_FILE"
# Collect data for 1 hour
echo "Collecting 1 hour of metrics..." | tee -a "$REPORT_FILE"
glances --export csv \
--export-csv-file /tmp/glances-capacity.csv \
--time 60 \
--stop-after 60 \
--quiet
# Analyze the data
echo -e "\n๐ RESOURCE UTILIZATION SUMMARY" | tee -a "$REPORT_FILE"
echo "----------------------------------------" | tee -a "$REPORT_FILE"
# CPU Analysis
avg_cpu=$(awk -F',' '{sum+=$2; count++} END {print sum/count}' /tmp/glances-capacity.csv)
peak_cpu=$(awk -F',' '{if($2>max) max=$2} END {print max}' /tmp/glances-capacity.csv)
echo "CPU:" | tee -a "$REPORT_FILE"
echo " Average: ${avg_cpu}%" | tee -a "$REPORT_FILE"
echo " Peak: ${peak_cpu}%" | tee -a "$REPORT_FILE"
# Memory trends
echo -e "\nMemory:" | tee -a "$REPORT_FILE"
free -h | tee -a "$REPORT_FILE"
# Disk growth projection
echo -e "\n๐ DISK USAGE TRENDS" | tee -a "$REPORT_FILE"
echo "----------------------------------------" | tee -a "$REPORT_FILE"
for mount in $(df -h | grep -v tmpfs | grep -v Filesystem | awk '{print $6}'); do
usage=$(df -h "$mount" | tail -1 | awk '{print $5}' | sed 's/%//')
size=$(df -h "$mount" | tail -1 | awk '{print $2}')
avail=$(df -h "$mount" | tail -1 | awk '{print $4}')
echo "Mount: $mount" | tee -a "$REPORT_FILE"
echo " Current usage: ${usage}%" | tee -a "$REPORT_FILE"
echo " Total size: $size" | tee -a "$REPORT_FILE"
echo " Available: $avail" | tee -a "$REPORT_FILE"
# Simple projection (naive)
if [ "$usage" -gt 50 ]; then
days_until_full=$((100 - usage))
echo " โ ๏ธ Estimated days until full: ~$days_until_full" | tee -a "$REPORT_FILE"
fi
done
# Recommendations
echo -e "\n๐ก RECOMMENDATIONS" | tee -a "$REPORT_FILE"
echo "----------------------------------------" | tee -a "$REPORT_FILE"
if (( $(echo "$avg_cpu > 70" | bc -l) )); then
echo "โ ๏ธ CPU: Consider scaling up CPU resources" | tee -a "$REPORT_FILE"
fi
if (( $(echo "$mem_usage > 80" | bc -l) )); then
echo "โ ๏ธ Memory: Consider adding more RAM" | tee -a "$REPORT_FILE"
fi
echo -e "\nโ
Report saved to: $REPORT_FILE"
}
capacity_report
๐จ Fix Common Problems
Problem 1: Glances Wonโt Start โ
Getting errors on launch?
# Check Python version
python3 --version
# Reinstall dependencies
sudo pip3 install --upgrade psutil
# Check for conflicts
pip3 list | grep glances
# Run in debug mode
glances --debug
# Try standalone mode
glances --disable-plugin all
Problem 2: Web Interface Not Accessible โ
Canโt connect to web interface?
# Check if running
ps aux | grep glances
# Check port
sudo ss -tulpn | grep 61208
# Firewall rules
sudo firewall-cmd --add-port=61208/tcp --permanent
sudo firewall-cmd --reload
# Try different binding
glances -w --bind 0.0.0.0
# Check logs
glances -w --debug
Problem 3: High CPU Usage from Glances โ
Glances using too many resources?
# Increase refresh interval
glances -t 5 # 5 seconds instead of default 3
# Disable heavy plugins
glances --disable-docker --disable-sensors
# Use standalone mode
glances --standalone
# Limit process list
glances --process-short-name
Problem 4: Export Not Working โ
Canโt export to database?
# Test InfluxDB connection
curl -i http://localhost:8086/ping
# Check export config
glances --export influxdb --debug
# Verify credentials
influx -username glances -password secret
# Try CSV export first
glances --export csv --export-csv-file test.csv
๐ Simple Commands Summary
Task | Command |
---|---|
๐ Start Glances | glances |
๐ Web mode | glances -w |
๐ก Client mode | glances -c server-ip |
๐ฅ๏ธ Server mode | glances -s |
๐ Export CSV | glances --export csv |
๐ Process search | / then type name |
๐ Sort by CPU | c |
๐พ Sort by memory | m |
โ Help | h |
๐ก Tips for Success
- Start Simple ๐ฏ - Learn keyboard shortcuts first
- Use Web Mode ๐ - Great for remote monitoring
- Set Thresholds ๐จ - Customize color alerts
- Export Data ๐ - Build historical trends
- Automate Alerts ๐ค - Donโt watch manually
- Document Normal ๐ - Know your baseline
Pro tip: I always run Glances in tmux so I can detach and reattach anytime. Also set up the web interface behind nginx with basic auth for security! ๐
๐ What You Learned
Youโre now a monitoring master! You can:
- โ Install and configure Glances
- โ Monitor system resources in real-time
- โ Set up web-based monitoring
- โ Export metrics to databases
- โ Create custom alerts
- โ Build monitoring dashboards
- โ Automate performance reporting
๐ฏ Why This Matters
Real-time monitoring gives you:
- ๐ Complete system visibility
- ๐จ Early problem detection
- ๐ Performance insights
- ๐ฐ Cost optimization data
- ๐ Troubleshooting power
- ๐ด Peace of mind
Last week, Glances helped me spot a runaway process eating 300% CPU at 2 AM. The alert woke me up, I fixed it in 2 minutes from my phone. Without Glances, that process wouldโve crashed the server by morning! ๐ฆธโโ๏ธ
Remember: You canโt fix what you canโt see. Glances gives you superhuman vision into your system. Use it wisely! ๐๏ธ
Happy monitoring! May your metrics be green and your alerts be few! ๐โจ