0
0
NginxDebug / FixBeginner · 4 min read

How to Fix Upstream Timed Out Error in Nginx

The upstream timed out error in Nginx happens when the backend server takes too long to respond. To fix it, increase the proxy_read_timeout and proxy_connect_timeout values in your Nginx configuration to allow more time for the backend to respond.
🔍

Why This Happens

This error occurs because Nginx waits for a response from the backend server (like an application or database) but the server takes longer than the set timeout. Nginx then stops waiting and shows the upstream timed out error.

Common reasons include slow backend processing, network delays, or too low timeout settings in Nginx.

nginx
location /api/ {
    proxy_pass http://backend_server;
    proxy_connect_timeout 5s;
    proxy_read_timeout 5s;
}
Output
504 Gateway Timeout "upstream timed out" error in Nginx logs
🔧

The Fix

Increase the timeout values so Nginx waits longer for the backend response. This helps when the backend needs more time to process requests.

Adjust proxy_connect_timeout to allow more time to connect, and proxy_read_timeout to wait longer for data.

nginx
location /api/ {
    proxy_pass http://backend_server;
    proxy_connect_timeout 30s;
    proxy_read_timeout 60s;
}
Output
Backend response received successfully without timeout
🛡️

Prevention

To avoid this error in the future:

  • Monitor backend server performance and optimize slow queries or code.
  • Set reasonable timeout values in Nginx based on your backend's typical response times.
  • Use health checks to detect slow or unresponsive backend servers early.
  • Consider load balancing to distribute requests evenly.
⚠️

Related Errors

Other errors similar to upstream timed out include:

  • 502 Bad Gateway: Nginx cannot connect to the backend server.
  • 503 Service Unavailable: Backend server is down or overloaded.
  • 504 Gateway Timeout: Nginx timed out waiting for the backend response (similar to upstream timed out).

Fixes usually involve checking backend health, network connectivity, and adjusting timeouts.

Key Takeaways

Increase proxy_read_timeout and proxy_connect_timeout in Nginx to fix upstream timeouts.
Slow backend responses often cause upstream timeout errors.
Monitor and optimize backend server performance to prevent timeouts.
Use health checks and load balancing to improve backend reliability.
Related errors like 502 and 503 also indicate backend connection issues.