Optimizing PHP in Ubuntu with Apache: A Step-by-Step Guide
Optimizing PHP performance in an Apache environment on Ubuntu involves configuring both the web server (Apache) and the PHP interpreter to efficiently handle requests, reduce latency, and utilize system resources effectively. Below are actionable steps categorized by component:
Before optimization, ensure your system is up-to-date to benefit from the latest security patches and performance improvements. Install Apache, PHP, and essential extensions (e.g., MySQL support, OPcache):
sudo apt update && sudo apt upgrade -y
sudo apt install apache2 php libapache2-mod-php php-mysql php-opcache php-redis -y
This installs Apache, PHP (with default modules), OPcache (for bytecode caching), and Redis (for object caching).
Apache’s configuration directly impacts how PHP requests are processed. Focus on the following settings:
Activate modules that improve PHP handling and compression:
sudo a2enmod rewrite deflate expires cache
sudo systemctl restart apache2
rewrite: Enables URL rewriting (useful for clean URLs in frameworks like Laravel).deflate: Compresses response data (reduces transfer size).expires: Sets cache headers for static assets (decreases repeat requests).cache: Enables disk-based caching for dynamic content.Apache’s MPM determines how it handles concurrent requests. For PHP, event MPM (recommended for modern systems) or prefork MPM (for non-thread-safe PHP versions) is ideal.
Check current MPM:
apache2ctl -V | grep -i mpm
Edit MPM settings (example for event MPM, adjust based on server RAM/CPU):
sudo nano /etc/apache2/mods-enabled/mpm_event.conf
Set:
<IfModule mpm_event_module>
StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 150
MaxConnectionsPerChild 0
</IfModule>
MaxRequestWorkers: Maximum concurrent connections (adjust based on (Total RAM - System RAM) / Memory per Apache process).ThreadsPerChild: Threads per process (higher values handle more requests per process).Disable unused MPMs (e.g., if using event MPM, disable prefork):
sudo a2dismod mpm_prefork
sudo systemctl restart apache2
KeepAlive reduces TCP connection overhead by allowing multiple requests over a single connection. Add to /etc/apache2/apache2.conf:
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
MaxKeepAliveRequests: Limits requests per connection (prevents resource exhaustion).KeepAliveTimeout: Time (in seconds) to keep the connection alive.PHP settings control script execution, memory usage, and caching. Edit /etc/php/8.1/apache2/php.ini (adjust version as needed):
OPcache stores precompiled script bytecode in memory, eliminating the need to recompile scripts on each request. Add/modify these lines:
[opcache]
zend_extension=opcache.so
opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
opcache.revalidate_freq=60
opcache.fast_shutdown=1
memory_consumption: Memory allocated to OPcache (increase if running multiple large applications).max_accelerated_files: Number of files OPcache tracks (set to ~80% of your application’s total files).revalidate_freq: Time (in seconds) between file checks (lower for development, higher for production).memory_limit: Increase from default (128M) to 256M or higher (depends on application needs).max_execution_time: Set to 30 seconds (or higher for long-running scripts like imports).upload_max_filesize/post_max_size: Increase for file uploads (e.g., 50M).memory_limit = 256M
max_execution_time = 30
upload_max_filesize = 50M
post_max_size = 50M
For security and performance, disable functions that are rarely used in production (e.g., exec, shell_exec):
disable_functions = exec,passthru,shell_exec,system,proc_open
Caching reduces redundant processing and database load:
Redis stores frequently accessed data (e.g., database queries, sessions) in memory. Install and configure:
sudo apt install redis-server php-redis -y
/etc/php/8.1/apache2/php.ini):extension=redis.so
predis/predis.Use mod_cache and mod_cache_disk to cache dynamic content (e.g., PHP pages). Edit /etc/apache2/conf-available/cache.conf:
<IfModule mod_cache.c>
<IfModule mod_cache_disk.c>
CacheEnable disk /
CacheRoot /var/cache/apache2/mod_cache_disk
CacheDirLevels 2
CacheDirLength 1
</IfModule>
</IfModule>
Enable the module and restart Apache:
sudo a2enconf cache
sudo systemctl restart apache2
Regularly monitor your setup to identify bottlenecks:
htop: Monitor CPU, memory, and process usage.apachetop: Track Apache request rates and response times.logrotate: Manage log file size (prevent disk exhaustion).sudo apt install htop apachetop logrotate -y
Check Apache error logs (/var/log/apache2/error.log) and PHP error logs (configure in php.ini via error_log) for warnings/errors.
error_log = /var/log/php_errors.log
log_errors = On
Use tools like ab (Apache Benchmark) to test server performance:
ab -n 1000 -c 100 http://yourdomain.com/
This sends 1000 requests with 100 concurrent users, helping you evaluate how optimizations impact throughput.
By following these steps, you can significantly enhance the performance of PHP applications running on Apache in Ubuntu. Remember to adjust settings based on your server’s hardware (RAM, CPU) and application requirements (e.g., a high-traffic site may need larger MaxRequestWorkers or memory_limit).