WordPress Server Optimization on Oracle Linux 8: Historical Configuration and Diagnostics

WordPress Server Diagnostics โ€” Oracle Linux 8 ยท Configuration case conceptual editorial illustration

In our previous post, [WordPress on OCI with Cloudflare: Configuration Examples and Prerequisites], we explored integrating Cloudflare’s CDN services. This article examines the recorded WordPress configuration on Oracle Linux 8 and the checks needed before applying its examples.

For intermittent failures or slow responses, correlate web server, PHP-FPM, database and application observations by time. The examples require validation in your environment; no particular setting or script guarantees recovery or a performance gain.

The 2025 label and versions in this article identify its historical example environment, not the current production stack or latest recommended releases. Check WordPress requirements, PHP support status and package compatibility before applying it. No present-day performance or runtime validation is implied.

Record incident times, request rates, latency and resource usage before changing settings. A baseline helps identify the bottleneck and compare results under a similar workload.

System Architecture for WordPress Server Optimization

1. Layered Architecture from Optimization Perspective

WordPress Server Optimization Architecture
WordPress Server Optimization Architecture

This diagram is a conceptual view of the server layers. Investigate their dependencies and measured bottlenecks rather than assuming each layer needs tuning.

2. Actual Server Architecture Configuration

WordPress Server Architecture on Oracle Linux
WordPress Server Architecture on Oracle Linux

This diagram illustrates the configuration described in the article. It is not a verified inventory of the current deployment or every request path.

Performance Optimization Metrics by System Component

The article records the following example environment:

Base Environment:

  • Operating System: Oracle Linux 8
  • Web Server: Apache (httpd)
  • PHP Version: 8.2.25
  • MySQL Version: MySQL Enterprise – Cloud v9.1.1
  • WordPress Version: 6.7.1

Hardware Resources:

  • Total Physical Memory (RAM): 11GB
  • Used Memory at the Recorded Snapshot: 1GB
  • Buffer/Cache Memory Usage: 7GB
  • Available Memory: 9GB
  • Swap Memory: 7GB (unused)

Limits of this snapshot:

  • Available memory at one instant does not establish headroom under peak load
  • Buffer/cache allocation alone does not demonstrate I/O performance; measure I/O separately
  • Unused swap at that instant does not rule out memory pressure at other times

Analysis of Settings Affecting WordPress Server Optimization

Current PHP and WordPress Settings:

  • PHP Memory Limit: 256M
  • WordPress Memory Limit: 40M
  • WordPress Maximum Memory Limit: 256M
  • PHP Maximum Input Variables: 1000
  • PHP Maximum POST Size: 64M

Checks Suggested by the Recorded Settings:

  • PHP and WordPress Memory-Limit Checks:
    • Compare the configured limits with the effective limit for actual web requests
    • System Memory: 11GB
    • WordPress Memory Limit: 40M. Its ratio to 11GB RAM is not actual memory utilization.
  • Effective PHP Limit for Web Requests:
    • PHP Memory Limit: 256M
    • WordPress Memory Limit: 40M. WordPress does not lower an existing higher PHP limit; check the effective request limit and memory-exhaustion errors rather than inferring a bottleneck from the constants.

PHP Configuration Limitations

Compare failing save or upload requests with the following input limits:

  1. Input Variable Count:
    • Current setting: max_input_vars = 1000
    • max_input_vars limits GET, POST and COOKIE input variables; inspect the transport format and actual variable count
    • Exceeding the limit can truncate form variables. It does not explain every JSON-based save failure
  2. Total POST Size:
    • Current setting: post_max_size = 64M
    • post_max_size limits the complete POST body. Also check upload_max_filesize, multipart overhead and web-server or proxy request-size limits

Server Configuration for WordPress Performance Tuning

Apache concurrency, PHP-FPM workers and database queues share finite resources. Review the total budget before raising a limit, then compare individual changes under a controlled workload.

Configuration File Backup

Identify the active configuration and included files before making a protected copy. The script below copies selected paths; it does not provide complete backup coverage or prove that restoration works. Check copy failures, ownership, access controls and the recovery procedure separately.

backup_configs.sh
#!/bin/bash
# backup_configs.sh

# Create backup directory
BACKUP_DIR="$(date +%Y%m%d_%H%M%S)"
BACKUP_DIR="/root/config_backups/${BACKUP_DIR}"
mkdir -p $BACKUP_DIR

# Backup Apache configuration
cp -r /etc/httpd $BACKUP_DIR/
echo "Apache configuration backup completed"

# Backup PHP configuration
cp /etc/php.ini $BACKUP_DIR/
cp -r /etc/php.d $BACKUP_DIR/
cp -r /etc/php-fpm.d $BACKUP_DIR/
echo "PHP configuration backup completed"

# Backup WordPress configuration
cp /var/www/html/wordpress/wp-config.php $BACKUP_DIR/
echo "WordPress configuration backup completed"
  

Apache Web Server Performance Tuning

For Apache, measure request throughput, queueing and connection behavior before deciding where tuning is needed.

1. MPM Module Selection and Configuration

Common Unix MPMs in Apache 2.4 include event, worker and prefork. Verify the installed package, loaded MPM and PHP execution model. The event settings below are examples, not recommendations for every deployment:

00-mpm.confExample ยท verify your environment
# Example values only; measure capacity before applying.
# /etc/httpd/conf.modules.d/00-mpm.conf

# Event MPM (recommended)
<IfModule mpm_event_module>
  StartServers 3
  MinSpareThreads 25
  MaxSpareThreads 75
  ThreadLimit 64
  ThreadsPerChild 25
  MaxRequestWorkers 400
  MaxConnectionsPerChild 0
</IfModule>
  

Prerequisites: The Apache/PHP values illustrate the Oracle Linux 8, Apache 2.4 and PHP 8.2.25 environment in this article; they are not universal recommendations. Measure PHP-FPM process RSS/PSS, latency and queueing under peak workload. Budget memory for the OS, Apache, database, caches and a safety margin before sizing concurrency. Review MaxRequestWorkers, ThreadsPerChild and ServerLimit together with FPM pm.max_children. memory_limit multiplied by process count is not actual reserved memory. A PHP php_admin_value[memory_limit] ceiling cannot be raised by WordPress WP_MAX_MEMORY_LIMIT. Back up the configuration, pass configuration checks and limited load tests, and restore it if memory pressure or latency worsens.

Each setting’s purpose and impact:

  • StartServers: Initial child-process count; evaluate with the selected MPM and workload
  • ThreadsPerChild: Threads per child; review ThreadLimit and total concurrency
  • MaxRequestWorkers: Limit on simultaneous requests; check its MPM-specific meaning and ServerLimit/ThreadsPerChild relationship

2. WordPress Virtual Host Configuration

/etc/httpd/conf.d/wordpress.conf
# /etc/httpd/conf.d/wordpress.conf

<VirtualHost *:80>
  ServerName yourdomain.com
  ServerAlias www.yourdomain.com
  DocumentRoot /var/www/html/wordpress

  # Logging configuration
  LogLevel warn
  ErrorLog logs/yourdomain.com-error.log
  CustomLog logs/yourdomain.com-access.log combined

  # HTTPS redirect
  RewriteEngine On
  RewriteCond %{HTTPS} off
  RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</VirtualHost>

<VirtualHost *:443>
  ServerName yourdomain.com
  ServerAlias www.yourdomain.com
  DocumentRoot /var/www/html/wordpress

  # SSL Configuration
  SSLEngine on
  SSLCertificateFile /etc/letsencrypt/live/yourdomain.com/fullchain.pem
  SSLCertificateKeyFile /etc/letsencrypt/live/yourdomain.com/privkey.pem

  # Enhanced SSL Security
  SSLProtocol all -SSLv3 -TLSv1 -TLSv1.1
  SSLCipherSuite ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256
  SSLHonorCipherOrder off

  # WordPress Directory Settings
  <Directory /var/www/html/wordpress>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride All
    Require all granted

    # Performance Optimization
    EnableSendfile On
    FileETag None
  </Directory>
</VirtualHost>
  

PHP-FPM Optimization for WordPress Performance

For PHP-FPM, measure per-process memory, execution time and queueing together. Raising configuration values alone does not establish a performance improvement.

1. Basic PHP Configuration

/etc/php.ini
# /etc/php.ini
; Memory Settings
memory_limit = 512M
max_execution_time = 300
max_input_time = 300
max_input_vars = 3000

; File Upload Settings
upload_max_filesize = 128M
post_max_size = 128M
max_file_uploads = 50

; Session Settings
session.gc_maxlifetime = 1440
session.gc_probability = 1
session.gc_divisor = 100

; Error Handling (Production Environment)
error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT
display_errors = Off
log_errors = On
error_log = /var/log/php_errors.log
  

2. PHP-FPM Configuration

www.confExample ยท verify your environment
; Example capacity only; measure peak memory and concurrency first.
# /etc/php-fpm.d/www.conf

[www]
; Process Management
pm = dynamic
pm.max_children = 50
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 35
pm.max_requests = 500

; Resource Limits
php_admin_value[memory_limit] = 512M
php_admin_value[max_execution_time] = 300

; Logging Configuration
php_admin_flag[log_errors] = on
php_admin_value[error_log] = /var/log/php-fpm/www-error.log
  

WordPress Configuration Optimization

Distinguish request-memory limits from constants that affect cache or scheduling. WP_CACHE alone does not activate a cache, and WP_MEMORY_LIMIT is not an allocation of the serverโ€™s total RAM.

Prerequisites: First configure system cron or a managed scheduler to invoke this siteโ€™s wp-cron.php regularly. Verify the actual installation path, site URL, execution account and PHP environment, then confirm scheduled publishing and plugin jobs run through that scheduler. Only then uncomment the line below. Keep visitor-triggered WP-Cron until validation succeeds. If the replacement fails, remove the constant or set it to false and check overdue jobs.

wp-config.phpExample ยท verify your environment
# /var/www/html/wordpress/wp-config.php

// Memory Settings
define('WP_MEMORY_LIMIT', '512M');
define('WP_MAX_MEMORY_LIMIT', '1024M');

// Performance Optimization
// Enable only after configuring and validating the replacement scheduler
// define('DISABLE_WP_CRON', true);
define('WP_CACHE', true);
define('EMPTY_TRASH_DAYS', 7);
define('WP_POST_REVISIONS', 5);

// Debugging Settings (Production)
define('WP_DEBUG', false);
define('WP_DEBUG_LOG', false);
define('WP_DEBUG_DISPLAY', false);
  

Configuration Changes and Service Restart

Prepare backups, configuration checks and a recovery procedure before changing settings. The example restarts PHP-FPM and Apache and can interrupt requests. Syntax checks and an active service state do not prove that WordPress works correctly. Verify real requests and errors afterward, and evaluate supported reload/graceful behavior for the actual deployment.

WordPress Service Restart Script

service_restart.sh
#!/bin/bash

# ================================
# Service Restart Script
# ================================

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

# Log file
LOG_FILE="/var/log/service_restart_$(date +%Y%m%d).log"
exec 1> >(tee -a "$LOG_FILE") 2>&1

# Services to restart
SERVICES=("php-fpm" "httpd")

# Prevent concurrent execution
LOCK_FILE="/tmp/service_restart.lock"
exec 200>$LOCK_FILE
flock -n 200 || { echo -e "${RED}Another instance is already running.${NC}"; exit 1; }

echo "$(date '+%Y-%m-%d %H:%M:%S') : Starting service restart process"

# Syntax check
echo -e "${YELLOW}Checking configuration syntax...${NC}"
if ! httpd -t; then
    echo -e "${RED}Apache configuration syntax error!${NC}"
    exit 1
fi

if ! php-fpm -t; then
    echo -e "${RED}PHP-FPM configuration syntax error!${NC}"
    exit 1
fi

# Restart services
for SERVICE in "${SERVICES[@]}"; do
    echo -e "${YELLOW}Restarting ${SERVICE}...${NC}"
    if systemctl restart "$SERVICE"; then
        if systemctl is-active --quiet "$SERVICE"; then
            echo -e "${GREEN}${SERVICE} restarted successfully${NC}"
        else
            echo -e "${RED}${SERVICE} is not active after restart!${NC}"
            exit 1
        fi
    else
        echo -e "${RED}Failed to restart ${SERVICE}${NC}"
        exit 1
    fi
    sleep 2
done

# Check logs
echo -e "${YELLOW}Recent error logs:${NC}"
echo "---- Apache Error Log ----"
tail -n 10 /var/log/httpd/error_log || echo "No Apache error log found."
echo "---- PHP-FPM Error Log ----"
tail -n 10 /var/log/php-fpm/error.log || echo "No PHP-FPM error log found."

echo "$(date '+%Y-%m-%d %H:%M:%S') : Service restart completed"
  

Configuration Implementation Order

1. Apache Configuration Changes:

Apache Config Update
# Modify configurations
sudo vi /etc/httpd/conf/httpd.conf
sudo vi /etc/httpd/conf.d/wordpress.conf

# Verify configuration
sudo httpd -t
  

2. PHP Configuration Changes:

PHP Config Update
# Modify PHP settings
sudo vi /etc/php.ini
sudo vi /etc/php-fpm.d/www.conf

# Verify configuration
sudo php-fpm -t
  

3. WordPress Configuration Changes:

wp-config.php Update
# Modify wp-config.php
sudo vi /var/www/html/wordpress/wp-config.php
  

4. Service Restart:

Execute Restart Script
sudo ./restart_services.sh
  

Enhancing WordPress Security with SELinux

SELinux controls access. Do not reduce its protections as a performance fix. The example grants writes across wp-content and enables network access with a broad boolean; assess the minimum required write directories and destinations before use. It does not validate the current server policy.

WordPress SELinux Context Configuration
# WordPress directory context configuration
sudo semanage fcontext -a -t httpd_sys_content_t "/var/www/html/wordpress(/.*)?"
sudo semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/html/wordpress/wp-content(/.*)?"
sudo restorecon -Rv /var/www/html/wordpress

# Additional SELinux settings
sudo setsebool -P httpd_can_network_connect on
sudo setsebool -P httpd_can_network_connect_db on
sudo setsebool -P httpd_unified on

# SELinux status verification
sestatus
getsebool -a | grep httpd
  

WordPress Server Monitoring and Maintenance

Implementing Effective System Monitoring

Record resource usage and service behavior together when operating WordPress. The examples below illustrate collection ideas; their parsing, thresholds and execution flow require validation rather than being treated as field-proven monitoring.

Real-time Resource Monitoring Configuration

monitor_system_resources.sh
#!/bin/bash
# monitor_system_resources.sh

# Color definitions
GREEN='\033[0;32m]'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

# Memory monitoring function
monitor_memory() {
  free -m | awk '
  NR==2{
    used=$3
    total=$2
    pct=used*100/total
    printf "Memory Usage: %d/%dMB (%.1f%%)\n", used, total, pct
    if (pct > 90) {
      exit 1
    } else if (pct > 80) {
      exit 2
    }
  }'
  return $?
}

# CPU monitoring function
monitor_cpu() {
  cpu_usage=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d. -f1)
  echo "CPU Usage: ${cpu_usage}%"

  if [ $cpu_usage -gt 90 ]; then
    return 1
  elif [ $cpu_usage -gt 80 ]; then
    return 2
  else
    return 0
  fi
}

# Disk monitoring function
monitor_disk() {
  disk_usage=$(df -h / | awk 'NR==2{print $5}' | cut -d% -f1)
  echo "Disk Usage: ${disk_usage}%"

  if [ $disk_usage -gt 90 ]; then
    return 1
  elif [ $disk_usage -gt 80 ]; then
    return 2
  else
    return 0
  fi
}
  

Key Performance Indicators (KPI) Setup and Tracking

grep-based process counts can include grep itself or unrelated matches. curl time_total measures the complete HTTP transfer, not browser page-load time. memory_get_usage in CLI PHP does not measure a web request or all FPM workers. Verify targets, authentication and the actual metric collection method separately.

monitor_wordpress_kpi.sh
#!/bin/bash
# monitor_wordpress_kpi.sh

# WordPress process monitoring
monitor_wordpress_processes() {
  echo "=== WordPress Process Status ==="

  # PHP-FPM process status
  php_proc=$(ps aux | grep php-fpm | wc -l)
  echo "PHP-FPM Process Count: ${php_proc}"

  # Apache process status
  apache_proc=$(ps aux | grep httpd | wc -l)
  echo "Apache Process Count: ${apache_proc}"

  # MySQL connection status
  mysql_conn=$(mysqladmin status | awk '{print $4}')
  echo "MySQL Active Connections: ${mysql_conn}"
}

# Performance metrics collection
collect_performance_metrics() {
  echo "=== Performance Metrics ==="

  # Page load time check
  curl -w "Page Load Time: %{time_total}s\n" -o /dev/null -s your-domain.com

  # PHP memory usage
  memory_usage=$(php -r "echo memory_get_usage(true);")
  echo "PHP Memory Usage: $((memory_usage/1024/1024))MB"
}
  

Monitoring Dashboard Implementation

This example saves a private HTML report of system readings. It does not implement continuous collection or an authenticated web dashboard.

Prerequisites: This example creates a private HTML operations report instead of a public web dashboard. Prepare PRIVATE_REPORT_DIR as an operator-owned directory with mode 0700, outside every DocumentRoot, Alias and publicly served static path. Generated files use mode 0600; view them locally or through an access-controlled operations channel only. Raw error logs are omitted. A public dashboard requires a separate design for authentication, access control, redaction and output escaping.

dashboard_generator.shExample ยท verify your environment
#!/bin/bash
# dashboard_generator.sh โ€” private report only
html_escape() {
    sed -e 's/&/\&amp;/g' -e 's/</\&lt;/g' -e 's/>/\&gt;/g'
}
generate_dashboard() (
    set -euo pipefail
    umask 077
    : "${PRIVATE_REPORT_DIR:?Set a verified private directory outside all web roots}"
    test -d "$PRIVATE_REPORT_DIR"
    REPORT_FILE=$(mktemp --suffix=.html "$PRIVATE_REPORT_DIR/status.XXXXXXXX")
    {
        printf '%s\n' '<!doctype html><html><head><meta charset="utf-8"><title>Private server status</title></head><body><h1>Private server status</h1><pre>'
        LC_ALL=C uptime | html_escape
        LC_ALL=C free -m | html_escape
        printf '%s\n' '</pre></body></html>'
    } > "$REPORT_FILE"
    printf 'Private report: %s\n' "$REPORT_FILE"
)

Core Log Analysis and Management

Efficient server log management and analysis are crucial for troubleshooting and performance optimization.

Critical Log File Locations and Usage

Log Path Configuration
# Log path configuration
LOG_PATHS=(
    "/var/log/httpd/error_log" # Apache error log
    "/var/log/httpd/access_log" # Apache access log
    "/var/log/php-fpm/error.log" # PHP-FPM error log
    "/var/log/php-fpm/www-slow.log" # PHP slow script log
    "/var/www/html/wordpress/wp-content/debug.log" # WordPress debug log
)
  

Log Rotation and Retention Policy

/etc/logrotate.d/wordpress
# /etc/logrotate.d/wordpress
/var/log/httpd/*log {
    daily
    rotate 14
    compress
    delaycompress
    missingok
    notifempty
    create 640 apache apache
    sharedscripts
    postrotate
        /bin/systemctl reload httpd.service > /dev/null 2>/dev/null || true
    endscript
}
  

Automated Log Analysis Script

analyze_logs.sh
#!/bin/bash
# analyze_logs.sh

# Error pattern definitions
ERROR_PATTERNS=(
    "PHP Fatal error"
    "ERROR"
    "failed"
    "Connection refused"
    "Permission denied"
)

# Log analysis function
analyze_logs() {
    local log_file=$1
    echo "=== Analysis: $log_file ==="

    for pattern in "${ERROR_PATTERNS[@]}"; do
        count=$(grep -c "$pattern" "$log_file")
        if [ $count -gt 0 ]; then
            echo "$pattern: $count occurrences"
            grep "$pattern" "$log_file" | tail -n 3
        fi
    done
}
  

Systematic Maintenance Process

Daily/Weekly/Monthly Checkpoints

maintenance_checklist.sh
#!/bin/bash
# maintenance_checklist.sh

# Daily checks
daily_check() {
    # Service status verification
    for service in httpd php-fpm mysqld; do
        systemctl status $service
    done

    # Disk space check
    df -h
    du -sh /var/log/*
}

# Weekly checks
weekly_check() {
    # Database optimization
    mysql -e "OPTIMIZE TABLE wp_posts, wp_postmeta, wp_options;"

    # Old log cleanup
    find /var/log/httpd/ -name "*.log" -mtime +30 -delete
}

# Monthly checks
monthly_check() {
    # Complete database analysis
    mysqlcheck -A --analyze

    # System update check
    yum check-update
}
  

Database Optimization Schedule

Prerequisites: Do not reset binary-log/GTID history during routine maintenance. RESET MASTER deletes that history in MySQL 8.0 and was removed in 8.4, so it also does not match the articleโ€™s 9.1.1 context. Do not substitute another RESET statement. Design log retention separately around replication, PITR and validated backups. Confirm the actual database, table prefix and storage engine first. REPAIR TABLE applies to MyISAM/ARCHIVE/CSV, not InnoDB recovery. Evaluate backup, locking and load before scheduling ANALYZE/OPTIMIZE separately. The example below only inspects candidates; it deletes neither posts nor comments. Permanent deletion requires a separate review of the selected items, retention policy, restorable backup and the operatorโ€™s intent.

optimize_database.shExample ยท verify your environment
#!/bin/bash
# optimize_database.sh โ€” inspection only
inspect_wordpress_db() {
    # Run in the verified WordPress installation as its intended account.
    # Replace wp_posts only after checking the configured table prefix.
    wp db query "SHOW TABLE STATUS WHERE Name = 'wp_posts';" || return 1
    wp post list --post_status=trash --fields=ID,post_title,post_date --format=table || return 1
    wp comment list --status=spam --fields=comment_ID,comment_date --format=table
}

Backup and Recovery Strategy

Prerequisites: This illustrates backup creation only; it performs no automatic deletion. Configure and verify paths, database name, permissions and a protected MySQL login-path first; do not embed passwords in the script. single-transaction applies to InnoDB; control DDL and file changes to obtain a consistent database/file set. Any command failure stops this stage and preserves existing known-good backups. A nonempty SQL file and readable archive do not prove recoverability. Restore the new set in an isolated environment and verify the database, files and site before marking it known-good. Review retention (for example, 30 days) separately only after that validation succeeds and independent copies plus a minimum known-good set remain. Never delete existing backups after failure or before validation.

backup_wordpress.shExample ยท verify your environment
#!/bin/bash
# backup_wordpress.sh โ€” creation stage; no retention deletion
backup_wordpress() (
    set -euo pipefail
    umask 077
    BACKUP_DIR="/backup/wordpress"
    WP_DIR="/var/www/html/wordpress"
    DB_NAME="wordpress"
    DB_LOGIN_PATH="wordpress_backup"
    mkdir -p -- "$BACKUP_DIR"
    STAGING=$(mktemp -d "$BACKUP_DIR/.pending.XXXXXXXX")
    mysqldump --login-path="$DB_LOGIN_PATH" --single-transaction \
        --routines --events --triggers "$DB_NAME" > "$STAGING/db.sql"
    test -s "$STAGING/db.sql"
    tar -czf "$STAGING/files.tar.gz" -C "$WP_DIR" .
    tar -tzf "$STAGING/files.tar.gz" > /dev/null
    printf 'Created, NOT restore-validated: %s\n' "$STAGING"
    # Keep all old backups. Validate an isolated restore before retention review.
)

WordPress Server Troubleshooting Guide

Connection Issue Diagnosis and Resolution

Separate DNS, network, listener and application-response failures. These example functions require validation of their invocation, output formats and actual targets; one ping or netstat snapshot cannot establish a root cause.

Bash โ€ข connection_diagnosis.sh
#!/bin/bash
# connection_diagnosis.sh

# Color definitions
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

# Log file paths
APACHE_ERROR_LOG="/var/log/httpd/error_log"
PHP_ERROR_LOG="/var/log/php-fpm/error.log"
SYSTEM_LOG="/var/log/messages"

# Connection status diagnosis
check_connections() {
    echo -e "${YELLOW}""=== Current Connection Status Analysis ===""${NC}"

    # Check active connections
    active_connections=$(netstat -an | grep ESTABLISHED | wc -l)
    echo "Active Connections: ${active_connections}"

    # Apache worker status
    apache_workers=$(ps aux | grep httpd | wc -l)
    echo "Apache Workers: ${apache_workers}"

    # PHP-FPM process status
    php_processes=$(ps aux | grep php-fpm | wc -l)
    echo "PHP-FPM Processes: ${php_processes}"
}

# Log analysis function
analyze_logs() {
    echo -e "${YELLOW}""=== Recent Errors Analysis ===""${NC}"

    echo "Apache Errors:"
    tail -n 20 $APACHE_ERROR_LOG | grep -i "error\|failed\|timeout"

    echo -e "\nPHP-FPM Errors:"
    tail -n 20 $PHP_ERROR_LOG | grep -i "error\|failed\|timeout"

    echo -e "\nSystem Messages:"
    tail -n 20 $SYSTEM_LOG | grep -i "error\|failed\|oom"
}
  

Performance Degradation Analysis and Response

Prerequisites: defunct describes a terminated child that its parent has not yet reaped; it is not a process name to kill. Use PID/PPID/STAT below to identify the parent, then investigate wait/waitpid handling and service logs. SIGKILL cannot reap a zombie. Restart a parent service only if needed after reviewing impact and recovery; the diagnosis does not call for blanket service restarts.

performance_troubleshoot.shExample ยท verify your environment
#!/bin/bash
# performance_troubleshoot.sh

# Performance metrics collection function
collect_performance_metrics() {
    echo "=== System Performance Metrics ==="

    # CPU usage
    echo "CPU Utilization:"
    top -bn1 | grep "Cpu(s)" | awk '{print $2}'

    # Memory usage
    echo -e "\nMemory Usage:"
    free -m

    # Disk I/O
    echo -e "\nDisk I/O Status:"
    iostat -x 1 3

    # MySQL status
    echo -e "\nMySQL Status:"
    mysqladmin status
}

# Immediate performance improvement measures
improve_performance() {
    echo "=== Executing Performance Improvement Measures ==="

    # Cache clearance
    echo "Clearing PHP OPCache..."
    php -r 'opcache_reset();'

    # WordPress cache cleanup
    echo "Clearing WordPress cache..."
    wp cache flush

    # Read-only zombie diagnosis
    echo "Inspecting zombie state and parent PID..."
    ps -eo pid,ppid,stat,comm | awk 'NR == 1 || $3 ~ /^Z/'

    # Decide on parent-service recovery separately after impact review.
}
  

Limits of the Automatic Recovery Example

Bash โ€ข auto_recovery.sh
#!/bin/bash
# auto_recovery.sh

# Threshold settings
MAX_LOAD=10
MAX_MEMORY_USAGE=90
MAX_CONNECTIONS=200

# System health check function
check_system_health() {
    # Load average check
    load_average=$(uptime | awk '{print $(NF-2)}' | cut -d. -f1)

    # Memory usage check
    memory_usage=$(free | grep Mem | awk '{print $3/$2 * 100.0}')

    # Connection count check
    connections=$(netstat -an | grep ESTABLISHED | wc -l)

    # Status evaluation and action
    if [ $load_average -gt $MAX_LOAD ] || \
       [ ${memory_usage%.*} -gt $MAX_MEMORY_USAGE ] || \
       [ $connections -gt $MAX_CONNECTIONS ]; then
        return 1
    fi
    return 0
}

# Recovery process
execute_recovery() {
    echo "$(date): Initiating recovery process"

    # Cache reset
    php -r 'opcache_reset();'
    wp cache flush

    # Service restart
    systemctl restart php-fpm
    systemctl restart httpd

    # Email notification
    mail -s "WordPress Server Automatic Recovery Executed" admin@example.com << EOF
Server automatic recovery has been executed.
Time: $(date)
Actions: Cache reset and service restart
Current Status:
$(collect_performance_metrics)
EOF
}

Conclusion and Key Guidelines

Effective Problem-Solving Checklist

  1. Preparation
    • Backup all configuration files
    • Document performance baselines
    • Maintain emergency contact list
  2. Problem Resolution Process
    • Accurately identify symptoms
    • Analyze logs for root causes
    • Apply solutions incrementally
    • Document all changes
  3. Post-Resolution Management
    • Document resolution process
    • Implement prevention measures
    • Enhance monitoring systems
ย 

Recommendations for Continuous Improvement

  • Conduct regular performance testing
  • Maintain security update schedule
  • Verify backup and recovery procedures
  • Update team training and technical documentation

Use recorded baselines and controlled comparisons to decide whether a change helped. The automatic-recovery sample requires the earlier functions and execution flow to be connected; crossing a sample threshold does not justify a restart by itself. A CLI OPcache reset should not be assumed to reset PHP-FPMโ€™s cache. Design repeat-action prevention, stop conditions and post-action validation before using it for production recovery.

ย 

Key Points to Remember:

  1. Always backup configurations before changes
  2. Make one change at a time for easier troubleshooting
  3. Monitor system stability after each change
  4. Do not expose debugging output publicly; retain protected diagnostic logs when needed

These examples support a structured investigation. A reliable result depends on the actual workload, tested changes and a working recovery procedure; follow those documented checks during an incident.

ย 

Note: All commands and configurations in this guide are based on Oracle Linux 8 and WordPress 6.7.1. Adjust settings according to your specific environment and requirements.

Scroll to Top