Monitor PHP-FPM Memory Usage and Website Status with a Simple Bash Script

Create script file
sudo nano /usr/local/bin/log_php_fpm_status.sh
Paste the following:
#!/bin/bash

LOG_FILE="/var/log/php-fpm-monitor.log"
timestamp=$(date '+%Y-%m-%d %H:%M:%S')

# Get systemctl status output
status=$(systemctl status php8.2-fpm)

# Get memory info
mem_total=$(grep MemTotal /proc/meminfo | awk '{print $2}')
mem_avail=$(grep MemAvailable /proc/meminfo | awk '{print $2}')
buffers=$(grep Buffers /proc/meminfo | awk '{print $2}')
cached=$(grep ^Cached /proc/meminfo | awk '{print $2}')

# Convert to MB
mem_total_mb=$(awk "BEGIN {printf \"%.1f\", $mem_total/1024}")
mem_avail_mb=$(awk "BEGIN {printf \"%.1f\", $mem_avail/1024}")
buffers_mb=$(awk "BEGIN {printf \"%.1f\", $buffers/1024}")
cached_mb=$(awk "BEGIN {printf \"%.1f\", $cached/1024}")
php_fpm_mb=$(echo "$status" | grep -i 'Memory:' | awk '{print $2}')
system_used_mb=$(awk "BEGIN {printf \"%.1f\", ($mem_total - $mem_avail - $buffers - $cached)/1024}")
buffers_cache_mb=$(awk "BEGIN {printf \"%.1f\", $buffers_mb + $cached_mb}")

# Get systemctl php-fpm status
status=$(systemctl status php8.2-fpm)

# Extract FPM info
requests=$(echo "$status" | grep -oP 'Requests:\s*\K\d+')
active=$(echo "$status" | grep -oP 'Processes active:\s*\K\d+')
idle=$(echo "$status" | grep -oP 'idle:\s*\K\d+')
traffic=$(echo "$status" | grep -oP 'Traffic:\s*\K[^,"]+')

# Check endpoint with curl
http_code=$(curl -s -o /dev/null -w "%{http_code}" https://tegneprogrammet-v3.bomann.no/admin/login)

if [ "$http_code" == "502" ]; then
    site_status="Bad Gateway (502)"
elif [ "$http_code" == "000" ]; then
    site_status="Connection Failed"
else
    site_status="HTTP $http_code"
fi

# Final log entry
echo "$timestamp | Tot-Mem: ${mem_total_mb}MB | P-FPM Used: ${php_fpm_mb} | Available: ${mem_avail_mb}MB | Active: $active | Idle: $idle | Rqst: $requests | Trfc: $traffic | Site: $site_status" >> "$LOG_FILE"

Make it executable:
sudo chmod +x /usr/local/bin/log_php_fpm_status.sh
Schedule the Script to Run Every Minute
sudo crontab -e

Edit : 
* * * * * /usr/local/bin/log_php_fpm_status.sh
Run the command to see output:
tail -f /var/log/php-fpm-monitor.log
My output:

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top