Apache is a powerful web server, but out-of-the-box configurations are often not optimized for your specific VPS resources. A common issue is that Apache tries to spawn more processes than your RAM can handle, causing the server to swap and eventually crash (Out of Memory).
This guide helps you calculate the perfect settings to maximize traffic capacity without crashing your server.
Step 1: Analyze Memory Usage
Before we can tune, we need to know how much RAM an average Apache process consumes. We recommend using the tool ps_mem.
- Install/Download the tool:
curl -L https://raw.githubusercontent.com/pixelb/ps_mem/master/ps_mem.py -o ps_mem.py chmod +x ps_mem.py - Run it to see memory usage per application:
sudo python3 ps_mem.py
Look for the line httpd or apache2. It will show the total RAM used and the count of processes. Divide the total by the count to get the Average Process Size.
Example: If Apache uses 500MB for 10 processes, your average is 50MB per process.
Step 2: Calculate MaxRequestWorkers
In Apache 2.4, the directive that controls the maximum number of simultaneous visitors is called MaxRequestWorkers (formerly known as MaxClients).
We need to set this number so that even if all slots are full, the server stays within its RAM limits.
(Total RAM - OS Overhead - Database RAM) / Avg Apache Process = MaxRequestWorkers
Example Calculation:
- VPS RAM: 4000MB (4GB)
- Reserved for OS & MySQL: -1000MB
- Available for Apache: 3000MB
- Avg Process Size: 50MB
- Result: 3000 / 50 = 60
In this example, you should set MaxRequestWorkers to 60. The default is often 150 or 256, which would crash this server under load.
Step 3: Apply Configuration
The location of the config file depends on your OS and MPM (Multi-Processing Module).
-
CentOS/RHEL:
/etc/httpd/conf.modules.d/00-mpm.conf(or similar) -
Ubuntu/Debian:
/etc/apache2/mods-enabled/mpm_prefork.conf
Edit the file and update the directives. You usually need to update ServerLimit to match:
<IfModule mpm_prefork_module>
StartServers 5
MinSpareServers 5
MaxSpareServers 10
# The limit we calculated:
MaxRequestWorkers 60
# Must be equal to or higher than MaxRequestWorkers:
ServerLimit 60
MaxConnectionsPerChild 0
</IfModule>
Restart Apache to apply changes:
# CentOS
systemctl restart httpd
# Ubuntu
systemctl restart apache2
Step 4: Disable Unused Modules
To lower the memory footprint per process, disable modules you don't use.
1. List enabled modules:
apachectl -M
2. Disable modules (example for Ubuntu):
a2dismod status
systemctl restart apache2
(On CentOS, comment out the LoadModule lines in /etc/httpd/conf.modules.d/).