Section 17: Server Administration Tasks

Complete Guide to System Updates, WordPress Management, Security, and Database Optimization

1. System Updates

Basic Update Commands

These are the fundamental commands for keeping your Ubuntu server up to date:

sudo apt update sudo apt upgrade sudo apt autoremove

Combined Single Command

Execute all update operations in one line:

sudo apt update && sudo apt upgrade && sudo apt autoremove

Automated Update Command (Non-Interactive)

Add the -y flag to automatically answer "yes" to all prompts:

sudo apt update && sudo apt upgrade -y && sudo apt autoremove -y

Update Process Flow

apt update
Refresh package lists
apt upgrade
Install available updates
apt autoremove
Remove unnecessary packages

2. Creating a Bash Alias for Updates

Create a convenient alias to simplify system updates:

1Navigate to Home Directory and Edit Aliases

cd nano .bash_aliases

2Add the Alias Definition

alias server_updates='sudo apt update && sudo apt upgrade -y && sudo apt autoremove -y'

3Activate the Alias

Use one of these methods to activate your new alias:

source ~/.bash_aliases # OR logout and login again exit
Usage: After activation, simply type server_updates to run all update commands.

3. Creating an Update Script

1Create the Script File

sudo nano server_updates.sh

2Script Contents

#!/bin/bash # Check if script is run as root if [ "$EUID" -ne 0 ]; then echo "Please run this script with sudo or as root." exit fi # Update package lists echo "Updating package lists..." sudo apt update # Upgrade installed packages echo "Upgrading installed packages..." sudo apt upgrade -y # Remove unnecessary packages echo "Removing unnecessary packages..." sudo apt autoremove -y echo "Update, upgrade, and autoremove completed."
Note: The script includes root privilege checking to ensure it runs with appropriate permissions.

4. WordPress Updates Management

Important: Always create a backup before performing WordPress updates. Updates can sometimes cause conflicts or compatibility issues.

Update Strategy Recommendations

Default PHP Pool User Permissions (Permissive)

This configuration allows updates to run without permission issues:

cd /var/www/example.com/ sudo ls -l public_html/ sudo chown -R PHP_POOL_USER:PHP_POOL_USER public_html/ sudo find /var/www/example.com/public_html/ -type d -exec chmod 770 {} \; sudo find /var/www/example.com/public_html/ -type f -exec chmod 660 {} \;
Type Permission Owner Group Other
Directories 770 rwx (7) rwx (7) --- (0)
Files 660 rw- (6) rw- (6) --- (0)

Restart PHP-FPM After Updates

sudo systemctl reload php8.3-fpm

5. Hardened WordPress Permissions

For enhanced security, implement more restrictive permissions:

Initial Hardened Setup

cd /var/www/example.com/ sudo ls -l public_html/ sudo chown -R PHP_POOL_USER:PHP_POOL_USER public_html/ sudo find /var/www/example.com/public_html/ -type d -exec chmod 550 {} \; sudo find /var/www/example.com/public_html/ -type f -exec chmod 440 {} \; sudo find /var/www/example.com/public_html/wp-content/ -type d -exec chmod 770 {} \; sudo find /var/www/example.com/public_html/wp-content/ -type f -exec chmod 660 {} \;

WordPress Update Workflow with Hardened Permissions

Loosen Permissions
770 dirs / 660 files
Perform WordPress Update
Core, themes, plugins
Harden Permissions
550/440 core, 770/660 wp-content
Reload PHP-FPM
Clear opcache

Pre-Update: Loosen Permissions

sudo find /var/www/example.com/public_html/ -type d -exec chmod 770 {} \; sudo find /var/www/example.com/public_html/ -type f -exec chmod 660 {} \;

Post-Update: Re-harden Permissions

sudo find /var/www/example.com/public_html/ -type d -exec chmod 550 {} \; sudo find /var/www/example.com/public_html/ -type f -exec chmod 440 {} \; sudo find /var/www/example.com/public_html/wp-content/ -type d -exec chmod 770 {} \; sudo find /var/www/example.com/public_html/wp-content/ -type f -exec chmod 660 {} \;

Final Step: Reload PHP-FPM

sudo systemctl reload php8.3-fpm
Location Directories Files Purpose
Core WordPress Files 550 440 Read-only for security
wp-content Directory 770 660 Allow plugin file creation

6. ClamAV Antivirus Setup

Installation

sudo apt update sudo apt install clamav
Info: The ClamAV definition database updates automatically after installation.

Disable Automatic Updates

sudo systemctl stop clamav-freshclam sudo systemctl disable clamav-freshclam

Manual Database Update

sudo freshclam

Perform Manual Scan

sudo clamscan -r /path/2/scan

Complete Manual Workflow

sudo freshclam sudo clamscan -r /path/2/scan
Best Practice: Run manual scans regularly, especially after installing new software or receiving suspicious files.

7. RKHunter (Rootkit Hunter)

Installation

sudo apt install rkhunter

Update Properties Database

sudo rkhunter --propupd

Perform Complete System Check

sudo rkhunter --checkall --sk

Flags:

View Log Files

sudo cat /var/log/rkhunter.log sudo less /var/log/rkhunter.log

Remove Automatic Cron Jobs

cd /etc/cron.daily/ sudo rm rkhunter cd /etc/cron.weekly/ sudo rm rkhunter
Note: Removing cron jobs allows manual control over when security scans are performed.

8. Database Tuning (MariaDB/MySQL)

View InnoDB Buffer Pool Actual Memory Usage

SHOW GLOBAL STATUS LIKE 'Innodb_buffer_pool_bytes_data';

View All Database Sizes

SELECT table_schema AS "Database", ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) AS "Size (MB)" FROM information_schema.tables GROUP BY table_schema;

View InnoDB Database Sizes Only

SELECT table_schema AS "Database", SUM(data_length + index_length) / 1024 / 1024 AS "Size (MB)" FROM information_schema.tables WHERE engine = 'InnoDB' GROUP BY table_schema;

View Buffer Pool Usage by Database

SELECT table_schema AS "Database", SUM(data_length + index_length) / 1024 / 1024 AS "Size (MB)" FROM information_schema.tables WHERE engine = 'InnoDB' GROUP BY table_schema;

View Database Table I/O Statistics

SELECT object_schema AS 'Database', object_name AS 'Table', COUNT_READ AS 'Reads', COUNT_WRITE AS 'Writes', SUM_TIMER_READ / 1000000000 AS 'Read Time (ms)', SUM_TIMER_WRITE / 1000000000 AS 'Write Time (ms)' FROM performance_schema.table_io_waits_summary_by_table ORDER BY SUM_TIMER_READ + SUM_TIMER_WRITE DESC;

Run MySQLTuner

cd cd MySQLTuner/ ls -l sudo ./mysqltuner
MySQLTuner: A Perl script that analyzes your MySQL/MariaDB installation and provides recommendations for optimization.

9. Disk Space Management

Critical: Monitor disk space regularly. Running out of disk space can cause server crashes.

Check Disk Space Usage

df -h

The -h flag displays sizes in human-readable format (KB, MB, GB).

Clean Package Cache

sudo apt autoremove && sudo apt clean

Clean System Logs

sudo journalctl --vacuum-time=1days

This removes journal logs older than 1 day.

Analyze Directory Sizes

cd / du -ah --max-depth=1 | sort -h

Largest directories are displayed at the bottom. You can navigate to any directory and repeat the command.

Disk Space Monitoring Workflow

Check Disk Space
df -h
Identify Large Directories
du -ah --max-depth=1
Clean Packages & Logs
apt clean, journalctl

10. Nginx Connection Backlog Configuration

Configure the connection backlog for better handling of concurrent connections:

backlog=2048 listen 80 backlog=2048; listen 443 ssl backlog=2048;
Backlog: Defines the maximum queue length for pending connections. Higher values can improve performance under heavy load.

11. PHP OPcache Files Monitoring Script

Create the Script

nano opcache_files.sh

Script Contents

#!/bin/bash round_to_prime() { local value=$1 primes=(223 463 983 1979 3907 7963 16229 32531 65407 130987 262237 524524 1048793) closest=0 min_diff=$((value - primes[0])) for prime in "${primes[@]}"; do diff=$((value - prime)) if [ $diff -lt 0 ]; then closest=$prime break elif [ $diff -lt $min_diff ]; then min_diff=$diff closest=$prime fi done echo "$closest" } echo "" echo "Checking for opcache.max_accelerated_files directive in PHP pool files..." echo "" echo "The value used (actual value) will be the first number in the set of prime numbers" echo "223, 463, 983, 1979, 3907, 7963, 16229, 32531, 65407, 130987, 262237, 524521, 1048793" echo "that is greater than or equal to the configured value (value set)" echo "" POOL_DIR="/etc/php/8.3/fpm/pool.d/" for file in "$POOL_DIR"*.conf; do filename=$(basename "$file") if grep -q "opcache.max_accelerated_files" "$file"; then value=$(grep "opcache.max_accelerated_files" "$file" | awk -F'=' '{print $2}' | tr -d ' ') rounded_value=$(round_to_prime "$value") echo "File: $filename - opcache.max_accelerated_files: set value ($value) actual value ($rounded_value)" else echo "File: $filename - opcache.max_accelerated_files directive not found" fi done echo "" echo "Listing domain names and number of PHP files in public_html directories..." echo "" WWW_DIR="/var/www/" for domain_dir in "$WWW_DIR"*/ ; do if [ "$domain_dir" == "/var/www/html/" ]; then continue fi domain_name=$(basename "$domain_dir") public_html_dir="$domain_dir/public_html/" if [ -d "$public_html_dir" ]; then php_file_count=$(find "$public_html_dir" -type f -name "*.php" | wc -l) echo "WordPress site: $domain_name - PHP files: $php_file_count" else echo "Domain: $domain_name - public_html directory not found" fi done echo ""
Purpose: This script checks OPcache configuration and counts PHP files per domain to help optimize the opcache.max_accelerated_files setting.

12. Common WordPress Update Issues

Issue 1: "Another update is currently in progress"

This occurs when WordPress fails to remove the core updater lock.

Solution: Remove Lock via SQL

mysql -u root -p SHOW DATABASES; USE your_database_name; DELETE FROM wp_options WHERE option_name = 'core_updater.lock'; exit
Important: Change wp_ to your actual table prefix if different.

Issue 2: "Briefly unavailable for scheduled maintenance"

This indicates a stuck maintenance mode, usually from an interrupted update.

Solution: Delete Maintenance File

cd /var/www/example.com/public_html/ sudo rm .maintenance

Post-Fix Recommendation

After resolving either issue, reload PHP-FPM to clear the opcache:

sudo systemctl reload php8.3-fpm

13. Best Practices Summary

System Maintenance

  • Run system updates regularly (weekly recommended)
  • Monitor disk space usage proactively
  • Review security scan logs regularly
  • Keep database optimized with MySQLTuner recommendations

WordPress Management

  • Always backup before updates
  • Update plugins one or two at a time
  • Test site functionality after each update
  • Use hardened permissions when not updating
  • Reload PHP-FPM after major changes

Security

  • Run ClamAV scans regularly
  • Perform RKHunter checks periodically
  • Monitor system logs for anomalies
  • Keep all software up to date
  • Use restrictive file permissions when possible

Performance

  • Monitor OPcache configuration and usage
  • Optimize database settings based on actual usage
  • Configure appropriate backlog values
  • Clear caches after significant changes