Редактирование PHP-FPM

Материал из K.Wiki
Перейти к: навигация, поиск

Внимание! Вы не авторизовались на сайте.

В истории изменений этой страницы будет записан ваш IP-адрес.
Правка может быть отменена. Пожалуйста, просмотрите сравнение версий, чтобы убедиться, что это именно те изменения, которые вас интересуют, и нажмите «Записать страницу», чтобы изменения вступили в силу.
Текущая версия Ваш текст
Строка 43: Строка 43:
  
 
;; Подключение шаблона со стандартными настройками.
 
;; Подключение шаблона со стандартными настройками.
include = /etc/php/7.0/fpm/pool.d/templates/default
+
include = /etc/php5/fpm/pool.d/templates/default
  
  
;; Specify the nice(2) priority to apply to the pool processes (only if set)
+
;; Статический режим создания рабочих процессов - число запущенных процессов пула равно максимальному.
;; The value can vary from -19 (highest priority) to 20 (lower priority)
+
;; Note: - It will only work if the FPM master process is launched as root
+
;;      - The pool processes will inherit the master process priority
+
;;        unless it specified otherwise
+
;; Default Value: no set
+
; process.priority = -19
+
 
+
;; Статический режим создания рабочих процессов - число запущенных процессов пула равно максимальному (pm.max_children).
+
 
; pm = static
 
; pm = static
 
;; Динамический режим создания рабочих процессов - число запущенных процессов пула зависит от нагрузки.
 
;; Динамический режим создания рабочих процессов - число запущенных процессов пула зависит от нагрузки.
 
pm = dynamic
 
pm = dynamic
;; При запуски рабочие процессы не создаются, они будут ответвлены при подключении новых запросов.
 
; pm = ondemand
 
  
;; Максимальное количество процессов пула, которые могут существовать одновременно.
+
;; Максимальное количество процессов пула.
 
pm.max_children = 5
 
pm.max_children = 5
  
;; Количество рабочих процессов при запуске.
+
;; Количество рабочих процессов при запуске службы.
;; Используется только при pm = dynamic.
+
 
pm.start_servers = 2
 
pm.start_servers = 2
  
 
;; Минимальное число простаивающих рабочих процессов.
 
;; Минимальное число простаивающих рабочих процессов.
 
;; Для экономии ресурсов можно приравнять к pm.start_servers.
 
;; Для экономии ресурсов можно приравнять к pm.start_servers.
;; Замечание: Используется и только при pm = dynamic, причём в этом случае обязательно.
 
 
pm.min_spare_servers = 1
 
pm.min_spare_servers = 1
  
 
;; Максимальное число простаивающих рабочих процессов.  
 
;; Максимальное число простаивающих рабочих процессов.  
 
;; От pm.min_spare_servers до pm.max_children.
 
;; От pm.min_spare_servers до pm.max_children.
;; Замечание: Используется и только при pm = dynamic, причём в этом случае обязательно.
 
 
pm.max_spare_servers = 3
 
pm.max_spare_servers = 3
 
;; Количество секунд, после которых простаивающий процесс будет убит.
 
;; Замечание: используется только при pm = ondemand.
 
; pm.process_idle_timeout = 10s;
 
  
 
;; Количество обработанных запросов, после которого процессы PHP-FPM будут перезагружены.
 
;; Количество обработанных запросов, после которого процессы PHP-FPM будут перезагружены.
;; Значение по-умолчанию: 0.
 
 
pm.max_requests = 500</pre>
 
pm.max_requests = 500</pre>
  
Строка 89: Строка 71:
 
Благодаря директиве <tt>include</tt> в настройки пула можно включать внешние файлы.
 
Благодаря директиве <tt>include</tt> в настройки пула можно включать внешние файлы.
 
Шаблоны принято использовать для описания общих настроек.
 
Шаблоны принято использовать для описания общих настроек.
Файлы шаблонов можно сохранять, например, в директорию <tt>/etc/php/7.0/fpm/pool.d/templates/</tt>.
+
Файлы шаблонов можно сохранять, например, в директорию <tt>/etc/php5/fpm/pool.d/templates/</tt>.
 
+
Например, стандартные настройки пула в файле <tt>/etc/php/7.0/fpm/pool.d/templates/default</tt>
+
<pre>;; Префикс для пула.
+
;; Виляет только на следующие директивы:
+
;; - 'access.log'
+
;; - 'slowlog'
+
;; - 'listen' (unixsocket)
+
;; - 'chroot'
+
;; - 'chdir'
+
;; - 'php_values'
+
;; - 'php_admin_values'
+
;; Если не задан, используется глобальный префикс (или /usr).
+
;; Примечание: эта директива может указывать относительный префикс к глобальному.
+
;; Значение по умолчанию: none.
+
; prefix = /path/to/pools/$pool
+
 
+
  
;; Порт и необязательный адрес или имя UNIX-сокета.
+
Например, стандартные настройки пула в файле <tt>/etc/php5/fpm/pool.d/templates/default</tt>
 +
<pre>;; Порт и необязательный адрес или имя UNIX-сокета.
 
;; Используется для взаимодействия с WEB-сервером.
 
;; Используется для взаимодействия с WEB-сервером.
 
; listen = 127.0.0.1:9000
 
; listen = 127.0.0.1:9000
listen = /var/run/php/php7.0-fpm_$pool.sock
+
listen = /var/run/php7.0-fpm_$pool.sock
  
;; Размер очереди одновременно ожидающих подключений к сокету.
+
;; Пользователь и группа, которые владеют файлом UNIX-сокета.
;; Значение по-умолучению: 511 (-1 on FreeBSD and OpenBSD)
+
; listen.backlog = 511
+
 
+
;; Пользователь и группа, которые владеют файлом UNIX-сокета, если он используется.
+
 
;; Пользователь, от имени которого работает WEB-сервер, должен иметь права на чтение.
 
;; Пользователь, от имени которого работает WEB-сервер, должен иметь права на чтение.
;; По-умолчанию, совпадают с пользователем и группой, от имени которых запущен процесс.
 
 
listen.owner = www-data
 
listen.owner = www-data
 
listen.group = www-data
 
listen.group = www-data
Строка 125: Строка 87:
 
; listen.mode = 0660
 
; listen.mode = 0660
  
;; When POSIX Access Control Lists are supported you can set them using
 
;; these options, value is a comma separated list of user/group names.
 
;; When set, listen.owner and listen.group are ignored
 
; listen.acl_users =
 
; listen.acl_groups =
 
  
;; List of addresses (IPv4/IPv6) of FastCGI clients which are allowed to connect.
+
;; Ограничение по времени, после которого запросы будут считаться медленными.
;; Equivalent to the FCGI_WEB_SERVER_ADDRS environment variable in the original
+
; request_slowlog_timeout = 0
;; PHP FCGI (5.2.2+). Makes sense only with a tcp listening socket. Each address
+
;; must be separated by a comma. If this value is left blank, connections will be
+
;; accepted from any ip address.
+
;; Default Value: any
+
; listen.allowed_clients = 127.0.0.1
+
 
+
 
+
;; The URI to view the FPM status page. If this value is not set, no URI will be
+
;; recognized as a status page. It shows the following informations:
+
;;  pool                - the name of the pool;
+
;;  process manager      - static, dynamic or ondemand;
+
;;  start time          - the date and time FPM has started;
+
;;  start since          - number of seconds since FPM has started;
+
;;  accepted conn        - the number of request accepted by the pool;
+
;;  listen queue        - the number of request in the queue of pending
+
;;                          connections (see backlog in listen(2));
+
;;  max listen queue    - the maximum number of requests in the queue
+
;;                          of pending connections since FPM has started;
+
;;  listen queue len    - the size of the socket queue of pending connections;
+
;;  idle processes      - the number of idle processes;
+
;;  active processes    - the number of active processes;
+
;;  total processes      - the number of idle + active processes;
+
;;  max active processes - the maximum number of active processes since FPM
+
;;                          has started;
+
;;  max children reached - number of times, the process limit has been reached,
+
;;                          when pm tries to start more children (works only for
+
;;                          pm 'dynamic' and 'ondemand');
+
;; Value are updated in real time.
+
;; Example output:
+
;;  pool:                www
+
;;  process manager:      static
+
;;  start time:          01/Jul/2011:17:53:49 +0200
+
;;  start since:          62636
+
;;  accepted conn:        190460
+
;;  listen queue:        0
+
;;  max listen queue:    1
+
;;  listen queue len:    42
+
;;  idle processes:      4
+
;;  active processes:    11
+
;;  total processes:      15
+
;;  max active processes: 12
+
;;  max children reached: 0
+
;;
+
;; By default the status page output is formatted as text/plain. Passing either
+
;; 'html', 'xml' or 'json' in the query string will return the corresponding
+
;; output syntax. Example:
+
;;  http://www.foo.bar/status
+
;;  http://www.foo.bar/status?json
+
;;  http://www.foo.bar/status?html
+
;;  http://www.foo.bar/status?xml
+
;;
+
;; By default the status page only outputs short status. Passing 'full' in the
+
;; query string will also return status for each pool process.
+
;; Example:
+
;;  http://www.foo.bar/status?full
+
;;  http://www.foo.bar/status?json&full
+
;;  http://www.foo.bar/status?html&full
+
;;  http://www.foo.bar/status?xml&full
+
;; The Full status returns for each process:
+
;;  pid                  - the PID of the process;
+
;;  state                - the state of the process (Idle, Running, ...);
+
;;  start time          - the date and time the process has started;
+
;;  start since          - the number of seconds since the process has started;
+
;;  requests            - the number of requests the process has served;
+
;;  request duration    - the duration in µs of the requests;
+
;;  request method      - the request method (GET, POST, ...);
+
;;  request URI          - the request URI with the query string;
+
;;  content length      - the content length of the request (only with POST);
+
;;  user                - the user (PHP_AUTH_USER) (or '-' if not set);
+
;;  script              - the main script called (or '-' if not set);
+
;;  last request cpu    - the %cpu the last request consumed
+
;;                          it's always 0 if the process is not in Idle state
+
;;                          because CPU calculation is done when the request
+
;;                          processing has terminated;
+
;;  last request memory  - the max amount of memory the last request consumed
+
;;                          it's always 0 if the process is not in Idle state
+
;;                          because memory calculation is done when the request
+
;;                          processing has terminated;
+
;; If the process is in Idle state, then informations are related to the
+
;; last request the process has served. Otherwise informations are related to
+
;; the current request being served.
+
;; Example output:
+
;;  ************************
+
;;  pid:                  31330
+
;;  state:                Running
+
;;  start time:          01/Jul/2011:17:53:49 +0200
+
;;  start since:          63087
+
;;  requests:            12808
+
;;  request duration:    1250261
+
;;  request method:      GET
+
;;  request URI:          /test_mem.php?N=10000
+
;;  content length:      0
+
;;  user:                -
+
;;  script:              /home/fat/web/docs/php/test_mem.php
+
;;  last request cpu:    0.00
+
;;  last request memory:  0
+
;;
+
;; Note: There is a real-time FPM status monitoring sample web page available
+
;;      It's available in: /usr/share/php/7.0/fpm/status.html
+
;;
+
;; Note: The value must start with a leading slash (/). The value can be
+
;;      anything, but it may not be a good idea to use the .php extension or it
+
;;      may conflict with a real PHP file.
+
;; Default Value: not set
+
; pm.status_path = /status
+
 
+
;; The ping URI to call the monitoring page of FPM. If this value is not set, no
+
;; URI will be recognized as a ping page. This could be used to test from outside
+
;; that FPM is alive and responding, or to
+
;; - create a graph of FPM availability (rrd or such);
+
;; - remove a server from a group if it is not responding (load balancing);
+
;; - trigger alerts for the operating team (24/7).
+
;; Note: The value must start with a leading slash (/). The value can be
+
;;      anything, but it may not be a good idea to use the .php extension or it
+
;;      may conflict with a real PHP file.
+
;; Default Value: not set
+
; ping.path = /ping
+
 
+
;; This directive may be used to customize the response of a ping request. The
+
;; response is formatted as text/plain with a 200 response code.
+
;; Default Value: pong
+
; ping.response = pong
+
 
+
 
+
;; Файл с логом проблем доступа.
+
;; По-умолчанию: не задан.
+
; access.log = log/$pool.access.log
+
 
+
;; The access log format.
+
;; The following syntax is allowed
+
;;  %%: the '%' character
+
;;  %C: %CPU used by the request
+
;;      it can accept the following format:
+
;;      - %{user}C for user CPU only
+
;;      - %{system}C for system CPU only
+
;;      - %{total}C  for user + system CPU (default)
+
;;  %d: time taken to serve the request
+
;;      it can accept the following format:
+
;;      - %{seconds}d (default)
+
;;      - %{miliseconds}d
+
;;      - %{mili}d
+
;;      - %{microseconds}d
+
;;      - %{micro}d
+
;;  %e: an environment variable (same as $_ENV or $_SERVER)
+
;;      it must be associated with embraces to specify the name of the env
+
;;      variable. Some exemples:
+
;;      - server specifics like: %{REQUEST_METHOD}e or %{SERVER_PROTOCOL}e
+
;;      - HTTP headers like: %{HTTP_HOST}e or %{HTTP_USER_AGENT}e
+
;;  %f: script filename
+
;;  %l: content-length of the request (for POST request only)
+
;;  %m: request method
+
;;  %M: peak of memory allocated by PHP
+
;;      it can accept the following format:
+
;;      - %{bytes}M (default)
+
;;      - %{kilobytes}M
+
;;      - %{kilo}M
+
;;      - %{megabytes}M
+
;;      - %{mega}M
+
;;  %n: pool name
+
;;  %o: output header
+
;;      it must be associated with embraces to specify the name of the header:
+
;;      - %{Content-Type}o
+
;;      - %{X-Powered-By}o
+
;;      - %{Transfert-Encoding}o
+
;;      - ....
+
;;  %p: PID of the child that serviced the request
+
;;  %P: PID of the parent of the child that serviced the request
+
;;  %q: the query string
+
;;  %Q: the '?' character if query string exists
+
;;  %r: the request URI (without the query string, see %q and %Q)
+
;;  %R: remote IP address
+
;;  %s: status (response code)
+
;;  %t: server time the request was received
+
;;      it can accept a strftime(3) format:
+
;;      %d/%b/%Y:%H:%M:%S %z (default)
+
;;      The strftime(3) format must be encapsuled in a %{<strftime_format>}t tag
+
;;      e.g. for a ISO8601 formatted timestring, use: %{%Y-%m-%dT%H:%M:%S%z}t
+
;;  %T: time the log has been written (the request has finished)
+
;;      it can accept a strftime(3) format:
+
;;      %d/%b/%Y:%H:%M:%S %z (default)
+
;;      The strftime(3) format must be encapsuled in a %{<strftime_format>}t tag
+
;;      e.g. for a ISO8601 formatted timestring, use: %{%Y-%m-%dT%H:%M:%S%z}t
+
;;  %u: remote user
+
;;
+
;; Default: "%R - %u %t \"%m %r\" %s"
+
; access.format = "%R - %u %t \"%m %r%Q%q\" %s %f %{mili}d %{kilo}M %C%%"
+
  
 
;; Файл лога медленно обрабатываемых запросов.
 
;; Файл лога медленно обрабатываемых запросов.
;; Обязателен, если задан request_slowlog_timeout.
+
;; Обязателен, если задан request_slowlog_timeout
 
; slowlog = log/$pool.log.slow
 
; slowlog = log/$pool.log.slow
 
;; Ограничение по времени, после которого запросы будут считаться медленными.
 
;; Значение '0s' означает отключение.
 
;; Доступные единицы: s - секунды (по-умолчанию), m - минуты, h - часы, d - дни
 
; request_slowlog_timeout = 0
 
 
;; The timeout for serving a single request after which the worker process will
 
;; be killed. This option should be used when the 'max_execution_time' ini option
 
;; does not stop script execution for some reason. A value of '0' means 'off'.
 
;; Available units: s(econds)(default), m(inutes), h(ours), or d(ays)
 
;; Default Value: 0
 
; request_terminate_timeout = 0
 
 
;; Set open file descriptor rlimit.
 
;; Default Value: system defined value
 
; rlimit_files = 1024
 
 
;; Set max core size rlimit.
 
;; Possible Values: 'unlimited' or an integer greater or equal to 0
 
;; Default Value: system defined value
 
; rlimit_core = 0
 
  
  
 
;; Считать /var/www/$pool корневой директорией для скриптов.
 
;; Считать /var/www/$pool корневой директорией для скриптов.
 
;; Нужно скорректировать все пути и обеспечить доступ к файлам сокетов и другим необходимым службам внутри этой директории.
 
;; Нужно скорректировать все пути и обеспечить доступ к файлам сокетов и другим необходимым службам внутри этой директории.
; chroot = /var/www/$pool
+
; chroot = /var/www/$pool</pre>
 
+
;; Перейти в дирректорию после запуска.
+
;; Примечание: может быть использован относительный путь.
+
;; Значение по-умолчанию: текущая директория или / при использовании chroot.
+
; chdir = /var/www
+
 
+
 
+
; Redirect worker stdout and stderr into main error log. If not set, stdout and
+
; stderr will be redirected to /dev/null according to FastCGI specs.
+
; Note: on highloaded environement, this can cause some delay in the page
+
; process time (several ms).
+
; Default Value: no
+
;catch_workers_output = yes
+
 
+
 
+
; Clear environment in FPM workers
+
; Prevents arbitrary environment variables from reaching FPM worker processes
+
; by clearing the environment in workers before env vars specified in this
+
; pool configuration are added.
+
; Setting to "no" will make all environment variables available to PHP code
+
; via getenv(), $_ENV and $_SERVER.
+
; Default Value: yes
+
;clear_env = no
+
 
+
; Limits the extensions of the main script FPM will allow to parse. This can
+
; prevent configuration mistakes on the web server side. You should only limit
+
; FPM to .php extensions to prevent malicious users to use other extensions to
+
; exectute php code.
+
; Note: set an empty value to allow all extensions.
+
; Default Value: .php
+
;security.limit_extensions = .php .php3 .php4 .php5 .php7
+
 
+
;; Передать переменные октужения, такие как LD_LIBRARY_PATH.
+
;; Все $VARIABLEs берутся из текущего окружения.
+
;; По-умолчанию, env пустой.
+
env[HOSTNAME] = $HOSTNAME
+
env[PATH] = /usr/local/bin:/usr/bin:/bin
+
; env[TMP] = /tmp
+
; env[TMPDIR] = /tmp
+
; env[TEMP] = /tmp</pre>
+
  
 
=== Изменение глобальных настроек PHP ===
 
=== Изменение глобальных настроек PHP ===
Строка 443: Строка 153:
 
Есть множество пакетов, дополняющих возможности [[PHP-FPM]].
 
Есть множество пакетов, дополняющих возможности [[PHP-FPM]].
 
Для учета изменений после установки модулей нужно перезапустить службу
 
Для учета изменений после установки модулей нужно перезапустить службу
  sudo service php7.0-fpm restart
+
  # service php5-fpm restart
  
 
=== memcached ===
 
=== memcached ===
 
Для кэширования данных в оперативной памяти.
 
Для кэширования данных в оперативной памяти.
  sudo apt-get install memcached php-memcached
+
  # apt-get install memcached php5-memcached
  
 
=== MySQL ===
 
=== MySQL ===
 
Для работы с базой данных [[MySQL]].
 
Для работы с базой данных [[MySQL]].
  sudo apt-get install mysql-server mysql-client php-mysql
+
  # apt-get install mysql-server mysql-client php5-mysql
  
=== php-gd ===
+
=== php5-gd ===
 
Для обработки изображений.
 
Для обработки изображений.
  sudo apt-get install php-gd
+
  # apt-get install php5-gd
  
=== php-imagick ===
+
=== php5-imagick ===
 
Для продвинутой обработки изображений.
 
Для продвинутой обработки изображений.
  sudo apt-get install imagemagick php-imagick
+
  # apt-get install imagemagick php5-imagick
  
 
== Ссылки ==
 
== Ссылки ==

Пожалуйста, учтите, что любой ваш вклад в проект «K.Wiki» может быть отредактирован или удалён другими участниками. Если вы не хотите, чтобы кто-либо изменял ваши тексты, не помещайте их сюда.
Вы также подтверждаете, что являетесь автором вносимых дополнений, или скопировали их из источника, допускающего свободное распространение и изменение своего содержимого (см. K.Wiki:Авторские права). НЕ РАЗМЕЩАЙТЕ БЕЗ РАЗРЕШЕНИЯ ОХРАНЯЕМЫЕ АВТОРСКИМ ПРАВОМ МАТЕРИАЛЫ!

Источник — «https://chuvilin.pro/wiki/PHP-FPM»