0
0
NginxDebug / FixBeginner · 4 min read

How to Fix 504 Gateway Timeout Error in Nginx

A 504 gateway timeout in nginx happens when the server waits too long for a response from an upstream server. To fix it, increase the proxy_read_timeout and fastcgi_read_timeout values in your nginx.conf or optimize your backend to respond faster.
🔍

Why This Happens

A 504 gateway timeout error occurs when nginx acts as a middleman but does not get a timely response from the backend server or service it is trying to reach. This can happen if the backend is slow, overloaded, or unreachable. The default timeout settings in nginx are often too low for long-running requests.

nginx
location / {
    proxy_pass http://backend_server;
    proxy_read_timeout 30s;
}
Output
504 Gateway Timeout
🔧

The Fix

Increase the timeout values so nginx waits longer for the backend response. This prevents premature timeout errors. Also, check your backend server to ensure it can handle requests efficiently.

nginx
location / {
    proxy_pass http://backend_server;
    proxy_read_timeout 120s;
    proxy_connect_timeout 60s;
    proxy_send_timeout 60s;
}

location ~ \.php$ {
    fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
    fastcgi_read_timeout 120s;
}
Output
Successful response from backend without 504 error
🛡️

Prevention

To avoid 504 errors in the future, monitor your backend server's performance and optimize slow queries or processes. Use health checks and load balancing to distribute traffic evenly. Regularly review and adjust nginx timeout settings based on your application's needs.

⚠️

Related Errors

Other common errors include:

  • 502 Bad Gateway: Happens when nginx cannot connect to the backend server.
  • 503 Service Unavailable: Backend server is overloaded or down.
  • 504 Gateway Timeout: Backend server took too long to respond.

Quick fixes involve checking backend availability, increasing timeouts, and ensuring network connectivity.

Key Takeaways

Increase proxy_read_timeout and fastcgi_read_timeout in nginx to fix 504 errors.
Ensure your backend server responds quickly and is not overloaded.
Use load balancing and health checks to improve backend reliability.
Monitor and adjust timeout settings regularly based on traffic and backend performance.