Gateway timeout php fpm

Increase PHP script execution time with Nginx

If you have a large WordPress setup or a server with limited resources, then you will often see the “504 Gateway Time-out” error.

You can follow the steps given below to increase the timeout value. PHP default is 30s.

Changes in php.ini

If you want to change max execution time limit for php scripts from 30 seconds (default) to 300 seconds.

In Apache, applications running PHP as a module above would have suffice. But in our case we need to make this change at 2 more places.

Changes in PHP-FPM

This is only needed if you have already un-commented request_terminate_timeout parameter before. It is commented by default, and takes value of max_execution_time found in php.ini

vim /etc/php5/fpm/pool.d/www.conf
request_terminate_timeout = 300

Changes in Nginx Config

To increase the time limit for example.com by

vim /etc/nginx/sites-available/example.com

If you want to increase time-limit for all-sites on your server, you can edit main nginx.conf file:

Add following in http section

Reload PHP-FPM & Nginx

Don’t forget to do this so that changes you have made will come into effect:

service php5-fpm reload service nginx reload

More

Share this:

Like this:

21 responses to “Increase PHP script execution time with Nginx”

Have you see this where you receive a HTTP 499 response from NginX rather than a 504? I’m having that problem with an AWS instance where I have a PHP script which terminates after 60 seconds. The script is I’ve increased the PHP execution time to 360 seconds as well as the fast_cgi_timeout but it still fails after 60 seconds. The script works from the command line though

@Steve I think you may find this helpful – http://stackoverflow.com/questions/15613452/nginx-issues-http-499-error-after-60-seconds-despite-config-php-and-aws If that doesn’t work, can you paste relevant lines from nginx error_log? There are many kind of timeouts there…

If you look into the php.ini file for “max_execution_time” you’ll see this note: Note: This directive is hardcoded to 0 for the CLI SAPI Therefore your script will never run out of time when you call it on the command line.

I am aware of CLI. This article is for CGI and FPM. This article is part of WordPress-Nginx series – http://rtcamp.com/series/wordpress-nginx-tutorials/.

Hi, We have been receiving this 504 Gateway Timeout using Nginx the last few days on our site. We have php handler DSO (as opposed to Fast CGI) running on our server. Does the above configuration tweak apply to server running DSO as php handler? Please advise.

Читайте также:  Form html css примеры

I am having issue when I do simple form submission using post action. I am getting 504 Gateway time out error
Max_execution_time is set to 120 and we are using fast-cgi
$_POST array is blank. Can you please help me in resolving this issue

Your PHP scripts might be taking more than 120 seconds.
$_POST could be blank because of many possible reasons (considering you are debugging a POST request) Did you install Nginx & PHP by following our tutorials https://rtcamp.com/tutorials/linux/ubuntu-php-mysql-nginx-postfix/ or simply use https://rtcamp.com/easyengine/

If i setup diffrent max execution time in php-fpm ,nginx and php.ini, then which will take in execution?

As far as I know, if the execution time on nginx-sides runs out, the php script will still be running in the background, but the user will get the “504 Gateway timeout”-error. On the other side, hitting the max-execution time for php-fpm or in php itself will kill the process, write something into the PHP log file (like “PHP Fatal error: Maximum execution time of XX seconds exceeded in”…). I don’t know what the fpm would write into the log, but it (for sure) will kill the php process. Just as a hint: I had some thoughts what would happen if you are uploading files … should the time for nginx include the time the user needs to upload data? If php is running as FastCGI process (as it is here), the answer is NO.
See: http://stackoverflow.com/questions/16064282/nginx-when-is-the-fastcgi-proxy-triggered-after-request-header-or-after-reques/16187165#16187165

Error message could be different but whoever dies first will break the chain. About uploads, normal HTTP file-uploaded are buffered at nginx-level. Sending them from nginx to PHP happens quite fast if PHP and Nginx are on same machine.

Источник

Увеличение времени выполнения PHP скрипта с Nginx

Увеличение времени выполнения PHP скрипта с Nginx

Если у вас есть большой проэкт или сервер с ограниченными ресурсами, то Вы будете часто видеть «504 Gateway Time-out» ошибку.

Вы можете выполнить приведенные ниже шаги, чтобы увеличить значение тайм-аута. В PHP по умолчанию 30 секунд.

Изменения в php.ini

Если вы хотите изменить максимальное время выполнения для PHP скриптов из 30 секунд (по умолчанию) до 300 секунд.

В Apache PHP работает как модуль, этих изменений будет достаточно. Но в нашем случае мы должны сделать изменения еще в нескольких местах.

Изменения в PHP-FPM

Это нужно, если Вы раскоментировали параметр request_terminate_timeout ранее. По умолчанию он закоментирован и берет значение max_execution_time found из php.ini

nano /etc/php5/fpm/pool.d/www.conf
request_terminate_timeout = 300

Изменения в Nginx Config

Увеличение time limit-а для одного домена example.com

nano /etc/nginx/sites-available/example.com

Если Вы хотите увеличить time-limit для всех доменов на вашем сервере, Вы можете отредактировать главный конфигурационный файл nginx.conf:

Добавить следующий параметр в http секцию

Перезагружаем PHP-FPM и Nginx

service php5-fpm restart service nginx restart

Установка Postgresql 9.4 Debian 7

Установка Postgresql 9.4 Debian 7 Wheezy Вышла новая версия PostgreSQL под…

Установка ImageMagick PHP на Debian/Ubuntu

Установка ImageMagick PHP на Debian/Ubuntu Установка пакета ImageMagick: apt-get install imagemagick…

Источник

Как исправить 504 gateway time out Nginx

Веб-сервер Nginx часто работает не только в качестве самого веб-сервера для отдачи контента, но и в качестве прокси, когда он вступает только посредником. Такая ситуация наблюдается намного чаще, чем можно было бы ожидать. Например, при работе с php-fpm и другими модулями динамических языков.

Читайте также:  Знакомство с GET-запросами

Именно в таком режиме может наблюдаться ошибка 504 gateway time out Nginx. В нашей сегодняшней статье мы попытаемся разобраться почему она возникает и как с ней бороться. Разберем несколько способов решения и причин.

Что значит 504 gateway time out Nginx?

Как я уже сказал, такая ошибка возникает, когда сервер Nginx работает в режиме прокси. Например, при использовании php-fpm или Apache. Дословно, она означает, что превышено время ожидания ответа от сервера. В нашем случае, превышено время ожидания ответа от php-fpm. Рассмотрим несколько причин такого поведения:

  • Скрипт PHP или на другом языке полностью завис и уже не вернет никакого ответа;
  • Скрипт работает очень долго, но в Nginx настроен интервал на сброс соединения если целевой сервер не ответил на запрос за отведенный строк;
  • Сервер перегружен и не успевает обслужить всех клиентов, вернуть ответы на все запросы Nginx;

Дальше рассмотрим что можно сделать если вы встретились с ошибкой 504 gateway time out Nginx.

Как исправить 504 gateway time out Nginx?

Самый первый вариант — это если вашему серверу, php-fpm или apache не хватает ресурсов системы, например, памяти или процессора. Вы можете посмотреть свободную память с помощью команды free:

Нагрузку на процессор можно узнать командой htop:

Естественно, если вы видите, что PHP занимает все процессорное время, то значит проблема в ресурсах сервера. Вы можете покопаться в движке своего сайта, пытаться оптимизировать те или иные моменты, об этом будет отдельная статья или же выбрать более мощный VPS сервер.

Второй вариант — это если так и было запланировано, чтобы скрипт работал долго. В таком случае нужно настроить Nginx, чтобы он дождался ответа от Apache или php-fpm. Для решения проблемы в случае с php-fpm нужно только добавить две строчки в блок настройки fastgci:

fastcgi_send_timeout 300;
fastcgi_read_timeout 300;

Здесь 300 означает 300 секунд, для большинства скриптов, этого будет вполне достаточно, но вы можете еще больше увеличить значение если это нужно. Также ошибка 504 может возникать, когда Nginx используется в качестве прокси для Apache или любого другого веб-сервера, тогда нужно еще настроить время ожидания для прокси. Добавьте эти строки в секцию server:

proxy_connect_timeout 600;
proxy_send_timeout 600;
proxy_read_timeout 600;
send_timeout 600;

Тут уже мы задаем таймаут 600 секунд для различных видов действий — подключения, отправки данных, чтения данных и так далее. После завершения настройки Nginx стоит перезапустить:

sudo systemctl restart nginx

Последний вариант, который мы рассмотрим — это скрипт завис. Если вы сами запускаете скрипт, то сразу увидите что зависло, но если такая ошибка встречается у пользователей, то это уже более серьезная проблема. Вы можете посмотреть встречаются ли вашим пользователям такие ошибки и где они встречаются с помощью команды:

fgrep -i » 504 » /var/log/nginx/access.log

Более подробную информацию иногда можно увидеть в error.log:

fgrep -i » 504 » /var/log/nginx/error.log

Дальше, если проблема именно в php-fpm, вы можете отследить какие скрипты выполняются медленно с помощью встроенной функции slow-log. Для ее активации добавьте следующие строки в конфигурацию вашего пула:

sudo vi /etc/php-fpm.d/www.conf

slowlog = /var/log/php-fpm/www-slow.log
request_slowlog_timeout = 5s

Здесь 5 секунд, означает, что в лог файл будут добавляться скрипты, которые выполняются дольше пяти секунд. Вы можете менять это значение по своему усмотрению. В логе вы сможете увидеть не только сами скрипты, но и трассировку методов, которые привели к проблемам:

Читайте также:  Variable and reference variable in php

Дальше останется только разобраться что с этим делать, например, оптимизировать скрипты или отключить лишние плагины.

Выводы

В этой статье мы рассмотрели как исправить 504 gateway time out Nginx 1.2 7, а также почему может возникнуть эта ошибка. Надеюсь, эта информация была полезной для вас.

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

How to Fix 504 Gateway Timeout in Nginx Server

I use NGINX a lot. I recently deployed a Node.js web application with NGINX as a reverse proxy server for it. One of the key features of the application is support for data imports using excel templates. However, it didn’t take long before users uploading bulky files started getting a 504 Gateway Timeout error from NGINX.

Are you getting the same error? Don’t worry, I have got you covered. In this article, I will show how to fix the 504 Gateway Timeout error by increasing the request timeout in the NGINX web server.

Increase Request Timeout in NGINX for a Proxied Server

If you are using NGINX as a reverse proxy for an application server such as Node.js or a web server such as Apache or Gunicorn, then you can increase request timeout by setting the following parameters either in the http, or server, or location directive.

The timeout is in seconds and makes sure that you have to set timeout values that will work effectively and efficiently for your environment.

proxy_connect_timeout 75; proxy_send_timeout 600; proxy_read_timeout 600;

From the names of the directives, it is easy to tell what timeout they define. The proxy_connect_timeout directive states a timeout for creating a connection with a proxied server. According to the official NGINX documentation, the value should not exceed 75 seconds.

The next directive proxy_send_timeout defines a timeout for transmitting a request to the proxied server. The last directive proxy_read_timeout sets a timeout for reading a response from the proxied server.

Now that you have a slight understanding of the above directives, you can configure that as shown. In the http context, you can set them in NGINX’s main configuration file located at /etc/nginx/nginx.conf.

In a location block, they would look like this:

Save the file and close it.

To apply the recent changes, you need to restart the NGINX service.

$ sudo systemctl restart nginx OR # systemctl restart nginx

Increase Request Timeout in NGINX for FastCGI

For a FastCGI server such as PHP-FPM, you can use the following directive either in the http, or server, or location:

fastcgi_connect_timeout 75; fastcgi_send_timeout 600; fastcgi_read_timeout 600;

In a location block for processing PHP files, you can define them as shown:

Do not forget to restart the NGINX service after making changes:

$ sudo systemctl restart nginx OR # systemctl restart nginx

Note: You might also have to make some configuration changes in the php.ini and PHP-FPM pool configuration files especially to the max_execution_time and request_terminate_timeout directives respectively.

That’s it! In this article, we looked at how to increase request timeout in NGINX to solve the 504 Gateway timeout error. For more information, read the NGINX documentation. For any comments, reach us via the feedback form below.

Источник

Оцените статью