How to Fix Upstream Timed Out Error in Nginx
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.
location /api/ {
proxy_pass http://backend_server;
proxy_connect_timeout 5s;
proxy_read_timeout 5s;
}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.
location /api/ {
proxy_pass http://backend_server;
proxy_connect_timeout 30s;
proxy_read_timeout 60s;
}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
proxy_read_timeout and proxy_connect_timeout in Nginx to fix upstream timeouts.