nginx 504 gateway time-out

A 504 gateway time-out error occurs when Nginx cannot receive a response from the service long enough. For example from PHP-FPM.

Nginx and PHP-FPM

The most common cause of this error is the collaboration of Nginx and PHP-FPM. In case there are very slow PHP scripts, Nginx will give a 504 gateway time-out when it does not wait for an answer for 30 seconds (by default).

To get rid of this error, try raising the timeout:

location ~ \.php$ {
  fastcgi_pass unix:/tmp/php5-fpm.sock;
  fastcgi_index index.php;
  fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
  include fastcgi_params;
  fastcgi_read_timeout 300;
}

Proxy

504 gateway time-out may also occur when Nginx is used as a proxy server. For example, when working with Apache. In order to avoid problems, you need to configure the timeout settings for proxy:

server {
...
    proxy_connect_timeout       600;
    proxy_send_timeout          600;
    proxy_read_timeout          600;
    send_timeout                600;
...
}

Do not forget to restart Nginx after changing the settings:

# nginx -s reload

It is important to understand that it is highly advisable to get rid of slow scripts. A solution with timeout settings may stop working when the load increases.

Related Post