Nginx 504 Gateway Timeout
Nginx didn't receive a response from the upstream server within the timeout period.
Explanation
Nginx 504 Gateway Timeout means the upstream server (PHP-FPM, Node.js, etc.) took too long to respond to Nginx. Unlike 502 where the response was invalid, 504 means the backend is processing but exceeding the allowed time. This commonly happens with long-running database queries, external API calls, file processing, or a backend that's hanging. The default Nginx timeout is typically 60 seconds. High server load or resource exhaustion can also cause timeouts.
Common Causes
- Backend processing too slow
- Slow database queries
- External API timeouts
- Server resource exhaustion
- Timeout settings too low
Solution
Increase Nginx timeout settings: proxy_read_timeout, fastcgi_read_timeout. Optimize the backend code to respond faster (add indexes, cache results, reduce external calls). Check for slow database queries with slow query log. Increase PHP max_execution_time if PHP is the bottleneck. Monitor server resources (CPU, memory, disk I/O). Add caching layers (Redis, Varnish, Nginx cache). Consider queuing long-running tasks instead of processing in the request cycle. Use load balancing to distribute traffic across multiple backends.
Code Example
# Increase Nginx timeouts
# /etc/nginx/sites-available/myapp
location ~ \.php\$ {
fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
fastcgi_read_timeout 300; # 5 minutes
fastcgi_send_timeout 300;
proxy_read_timeout 300;
}
location /api/ {
proxy_pass http://127.0.0.1:3000;
proxy_read_timeout 300;
proxy_connect_timeout 60;
}
# Increase PHP timeout
# /etc/php/8.2/fpm/php.ini
max_execution_time = 300
# Or in .htaccess (Apache)
# max_execution_time = 300
# Check for slow queries
# MySQL: SET GLOBAL slow_query_log = 1;
# tail -f /var/log/mysql/slow-query.log
# Monitor server resources
top
htop
iostat -x 1
# Nginx cache for static responses
location /static/ {
proxy_cache_valid 200 1d;
expires 1d;
}
Error Information
Language
bash
Framework
nginx
Difficulty
Intermediate
Views
411
Related Errors
DevOps
Terraform State Locked
Another Terraform operation is already running and has locked the state file.
General
Git Merge Conflict
Git cannot automatically merge changes from two branches because they modified the same lines.
DevOps
Laravel Schedule Task Failure
A scheduled task failed to execute or completed with errors.
ENOSPC
DevOps
Out of Disk Space
The system or application ran out of disk space.