How to Configure Max Connections in Nginx and PHP-FPM
/ 2 min read
Table of Contents
As traffic grows, default web server settings fail to handle the load. Users experience 502 Bad Gateway errors or hanging pages because the server has exhausted its connection limit.
To scale effectively, you must increase the process pools in Nginx and PHP-FPM, as well as system OS limits.
1. Tuning Nginx Worker Processes
Nginx uses worker processes to handle requests. Settings are located in /etc/nginx/nginx.conf.
# Automatically spawn processes based on CPU coresworker_processes auto;
events { # Number of simultaneous connections per worker process # Default is often 768 or 1024. Increase for high-traffic sites. worker_connections 4096;
# Event processing method (highly efficient for Linux) use epoll;
# Accept as many connections as possible at once multi_accept on;}_Total max clients = worker_processes _ worker_connections.*
2. Tuning PHP-FPM Pool
Nginx forwards dynamic requests to PHP-FPM. If Nginx can accept 4000 connections but PHP-FPM can only handle 50, a bottleneck occurs.
Open your pool configuration (e.g., /etc/php/8.3/fpm/pool.d/www.conf):
; Dynamic process management modepm = dynamic
; Maximum number of child processes (limit of simultaneous requests)pm.max_children = 200
; Number of child processes created on startuppm.start_servers = 20
; Minimum number of idle spare processespm.min_spare_servers = 10
; Maximum number of idle spare processespm.max_spare_servers = 30
; Number of requests a process handles before respawning (memory leak protection)pm.max_requests = 500Warning: Each PHP process consumes RAM (20 to 100+ MB). Calculate pm.max_children based on your server’s available RAM.
3. Linux System Limits (File Descriptors)
In Linux, every network connection is an open file. If the system imposes a strict file descriptor limit, your new Nginx settings will fail.
Check the current limit:
ulimit -nTo increase the limit, edit /etc/security/limits.conf:
* soft nofile 65535* hard nofile 65535nginx soft nofile 65535nginx hard nofile 65535Applying Changes
After making all modifications, restart the services:
sudo systemctl restart php8.3-fpmsudo systemctl restart nginx