DEV3 Technologies home

DEV3 Developer Forum

How do I fix "502 Bad Gateway" from Nginx with PHP-FPM or a Node upstream?

DevOps helpSolved0 views
dev3 ·

Nginx returns 502 Bad Gateway intermittently. The error log says "connect() to unix:/run/php/php8.3-fpm.sock failed (2: No such file or directory)" or "upstream prematurely closed connection".

#nginx#502#troubleshooting

0

1 reply

dev3 · Accepted answer

502 means Nginx reached for the upstream (PHP-FPM, Node, Gunicorn) and got no valid response. The error log says why; match your message.

1. connect() ... failed (2: No such file or directory) The socket path is wrong or PHP-FPM is down.

systemctl status php8.3-fpm
ls /run/php/
grep -R "fastcgi_pass" /etc/nginx/sites-enabled/

Make the path match the installed version (updating PHP changes the socket name).

2. (13: Permission denied) Nginx's user cannot access the socket. In the PHP-FPM pool (/etc/php/8.3/fpm/pool.d/www.conf) set listen.owner = www-data, listen.group = www-data, listen.mode = 0660, and make Nginx run as www-data.

3. upstream prematurely closed connection The PHP worker crashed or was killed: memory exhaustion, a segfault from an extension, or request_terminate_timeout. Check /var/log/php8.3-fpm.log and dmesg | grep -i killed.

4. connect() failed (111: Connection refused) for TCP upstreams The app is not listening on that port. Start it, check ss -ltnp | grep 3000, and make the proxy target match.

5. Intermittent 502 under load The pool ran out of workers (server reached pm.max_children appears in the FPM log). Tune:

pm = dynamic
pm.max_children = 20
pm.start_servers = 4
pm.min_spare_servers = 2
pm.max_spare_servers = 6

Pick max_children from available RAM divided by average worker memory (ps --no-headers -o rss -C php-fpm8.3). Too high a value causes swapping and OOM kills.

6. Slow requests may give 504 instead: raise fastcgi_read_timeout, but also fix the slow code.

Reload after edits: sudo nginx -t && sudo systemctl reload nginx.

0

Your reply

Every post is reviewed by DEV3 before it appears. Usually reviewed within 24 hours.

Markdown supported. Use ``` for code blocks. Images are not allowed.