Home / Localhost / nginx 502 Bad Gateway

nginx 502 Bad Gateway: causes and how to fix it

Fix nginx 502 Bad Gateway with Node, PHP-FPM or any proxy: read the error log, check the app is running and the port or socket matches.

A 502 Bad Gateway means nginx is working but the program behind it did not answer properly. The error log tells you exactly why, so start there.

What to do, step by step

  1. Open the nginx error log and read the last lines: sudo tail -n 30 /var/log/nginx/error.log.
  2. If it says connect() failed (111: Connection refused), your app is not running or not on that address and port.
  3. Check the app is up and listening: sudo ss -tlnp and look for the port from your proxy_pass line.
  4. For PHP, check PHP-FPM runs and that fastcgi_pass matches its socket or port.
  5. Fix the cause, then reload nginx: sudo nginx -t && sudo systemctl reload nginx.

Commands you can copy

Read the newest errors
sudo tail -n 30 /var/log/nginx/error.log
See what listens on which port
sudo ss -tlnp
Test, then reload the config
sudo nginx -t && sudo systemctl reload nginx

Other causes to check

(13: Permission denied) while connecting to upstream
nginx cannot open the socket or port. For a socket file, check its owner and mode (listen.owner and listen.group in the PHP-FPM pool). On SELinux systems run sudo setsebool -P httpd_can_network_connect 1.
(110: Connection timed out) or upstream timed out
The app answers too slowly. Find out why it is slow, or raise proxy_read_timeout (or fastcgi_read_timeout for PHP).
Works for a while, then 502
The app crashed or ran out of memory. Check its own logs and use a process manager such as systemd or PM2 to restart it.
upstream sent too big header
Large cookies or headers. Raise proxy_buffer_size and proxy_buffers, or send smaller headers.
PHP: connect() to unix:/run/php/php8.3-fpm.sock failed (2: No such file or directory)
The socket path is wrong for your PHP version. List the sockets with ls /run/php/ and use the real file name.

Questions about nginx 502 Bad Gateway

What is the difference between 502 and 504?
A 502 means nginx got no usable answer from your app. A 504 means the app took too long. The error log says which one happened and why.
Is a 502 an nginx bug?
Almost never. It points to the app or the connection to it. nginx only reports that it could not get an answer.
Where is the nginx error log?
Usually /var/log/nginx/error.log. Your server block may set a different path with the error_log line.

Updated 2026-10-11

Free tools that help

Config generators for this

Related pages