Nginx – I can’t avoid 504 gateway time-out

504nginxPHP

In order to avoid the nginx 504 gateway time-out, I've tried to do this in the beginning of my PHP code:

set_time_limit(0);

Also, I've tried to raise the time settings at /etc/php/7.0/fpm/php.ini:

max_execution_time = 3600
max_input_time = 3600

And at /etc/php/7.0/fpm/pool.d/www.conf:

request_terminate_timeout=3600

After restarting nginx, I am still getting 504 gateway time-out before 3600 seconds on requests.

What more should I do to avoid it definitely?

Best Answer

Nginx and Apache with the performant MPM-Event worker are using a dedicated daemon (service) to run PHP. You have already configured this daemon in the right way. But now you have to configure the web server to wait for such a long time. The magic setting can be done with the setting fastcgi_read_timeout.

Configure Nginx to wait some time ...

location ~ \.php$ {

  # allow logging
  access_log              /var/log/nginx/access.log vhosts;

  # include defaults
  include                 fastcgi_params;

  # define connection to php-fpm
  fastcgi_keep_conn       on;
  fastcgi_pass            unix:/var/run/php5-fpm.sock;
  fastcgi_index           index.php;

  # php script name
  fastcgi_param           SCRIPT_FILENAME  $document_root$fastcgi_script_name;
  fastcgi_param           SCRIPT_NAME      $fastcgi_script_name;

  # set buffers
  fastcgi_buffer_size             128k;
  fastcgi_buffers                 256 16k;
  fastcgi_busy_buffers_size       256k;
  fastcgi_temp_file_write_size    256k;

  # allow web-server to wait for a long time before giving up
  fastcgi_read_timeout            3600s;

}

I cannot recommend to activate this setting for a public accessible web server.

If there is a task which needs some time - you should do this task via CLI (command line interface) instead. A good example could be the generation of a Google sitemap.xml of a huge website.

Example:

Execute the script via command line ...

cd /var/www/mysite/ ; php generateSitemap.php

Define a cronjob to execute the script daily via command line ...

0 4 * * *    cd /var/www/mysite/ ; php generateSitemap.php