CH-J Toolsserver management over SSH
Menu
All guides and articles →

NGINX 502 Bad Gateway: Causes and Solutions

Find the layer that is generating the 502 and verify the connection to the backend. HTTP proxy, PHP-FPM, Unix sockets, TLS and secure patching according to the specific log.

502 indicates a gateway problem but does not identify its cause

HTTP 502 means that a server acting as a gateway or proxy received an invalid response while handling a request through another server. In normal NGINX operation, you might see this status when the backend is unavailable or the connection is prematurely terminated. However, the page with the number alone does not determine whether the error was caused by your NGINX, an upstream service, or the application directly behind it.

First, draw the actual flow: client, possible CDN, reverse proxy, web server, PHP-FPM or application process and other dependencies. IPv4 and IPv6 can lead elsewhere. An error on only one domain or URL can point to a specific server block, location or upstream. Don't start by changing all timeouts and restarting all services.

Before fixing, record the time, method, destination URL without secret parameters, and status code. Do not retry the user's POST or payment as a diagnostic test. For basic reproduction, choose a safe GET to a known read path. The actual error page and Server header are clues, but not definitive proof, of which layer decided the status.

Link a specific request to an access and error log

Find the actual logs used and their timezone. The path /var/log/nginx/error.log is a common example, not a guarantee for every vhost. The logs can be separate, sent to the stderr container, or to another service. If the first file does not have the relevant event, verify the logging configuration and the correct server instead of assuming that NGINX knows nothing.

date -Is
sudo tail -n 80 /var/log/nginx/error.log
sudo journalctl -u nginx.service --since "-15 min" --no-pager
# Případná kontrola účinné konfigurace pouze v neveřejném prostředí:
sudo nginx -T

Nginx -T can list private addresses and configuration values. Do not share the entire output without checking. Search for a specific server_name, location, proxy_pass or fastcgi_pass and link to the logs. It is important to find the actual matching branch, as a generic upstream of the same name in a different file may not serve your request.

  • Connection refused when connect() to upstream: check the address, port, and running backend.
  • No such file or directory for Unix socket: verify the path and creation of the socket.
  • Permission denied when connecting: check path traversal and worker permissions.
  • Upstream prematurely closed connection or invalid header: look for a crash, incorrect protocol, or invalid backend output.

HTTP backend: listener is not enough, you need the right application

If proxy_pass points to a TCP endpoint, verify that it is actually listening and serving. A loopback on one machine is not a loopback to another container. Port 8080 may hold a different program than you expect. Therefore, compare the process identity and address with the configuration of the given upstream.

sudo ss -lntp 'sport = :8080'
systemctl status APLIKACE.service --no-pager
sudo journalctl -u APLIKACE.service --since '-15 min' --no-pager

# Příklad jen pro známý HTTP backend a bezpečnou čtecí cestu:
curl --max-time 5 -sS -D - -o /dev/null \
  -H 'Host: aplikace.example' http://127.0.0.1:8080/health

Replace the unit name and path /health with actual values. A direct successful request is useful, but must match the original host, path, and handling. The health endpoint may be fine while a specific application path fails on the database. Don't assume that a basic 200 acknowledges every type of request.

For dynamic addresses, such as behind container DNS, consider the actual resolver configuration and upstream lifecycle. The fix is not to randomly rewrite the name to the historical IP. First, verify where NGINX is resolving the name and what configuration recovery method your particular deployment is using.

PHP-FPM and Unix socket: two services, one concrete path

PHP often uses fastcgi_pass on a Unix socket. PHP-FPM must be running, create a socket on the expected path, and allow access to the NGINX worker account. The main NGINX process may run as root, but requests are served by workers with different privileges. Therefore, checking from the root shell alone is not enough to explain Permission denied.

sudo systemctl status php8.3-fpm.service --no-pager
sudo journalctl -u php8.3-fpm.service --since "-15 min" --no-pager
sudo ss -xlnp
namei -l /run/php/php8.3-fpm.sock
ls -l /run/php/php8.3-fpm.sock

Adjust the service and socket versions according to your installation. Compare listen in the FPM pool and fastcgi_pass in NGINX. The listen.owner, listen.group, listen.mode or ACL parameters must match the intended access. Creating a plain empty file with the same name will not fix a missing socket. You need a running correct service that serves the actual socket.

FPM is not an HTTP server and you cannot send a plain HTTP curl to its FastCGI endpoint and expect a valid web response. Verify it via the correct protocol and established pool diagnostics. Do not expose FPM status or diagnostic scripts publicly just for a quick confirmation of status.

Incorrect protocol, TLS, and script path

HTTP, HTTPS, and FastCGI are not interchangeable communication methods. Proxy_pass with http on a backend requiring TLS may result in an invalid or terminated response. Fastcgi_pass expects FastCGI, not a regular web port. After migrating a service, compare both the protocol and the port, not just the IP address.

# Příklad testu známého HTTPS backendu se správným jménem a SNI:
curl --max-time 5 --resolve aplikace.example:8443:127.0.0.1 \
  -sS -D - -o /dev/null https://aplikace.example:8443/health

If TLS fails, check the trust, expected name, and SNI against the backend connection policy. Disabling certificate verification is not a general fix. Also, do not confuse the proxy public certificate with the backend certificate: these are two different connections and their trust settings may be different.

For PHP, check SCRIPT_FILENAME, document root, and any chroot or immutable publish revision. An incorrect path may return a status other than 502 depending on the entire configuration. So don't automatically resolve a File not found message with the same treatment as a socket connection refused. Determine who created the response and whether FPM actually received the correct script.

Intermittent 502: process crash and capacity have a different solution than a typo

If most requests work, compare failure times to backend restarts, deploying a new revision, running out of memory, or reaching the number of workers. Premature termination can be the result of a crash, a graceful exit, or an application bug. It is not safe to automatically conclude from a single line that increasing pm.max_children is enough.

uptime
free -h
sudo journalctl -k --since "-30 min" --no-pager
systemctl show APLIKACE.service -p NRestarts -p Result -p MemoryCurrent

Increase the number of workers only if you have the memory for them and the application can handle higher concurrency. Otherwise, you can make the queue OOM and even more aborted responses. Also check the application limits and database in place. Repeated restarts without logging the cause may help briefly, but will remove useful context and may not fix the failure.

If the response has already started to go to the client, a later error may not change the previously sent status to 502. The client may receive truncated content even with the original 200. Therefore, if you suspect an interruption, also monitor the completeness of the response and transmission errors, not just the sum of the status codes in the overview.

Apply the fix in a targeted manner and verify it with a new request

Before changing, back up the specific file and write down the reason. For NGINX, perform a syntax check and only use reload after it is successful. The syntax check does not check the live availability of the upstream, the permissions on each file, or the meaning of all application parameters. Therefore, an actual new request must follow.

sudo nginx -t
# Až po úspěšné kontrole a v rámci schválené změny:
sudo systemctl reload nginx.service

In CH-J Tools, you can use the terminal, log check, and available NGINX Manager features to manage the configuration depending on the application version. However, the result is confirmed by the actual server. A successful file save or a green syntax test does not mean that the backend is responding correctly.

  • The originally failing secure request will now pass through the same public path.
  • The direct backend and proxy correspond to the intended protocol and host.
  • The same error does not appear in the corresponding error log.
  • Important neighboring vhosts are running and socket rights have not been extended to all.
  • For intermittent failure, the test was performed over an appropriate load or repetitive operating cycle.

When to pass on findings

If the cause remains unclear, provide the exact time, the relevant URL without sensitive parameters, the status, and a small anonymized error log snippet. Attach a path map and verified direct backend test results. This is more actionable than a general statement that "the server is down" and will allow the application administrator to follow up on the same request.

Do not label increasing the timeout as a fix for a rejected connection. If the backend is not listening on the address, waiting longer will not produce the correct service. Similarly, chmod 777 is not a solution for incorrect socket ownership, and disabling TLS authentication does not fix incorrect identity. Any change should be specific to the confirmed problem.

Frequently asked questions

Is 502 always a PHP-FPM error?

No. It can be created by a different proxy layer or application. First, determine the actual flow and the corresponding error log.

Will increasing proxy_read_timeout help when Connection refused?

No. A rejected connection requires checking the address, port, listener, and backend. The timeout is a different issue.

Can I test an FPM socket with plain HTTP curl?

Not as an HTTP service. FPM uses FastCGI and the test must match that protocol or a working web path.

Why did nginx -t pass and the website still returns 502?

The check verifies the configuration, not the full behavior of the backend in operation. You also need the actual request and related logs.

Detailed documentation

NGINX: HTTP proxy →

NGINX: FastCGI and script parameters →

PHP: configuring FPM pools and sockets →

IETF RFC 9110: status 502 Bad Gateway →

Biometric unlock and security →

All tutorials by category →