On a single host, a Unix domain socket is the right default for PHP-FPM: it skips the IP and TCP stack, it cannot be reached from the network at all, and it gives you file permissions as a real access control. The moment PHP-FPM runs on a different host — or in a container that cannot share a filesystem path with the web server — TCP is the only option, and that is a topology decision rather than a performance one. The speed gap is far smaller than most benchmarks claim: tens of microseconds per connection, against a PHP request that takes tens of milliseconds. What separates the two transports in production is how they fail — socket ownership, a full listen backlog, ephemeral port exhaustion — and that is what the rest of this page covers.
What you’ll accomplish
- Set
listenin both forms and match it on the nginx (fastcgi_pass) and Apache (SetHandler proxy:) side. - Get socket ownership right with
listen.owner,listen.groupandlisten.mode, and recognise the 502 that follows when you don’t. - Size
listen.backlogagainstnet.core.somaxconn, and read backlog pressure fromss, from the kernel counters and from the FPM status page. - Bind a TCP pool safely, and understand why
0.0.0.0:9000on a reachable interface is a remote code execution invitation rather than a performance tweak. - Measure both transports on your own hardware and read the result honestly, instead of trusting a number from someone else’s box.
Prerequisites
- Root or
sudoon the host running PHP-FPM, and the ability to reload both PHP-FPM and the web server. - PHP-FPM 7.4 or newer. The directives below have been stable for many major versions; only the paths move:
/etc/php/8.3/fpm/pool.d/on Debian and Ubuntu,/etc/php-fpm.d/on RHEL, Alma and Rocky,/opt/cpanel/ea-php83/root/etc/php-fpm.d/under cPanel’s EA-PHP. - A socket directory that survives for the lifetime of the service:
/run/php/on Debian and Ubuntu,/run/php-fpm/on the RHEL family, both tmpfs created by the packaged systemd unit. Not/tmp— it is world-writable, cleared on boot, and may be a private namespace under systemd’sPrivateTmp. iproute2forss, plusnstatornet-toolsfor the kernel counters.- With SELinux enforcing, the web server reaches the packaged socket path because that path is labelled for it. A socket you invent elsewhere will not be, and the denial reads as a permission error that
ls -lcannot explain. - Read
net.core.somaxconnon the host rather than assuming it. The kernel default changed from 128 to 4096 in Linux 5.4, and distributions override it.
How it works
A Unix domain socket is an AF_UNIX endpoint with a filesystem path for a name. When nginx connects to it, the kernel copies bytes from one socket buffer to the other: no IP header, no TCP header, no sequence numbering, no route lookup, no netfilter traversal, no port allocation, no teardown state. The path is the address, and the permission bits on that path are the only thing between a process and the pool.
A TCP loopback connection to 127.0.0.1:9000 runs the whole TCP state machine even though both endpoints are on the same machine. Before the first FastCGI byte moves, the kernel picks an ephemeral port for the client side out of net.ipv4.ip_local_port_range, completes a three-way handshake over the lo device, and builds real IP and TCP headers. Packets on lo do traverse the netfilter hooks, so your iptables or nftables ruleset is in the path whether you meant it to be or not. When the connection closes, the side that closed first holds the four-tuple in TIME_WAIT for 60 seconds.
Two honest qualifications, because both are usually overstated. Checksums are not really part of the difference — the kernel skips TCP checksum validation on the loopback device anyway. And the handshake is cheap: the extra cost of a loopback TCP connection lands in the tens of microseconds, against a WordPress or Laravel request that spends 20 to 200 milliseconds in PHP and the database. It becomes visible only at the tail, under high connection churn, and it shows up there as connection failures rather than slower responses.
The differences that will actually page someone are these:
| Unix domain socket | TCP on loopback | TCP across hosts | |
|---|---|---|---|
| Reachable from the network | No, ever | No, if bound to 127.0.0.1 | Yes — this is the point, and the risk |
| Access control | File owner, group and mode | Bind address only | listen.allowed_clients plus a firewall |
Port and TIME_WAIT pressure | None | Real above a few thousand connections/s | Real, plus NAT and conntrack |
| Backlog overflow evidence | nginx error log, FPM status page | Same, plus ListenOverflows counters | Same |
| One endpoint per site | Natural — one socket file per pool | Needs one port per pool | Needs one port per pool |
| Load balancing across instances | Not possible | upstream block over several ports | upstream block over several hosts |
The access-control row deserves a sentence of its own. FastCGI has no authentication whatsoever: anything that can open a TCP connection to a pool can hand it a SCRIPT_FILENAME and have the pool execute a file as the pool user. Binding to 0.0.0.0:9000 on a host with a reachable interface is functionally the same as publishing a remote shell. security.limit_extensions (default .php) narrows what can be executed, but it is a second line of defence, not the fence.
Step-by-step
1. Settle which transport the topology calls for. Answer this before editing anything: switching later means touching the pool file and every vhost that references it.
2. Read what the pool is bound to right now. Never assume the file on disk matches the running process.
grep -rn '^listen' /etc/php/8.3/fpm/pool.d/
ss -lnx | grep -i fpm
ss -lnt '( sport = :9000 )'
A socket pool prints a path from grep and one LISTEN line from ss -lnx; a TCP pool prints an address and port that ss -lnt confirms. If grep and ss disagree, someone reloaded the config without restarting after a transport change.
3. Configure the socket form. In the pool file, the three ownership directives are not optional — the defaults are the running user, which is very often not the web server user.
listen = /run/php/php8.3-fpm.sock
listen.owner = www-data
listen.group = www-data
listen.mode = 0660
listen.backlog = 511
On a multi-tenant box the pattern differs: set listen.owner to the site’s own user and listen.group to the web server’s group, keeping 0660. The web server can connect, the site owns its socket, and no other site’s user can reach it. That per-pool design is covered in PHP-FPM pool isolation per site; what matters here is that only a socket supports it.
4. Point the web server at the socket. For nginx:
location ~ \.php$ {
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
fastcgi_pass unix:/run/php/php8.3-fpm.sock;
}
For Apache with mod_proxy_fcgi, the socket form uses the proxy:unix: prefix and still needs a dummy fcgi:// authority after the pipe:
<FilesMatch \.php$>
SetHandler "proxy:unix:/run/php/php8.3-fpm.sock|fcgi://localhost/"
</FilesMatch>
The pipe and the trailing slash are both load-bearing; the surrounding vhost details are in running PHP-FPM behind Apache with mod_proxy_fcgi.
5. Reload, then confirm the socket appeared with the ownership you asked for. PHP-FPM recreates the socket on start, so mistakes become visible here.
sudo systemctl reload php8.3-fpm
ls -l /run/php/php8.3-fpm.sock
srw-rw---- 1 www-data www-data 0 Sep 8 09:12 /run/php/php8.3-fpm.sock
That s at the front means it is a socket. If the owner or group is root, the directives did not take effect — check you edited the pool file the master actually loaded, not a .conf.bak or a second pool claiming the same path.
6. Configure the TCP form when the topology requires it. Bind to a specific address, never to 0.0.0.0, unless a private interface is genuinely the only path and you have a firewall in front of it.
listen = 127.0.0.1:9000
listen.backlog = 511
listen.allowed_clients = 127.0.0.1
For a remote node, listen takes that node’s private address and listen.allowed_clients takes a comma-separated list of web server addresses. It is an address filter inside PHP-FPM, evaluated after the connection is accepted, and it applies to TCP pools only — a socket ignores it. Treat it as defence in depth behind a firewall rule, not as the firewall.
On the nginx side, reuse connections instead of opening a new one per request. This is the single change that removes most of TCP’s disadvantage:
upstream php_backend {
server 127.0.0.1:9000;
keepalive 32;
}
location ~ \.php$ {
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
fastcgi_pass php_backend;
fastcgi_keep_conn on;
}
Without fastcgi_keep_conn on, nginx tells the FastCGI server not to keep the connection and the keepalive directive above it does nothing.
7. Size the backlog against the kernel, not against a blog post. listen.backlog is the second argument to listen(), and the kernel silently caps it at net.core.somaxconn. Setting 4096 on a host where somaxconn is 128 gives you 128.
sysctl net.core.somaxconn
echo 'net.core.somaxconn = 1024' | sudo tee /etc/sysctl.d/99-php-fpm.conf
sudo sysctl --system
sudo systemctl restart php8.3-fpm
A backlog change needs a restart, not a reload: the listening socket is created once, and reload does not recreate it.
8. Measure it on your own box, if you measure it at all. A number from another host tells you nothing. Use a script that does almost no work, so you are timing the transport rather than the application:
printf '%s' '<?php echo "ok";' | sudo tee /var/www/html/bench.php
wrk -t4 -c64 -d60s --latency http://127.0.0.1/bench.php
Run it A, B, A, B — socket, TCP, socket, TCP — restarting between runs and discarding the first 30 seconds of each so opcache is warm. Keep pm.max_children and every other pool setting identical. Read the p95 and p99 lines from --latency, not the mean, which hides exactly the effect you are looking for. And watch the FPM status page during the run: measuring a worker shortage instead of a transport is the usual way this experiment goes wrong.
Validate it works
Confirm the whole path end to end, not just that the service started.
curl -sS -o /dev/null -w '%{http_code} %{time_total}\n' http://127.0.0.1/bench.php
sudo tail -n 20 /var/log/nginx/error.log
ss -lnt '( sport = :9000 )'
200 0.004312
An empty nginx error log tail is the real success signal. For a TCP pool, ss -lnt should show Recv-Q at or near 0 — that column is the current depth of the accept queue, and a persistently non-zero value means requests are waiting for a worker to call accept(). Send-Q on the same line is the effective backlog after the somaxconn cap, the fastest way to confirm step 7 worked.
Then check the kernel’s own opinion, which only exists for TCP:
nstat -az TcpExt.ListenOverflows TcpExt.ListenDrops
netstat -s | grep -i 'listen queue'
Both should stay flat across a load test. There is no equivalent for AF_UNIX: a socket pool that overflows its backlog leaves evidence in the nginx error log and in the max listen queue field of the FPM status page, and nowhere else.
Troubleshooting
connect() to unix:/run/php/php8.3-fpm.sock failed (13: Permission denied), surfacing as a 502. The web server user cannot open the socket. Compare ls -l on the socket with the web server’s user: either listen.group does not match, or listen.mode is 0600. Fix the directives and restart FPM rather than chmod’ing the socket by hand: FPM recreates it on every start and will undo you. If mode and ownership look correct under SELinux, check ausearch -m avc -ts recent.
connect() ... failed (11: Resource temporarily unavailable). The accept queue is full: FPM has no idle worker and the backlog filled behind it. Raising listen.backlog buys queueing time, not capacity — it turns a fast 502 into a slow response. Revisit pm.max_children and the slow log first. Confirm with Recv-Q in ss -lnt for a TCP pool, or max listen queue on the status page for either.
connect() ... failed (2: No such file or directory) or (111: Connection refused). The path in the vhost does not match listen in the pool, or a stale socket survived a pool being renamed or removed — FPM does not clean up sockets belonging to pools that no longer exist. Compare grep -rn '^listen' in the pool directory against grep -rn fastcgi_pass in the vhosts, delete orphaned .sock files, and restart.
connect() to 127.0.0.1:9000 failed (99: Cannot assign requested address). Ephemeral port exhaustion on loopback. Every closed FastCGI connection holds its four-tuple in TIME_WAIT for 60 seconds, and 60 seconds of churn at a few thousand connections per second will outrun net.ipv4.ip_local_port_range.
ss -tan state time-wait | wc -l
sysctl net.ipv4.ip_local_port_range net.ipv4.tcp_tw_reuse
Enable connection reuse in nginx first (fastcgi_keep_conn on with keepalive): that removes the churn rather than absorbing it. net.ipv4.tcp_tw_reuse set to 2 permits reuse for loopback traffic and is a reasonable second step. Do not go looking for tcp_tw_recycle — it was removed in Linux 4.12. On a single host the cleanest fix remains the socket, which has no ports to exhaust.
A remote pool answers nothing and PHP-FPM logs a connection-disallowed error naming the client IP. listen.allowed_clients does not include the web server’s source address. It matches the address the connection actually arrives from, which behind NAT or a container bridge is not the address configured on the web server. Read the rejected IP out of the FPM error log and use that value.
When this is the wrong approach
A socket is not an option when PHP-FPM and the web server cannot see the same filesystem path: separate hosts, or separate containers without a shared volume. Sharing one between containers means a shared mount and matching numeric UID and GID on both sides, because usernames do not cross a container boundary — workable for a sidecar in one pod with an emptyDir, a poor idea across anything larger.
A socket is also wrong when you need more than one FPM instance behind a single entry point. nginx upstream blocks with multiple server lines, health checks and weights need addresses; you cannot balance across socket paths.
On some managed platforms the transport is not yours to choose. Control panels that generate pool and vhost config rewrite whatever you set on the next build, so changing it means changing the template rather than the file. If the panel writes TCP on loopback with a per-site port, that is defensible, not something to fight.
And if you came here hoping the socket would fix a latency problem, it will not. A transport change moves tens of microseconds. If your p95 is bad, the answer is in pool sizing, the opcode cache or the database, and switching listen only makes it harder to tell what changed.
Every directive on this page is documented in the PHP-FPM configuration manual, and the nginx side in the ngx_http_fastcgi_module reference.
If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.