Understanding 504 Gateway Timeout
Nginx/Apache waited too long for a response from the backend (PHP-FPM, database, external API).
Default timeout is often 60 seconds.
Fix 1: Increase PHP Execution Time
In php.ini:
max_execution_time = 300
max_input_time = 300
Or in PHP-FPM pool:
request_terminate_timeout = 300
Restart PHP-FPM.
Fix 2: Increase Nginx Timeouts
Edit site config:
proxy_read_timeout 300s;
proxy_connect_timeout 300s;
proxy_send_timeout 300s;
fastcgi_read_timeout 300s;
Test and reload:
sudo nginx -t
sudo systemctl reload nginx
Fix 3: Optimize Slow Scripts
Identify slow queries/endpoints:
# Enable slow log in PHP
slowlog = /var/log/php-slow.log
request_slowlog_timeout = 5
Check database slow queries:
sudo tail -f /var/log/mysql/mysql-slow.log
Fix 4: Check External API Calls
If your script calls external APIs, implement caching or async processing.
Fix 5: Resource Bottlenecks
top
free -h
iostat -x 1
Upgrade VPS if consistently hitting limits.
Fix 6: For File Uploads
Increase client_max_body_size and timeouts for large uploads:
client_max_body_size 100M;
proxy_read_timeout 600s;
💡 Long-term: Optimize database queries and implement async job queues for heavy processing.