[PHP‐FPM] best tune - fourslickz/notes GitHub Wiki

1. Edit PHP-FPM Pool Configuration

Edit /etc/php/7.x/fpm/pool.d/www.conf

; The user and group under which PHP-FPM will run.
user = www-data
group = www-data

; Listen on a TCP socket or a Unix socket.
; Use TCP if this VM serves requests remotely (e.g., multiple VMs).
listen = 0.0.0.0:9000
; Uncomment the following for Unix sockets (faster for local use).
; listen = /run/php/php7.x-fpm.sock

; Set permissions for the Unix socket (only needed for socket usage).
listen.owner = www-data
listen.group = www-data
listen.mode = 0660

; Set the process manager type. Dynamic allows scaling based on demand.
pm = dynamic

; Number of child processes to start on service startup.
pm.start_servers = 8

; Minimum number of idle child processes.
pm.min_spare_servers = 4

; Maximum number of idle child processes.
pm.max_spare_servers = 12

; Total number of child processes that can run simultaneously.
pm.max_children = 50

; Maximum number of requests a child process should handle before respawning.
; Prevents memory leaks from long-running scripts.
pm.max_requests = 500

; Log slow requests for debugging.
request_slowlog_timeout = 5s
slowlog = /var/log/php7.x-fpm.slow.log

; Error log settings.
php_admin_value[error_log] = /var/log/php7.x-fpm.error.log
php_admin_flag[log_errors] = on

Estimate PHP process memory usage

ps --no-headers -o "rss,cmd" -C php-fpm7.x | awk '{ sum+=$1 } END { printf ("%.0f\n", sum/NR) }'
Total RAM: 8 GB (8192 MB)
Reserve 2 GB for the system and other apps → 8192 - 2048 = 6144 MB
Divide by PHP process size: 6144 MB / 50 MB ≈ 122

3. Tuning OPcache

Edit the OPcache configuration file: /etc/php/7.x/fpm/conf.d/10-opcache.ini

; Enable OPcache
opcache.enable=1
opcache.enable_cli=1

; Memory allocated for OPcache (adjust based on app size)
opcache.memory_consumption=256

; Maximum number of scripts cached
opcache.max_accelerated_files=10000

; Validate cached scripts less frequently
opcache.validate_timestamps=1
opcache.revalidate_freq=2

; Prevent fragmentation
opcache.interned_strings_buffer=16

4. Optimize PHP.ini

Edit /etc/php/7.x/fpm/php.ini for global settings:

; Increase execution time and memory limits for intensive scripts.
max_execution_time = 120
memory_limit = 512M

; Set post size and upload size limits for file uploads.
post_max_size = 100M
upload_max_filesize = 100M

; Enable error logging.
log_errors = On
error_log = /var/log/php7.x-fpm.error.log

; Disable unnecessary PHP modules (e.g., xdebug in production).
zend_extension=xdebug.so ; Uncomment or remove in production.