Sub topic 2
PHP-FPM: pools and worker processes
This chapter assumes you know basic Linux commands, can edit files with sudo, and have Nginx and PHP installed on a Debian or Ubuntu server. You should also know HTTP status codes and headers.
How PHP-FPM runs your code
PHP-FPM (FastCGI Process Manager) keeps a set of PHP worker processes running. Nginx does not execute PHP itself. It passes each PHP request to a worker over FastCGI, a standard protocol for handing a request to a program and receiving the response.
A pool is a named group of workers with its own settings, such as the user they run as and the socket they listen on.
; /etc/php/8.3/fpm/pool.d/www.conf
[www]
user = www-data
group = www-data
listen = /run/php/php8.3-fpm.sock
pm = dynamic
pm.max_children = 5
pm.start_servers = 2
pm.min_spare_servers = 1
pm.max_spare_servers = 3With pm = dynamic, PHP-FPM starts pm.start_servers workers and adds or removes idle workers within the spare limits. pm.max_children is a hard cap on total workers.
Connecting Nginx to PHP-FPM with FastCGI
Nginx sends .php requests to PHP-FPM with fastcgi_pass. The snippets/fastcgi-php.conf file sets the standard FastCGI parameters.
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php8.3-fpm.sock;
}The socket path must match the listen line in the pool. A mismatch produces a 502 error.
WSGI and ASGI: how Python apps talk to servers
WSGI (Web Server Gateway Interface) is a standard interface between Python web apps and web servers. A WSGI app is a callable, meaning a function you can call, that receives the request environment and a start_response function. It returns the body as an iterable of bytes. ASGI (Asynchronous Server Gateway Interface) is the newer version, built for async code and WebSockets.
Running a Python app with Gunicorn
Gunicorn is a WSGI server. Save this as app.py:
def application(environ, start_response):
body = b"Hello from WSGI\n"
start_response("200 OK", [
("Content-Type", "text/plain"),
("Content-Length", str(len(body))),
])
return [body]Start Gunicorn with three workers, then test it:
gunicorn --workers 3 --bind 127.0.0.1:8000 app:application
curl -i http://127.0.0.1:8000/Each worker is a separate process, so three workers handle three requests at once. Binding to 127.0.0.1 keeps the app off the public network.
Putting Nginx in front of Gunicorn with proxy_pass
Nginx receives public requests and forwards them to Gunicorn with proxy_pass:
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
}
}sudo nginx -t
sudo systemctl reload nginx> Not a quote: Nginx fastcgi_pass speaks the FastCGI protocol to PHP-FPM, while proxy_pass speaks HTTP to Gunicorn.
Exercise
If pm.max_children is 5 and six requests arrive at the same moment, what happens to the sixth request?
Show answer
It waits in the socket queue until a worker is free. If the wait is too long, Nginx may return a 502 or 504 error.