504 Gateway Timeout in nginx

A 504 Gateway Timeout means nginx reached your application, but the application took too long to respond. Unlike a 502, the backend is alive, it is just slow.

Mark van Eijk 1 minute read Errors
  1. About error 504
  2. Why do I see this error
  3. Solution

About error 504

A 504 Gateway Timeout is returned when nginx, acting as a reverse proxy, successfully connects to the upstream server but does not receive a complete response within the configured timeout window.

This is the key difference with a 502 Bad Gateway: with a 502 the backend gave a bad or no connection, with a 504 the connection was fine but the response never arrived in time.

Why do I see this error

The backend is taking longer than nginx is willing to wait. Common reasons:

  • A slow database query or a missing index.
  • A long running job (report generation, export, image processing) handled inside the request instead of a queue.
  • A slow external API call the request depends on.
  • PHP's own max_execution_time is lower than the work needs.

By default nginx waits 60 seconds (proxy_read_timeout for proxied apps, fastcgi_read_timeout for PHP-FPM) before giving up.

Solution

For a PHP-FPM application, raise the FastCGI read timeout in your server or location block:

location ~ \.php$ {
    fastcgi_pass unix:/run/php/php8.3-fpm.sock;
    fastcgi_read_timeout 120s;
    include fastcgi_params;
}

For a proxied application (Node, Octane, a separate service), raise the proxy timeouts instead:

location / {
    proxy_pass http://127.0.0.1:8000;
    proxy_read_timeout 120s;
    proxy_send_timeout 120s;
}

PHP has its own limit too, so raise that as well or nginx will outwait a script that PHP already killed:

; php.ini
max_execution_time = 120

Reload after changing the configuration:

systemctl reload nginx
systemctl reload php8.3-fpm

Raising timeouts is a bandage, not a cure. The real fix is to make the request fast: add the missing database index, or move slow work (emails, exports, third-party calls) into a background queue so the request returns immediately. See optimizing server performance for more.