How to Fix 504 Gateway Timeout Error in Nginx
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.
location / {
proxy_pass http://backend_server;
proxy_read_timeout 30s;
}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.
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;
}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
nginxcannot 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
proxy_read_timeout and fastcgi_read_timeout in nginx to fix 504 errors.