Manage resource usage Apache & PHP

This post was generated by an LLM


Listen

How to Optimize Apache Server Performance and Reduce Resource Usage on Small Servers

When running a PHP 8.0 and Apache setup on a small server with limited resources, you might encounter high CPU and memory usage due to multiple Apache instances consuming more resources than necessary. This tutorial will guide you through optimizing your Apache configuration and implementing caching solutions to improve performance and reduce resource consumption.

Prerequisites

Before starting this tutorial, you’ll need:

  • A server running Ubuntu or Debian with Apache and PHP 8.0 installed
  • Root or sudo access to the server
  • Basic knowledge of command-line operations
  • SSH access to your server

Step 1: Analyze Apache Processes

First, let’s analyze the running Apache processes to determine if there are indeed too many instances consuming resources.

  1. Connect to your server via SSH.

  2. Run the following command to view the Apache processes:

ps aux | grep apache2

This command will display a list of all running Apache processes along with their resource usage.

  1. Check the number of Apache processes and their memory consumption. If you notice an excessive number of processes or high memory usage, proceed to the next step.

You can also use the following command to get a count of active Apache processes:

ps aux | grep apache2 | grep -v grep | wc -l

Step 2: Adjust Apache Configuration

To optimize Apache’s performance and resource usage, we’ll modify the Apache configuration file to control the number of worker processes.

  1. Open the Apache configuration file using a text editor:
sudo nano /etc/apache2/apache2.conf
  1. Locate the <IfModule mpm_prefork_module> section in the configuration file. If it doesn’t exist, you may need to check the mods-available directory:
sudo nano /etc/apache2/mods-available/mpm_prefork.conf
  1. Adjust the following directives based on your server’s resources:
<IfModule mpm_prefork_module>
    StartServers 2
    MinSpareServers 2
    MaxSpareServers 4
    MaxRequestWorkers 50
    MaxConnectionsPerChild 1000
</IfModule>

Here’s what each directive controls:

  • StartServers: The initial number of Apache child processes to start
  • MinSpareServers and MaxSpareServers: The minimum and maximum number of idle Apache child processes
  • MaxRequestWorkers: The maximum number of simultaneous requests that Apache can handle
  • MaxConnectionsPerChild: The maximum number of requests a child process can handle before it is terminated and replaced

For a server with 2 CPUs and 4GB of RAM, the above settings are a good starting point. Adjust these values based on your server’s available resources and expected traffic.

  1. Save the changes and exit the text editor (Ctrl+X, then Y, then Enter for nano).

Step 3: Enable the Prefork Module

Ensure the prefork module is enabled:

sudo a2enmod mpm_prefork
sudo a2dismod mpm_event mpm_worker

Step 4: Restart Apache

After modifying the Apache configuration, restart the Apache service to apply the changes:

sudo systemctl restart apache2

Verify that Apache is running properly:

sudo systemctl status apache2

Step 5: Monitor Server Performance

Monitor your server’s CPU and memory usage after making the configuration changes.

  1. Use the top command to monitor real-time resource usage:
top

Look for the CPU and memory usage percentages to ensure they are within acceptable limits.

  1. You can also use tools like htop or glances for a more detailed view of system resource usage:
sudo apt update
sudo apt install htop
htop
  1. Monitor Apache processes specifically:
watch "ps aux | grep apache2"

Step 6: Enable OPcache for PHP Performance

OPcache is a built-in caching engine in PHP that optimizes PHP performance by storing precompiled script bytecode in shared memory. It reduces the overhead of parsing and compiling PHP scripts on each request.

Enable OPcache

OPcache is bundled with PHP 8.0, but it may not be enabled by default. To enable OPcache:

  1. Open the PHP configuration file:
sudo nano /etc/php/8.0/apache2/php.ini
  1. Locate the [opcache] section in the configuration file, or add it if it doesn’t exist.

  2. Ensure the following directives are set:

opcache.enable=1
opcache.enable_cli=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=10000
opcache.revalidate_freq=60

Configuration explanations:

  • opcache.enable: Enables OPcache for web requests
  • opcache.enable_cli: Enables OPcache for PHP CLI commands
  • opcache.memory_consumption: Sets the maximum memory OPcache can use (in megabytes)
  • opcache.interned_strings_buffer: Sets the size of the interned strings buffer (in megabytes)
  • opcache.max_accelerated_files: Sets the maximum number of files OPcache can cache
  • opcache.revalidate_freq: Sets the frequency (in seconds) at which OPcache checks for file modifications
  1. Save the changes and exit the text editor.

Step 7: Restart Apache Again

After modifying the PHP configuration, restart the Apache service:

sudo systemctl restart apache2

Step 8: Verify OPcache Configuration

To verify that OPcache is enabled and configured correctly:

  1. Create a PHP info script:
echo "<?php phpinfo(); ?>" | sudo tee /var/www/html/info.php
  1. Access the script through your web browser at http://your-server-ip/info.php

  2. Look for the “OPcache” section in the output to confirm the settings.

  3. Remove the info script for security:

sudo rm /var/www/html/info.php

Alternatively, you can check OPcache status via command line:

php -m | grep -i opcache

Step 9: Additional Optimization Techniques

If you still observe high resource usage, consider these additional optimizations:

Enable Apache Compression

Enable the mod_deflate module to compress server responses:

sudo a2enmod deflate
sudo systemctl restart apache2

Optimize PHP Settings

Edit the PHP configuration to set appropriate limits:

sudo nano /etc/php/8.0/apache2/php.ini

Adjust these values based on your needs:

memory_limit = 256M
max_execution_time = 60
max_input_vars = 3000
post_max_size = 64M
upload_max_filesize = 64M

Consider Alternative Architectures

For high-traffic sites, consider:

  • Using Nginx as a reverse proxy in front of Apache
  • Implementing application-level caching (Redis/Memcached)
  • Database query optimization
  • Content Delivery Network (CDN) for static assets

Step 10: Ongoing Monitoring

Set up automated monitoring to track your server’s performance:

  1. Install and configure system monitoring tools:
sudo apt install sysstat
  1. Monitor Apache access and error logs:
sudo tail -f /var/log/apache2/access.log
sudo tail -f /var/log/apache2/error.log
  1. Set up log rotation to prevent log files from consuming disk space:
sudo nano /etc/logrotate.d/apache2

Conclusion

By following these steps—optimizing Apache’s prefork module configuration, enabling OPcache for PHP bytecode caching, and implementing additional performance optimizations—you can significantly reduce resource usage on your server while maintaining good performance.

The key benefits of this optimization include:

  • Improved PHP script execution speed through bytecode caching
  • Reduced CPU usage as scripts don’t need to be parsed and compiled on each request
  • Better memory management through controlled Apache worker processes
  • More efficient handling of concurrent requests

Remember to continuously monitor your server’s performance and make adjustments as needed based on your specific workload and requirements. Start with conservative settings and gradually increase them as you understand your server’s capacity and traffic patterns.


This post has been uploaded to share ideas an explanations to questions I might have, relating to no specific topics in particular. It may not be factually accurate and I may not endorse or agree with the topic or explanation – please contact me if you would like any content taken down and I will comply to all reasonable requests made in good faith.

– Dan


Comments

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.