PHP-FPM — различия между версиями
Kirill (обсуждение | вклад) (Новая страница: «== Установка == # apt-get install php5-mysql php5-fpm После установки нужно в файле <tt>/etc/php5/fpm/php.ini</tt> заменит…») |
Kirill (обсуждение | вклад) (→Шаблоны) |
||
| (не показано 20 промежуточных версии этого же участника) | |||
| Строка 1: | Строка 1: | ||
== Установка == | == Установка == | ||
| − | # apt-get install | + | # apt-get install php-fpm |
| − | После установки нужно в файле <tt>/etc/ | + | После установки для устранения [http://forum.antichat.ru/thread222063-php-fpm.html уязвимости] нужно в файле <tt>/etc/php/7.0/fpm/php.ini</tt> заменить |
;cgi.fix_pathinfo=1 | ;cgi.fix_pathinfo=1 | ||
на | на | ||
cgi.fix_pathinfo = 0 | cgi.fix_pathinfo = 0 | ||
| − | и перезапустить | + | и перезагрузить службу |
| + | sudo service php7.0-fpm reload | ||
| + | |||
| + | == Настройка директорий и пользователей == | ||
| + | В этом руководстве считается, что для хранения файлов каждого сайта используется директория <tt>/var/www/{имя сайта}/www/</tt>. | ||
| + | Поэтому нужно обеспечить существование этой директории (<code>{имя сайта}</code> нужно заменить своим значением) | ||
| + | sudo mkdir /var/www | ||
| + | sudo mkdir /var/www/{имя сайта} | ||
| + | sudo mkdir /var/www/{имя сайта}/www | ||
| + | sudo mkdir /var/www/{имя сайта}/save | ||
| + | sudo mkdir /var/www/{имя сайта}/tmp | ||
| + | |||
| + | Кроме того, с точки зрения безопасности, полезно, чтобы работа с разными сайтами осуществлялась от имен разных пользователей. | ||
| + | Поэтому нужно создать пользователя и предоставить ему права для работы с директорией (<code>{имя пользователя}</code> и <code>{имя сайта}</code> нужно заменить своими значениями) | ||
| + | sudo useradd {имя пользователя} -G www-data -m -U -s /bin/false | ||
| + | sudo chown {имя пользователя}:{имя пользователя} -R /var/www/{имя сайта} | ||
| + | sudo chmod -R a-rwx,u+rwX,g+rX /var/www/{имя сайта} | ||
| + | sudo adduser www-data {имя пользователя} | ||
| + | |||
| + | == Настройка пулов == | ||
| + | Пулы используются для описания настроек [[PHP-FPM]]. | ||
| + | Они позволяют использовать различные параметры PHP для разных сайтов. | ||
| + | Настройки пулов хранятся в директории <tt>/etc/php/7.0/fpm/pool.d/</tt>, по одному файлу <tt>*.conf</tt> на пул. | ||
| + | |||
| + | Для учета изменений настроек нужно перезагрузить службу | ||
| + | sudo service php7.0-fpm reload | ||
| + | |||
| + | Пример настроек (<code>{имя сайта}</code>, <code>{имя пользователя}</code> и <code>{имя группы}</code> нужно заменить своими значениями) | ||
| + | <pre>;; Имя пула в квадратных скобках. | ||
| + | ;; Присваивается переменной $pool, которую можно использовать в других директивах. | ||
| + | [{имя сайта}] | ||
| + | |||
| + | ;; Пользователь и группа, от имени которых работает пул. | ||
| + | user = {имя пользователя} | ||
| + | group = {имя группы} | ||
| + | |||
| + | |||
| + | ;; Подключение шаблона со стандартными настройками. | ||
| + | include = /etc/php/7.0/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 = dynamic | ||
| + | ;; При запуски рабочие процессы не создаются, они будут ответвлены при подключении новых запросов. | ||
| + | ; pm = ondemand | ||
| + | |||
| + | ;; Максимальное количество процессов пула, которые могут существовать одновременно. | ||
| + | pm.max_children = 5 | ||
| + | |||
| + | ;; Количество рабочих процессов при запуске. | ||
| + | ;; Используется только при pm = dynamic. | ||
| + | pm.start_servers = 2 | ||
| + | |||
| + | ;; Минимальное число простаивающих рабочих процессов. | ||
| + | ;; Для экономии ресурсов можно приравнять к pm.start_servers. | ||
| + | ;; Замечание: Используется и только при pm = dynamic, причём в этом случае обязательно. | ||
| + | pm.min_spare_servers = 1 | ||
| + | |||
| + | ;; Максимальное число простаивающих рабочих процессов. | ||
| + | ;; От pm.min_spare_servers до pm.max_children. | ||
| + | ;; Замечание: Используется и только при pm = dynamic, причём в этом случае обязательно. | ||
| + | pm.max_spare_servers = 3 | ||
| + | |||
| + | ;; Количество секунд, после которых простаивающий процесс будет убит. | ||
| + | ;; Замечание: используется только при pm = ondemand. | ||
| + | ; pm.process_idle_timeout = 10s; | ||
| + | |||
| + | ;; Количество обработанных запросов, после которого процессы PHP-FPM будут перезагружены. | ||
| + | ;; Значение по-умолчанию: 0. | ||
| + | pm.max_requests = 500</pre> | ||
| + | |||
| + | === Шаблоны === | ||
| + | Благодаря директиве <tt>include</tt> в настройки пула можно включать внешние файлы. | ||
| + | Шаблоны принято использовать для описания общих настроек. | ||
| + | Файлы шаблонов можно сохранять, например, в директорию <tt>/etc/php/7.0/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-сокета. | ||
| + | ;; Используется для взаимодействия с WEB-сервером. | ||
| + | ; listen = 127.0.0.1:9000 | ||
| + | listen = /var/run/php/php7.0-fpm_$pool.sock | ||
| + | |||
| + | ;; Размер очереди одновременно ожидающих подключений к сокету. | ||
| + | ;; Значение по-умолучению: 511 (-1 on FreeBSD and OpenBSD) | ||
| + | ; listen.backlog = 511 | ||
| + | |||
| + | ;; Пользователь и группа, которые владеют файлом UNIX-сокета, если он используется. | ||
| + | ;; Пользователь, от имени которого работает WEB-сервер, должен иметь права на чтение. | ||
| + | ;; По-умолчанию, совпадают с пользователем и группой, от имени которых запущен процесс. | ||
| + | listen.owner = www-data | ||
| + | listen.group = www-data | ||
| + | |||
| + | ;; Права доступа к файлу UNIX-сокета. | ||
| + | ; 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 | ||
| + | ;; 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. | ||
| + | ; 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 корневой директорией для скриптов. | ||
| + | ;; Нужно скорректировать все пути и обеспечить доступ к файлам сокетов и другим необходимым службам внутри этой директории. | ||
| + | ; chroot = /var/www/$pool | ||
| + | |||
| + | ;; Перейти в дирректорию после запуска. | ||
| + | ;; Примечание: может быть использован относительный путь. | ||
| + | ;; Значение по-умолчанию: текущая директория или / при использовании 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 === | ||
| + | С помощью директивы <tt>php_admin_value</tt> можно изменять глобальные настройки [[PHP]] для отдельного пула. Например | ||
| + | <pre>;; Каталог с файлами сайта. | ||
| + | php_admin_value[open_basedir] = /var/www/$pool | ||
| + | |||
| + | ;; Каталог для размещения временных файлов. | ||
| + | php_admin_value[upload_tmp_dir] = /var/www/$pool/tmp | ||
| + | |||
| + | ;; Каталог для хранения файлов сессий. | ||
| + | php_admin_value[session.save_path] = /var/www/$pool/save | ||
| + | |||
| + | ;; Ограничение памяти для выполнения скриптов. | ||
| + | php_admin_value[memory_limit] = 50M | ||
| + | |||
| + | ;; Настройки ssmtp. | ||
| + | php_admin_value[sendmail_path] = /usr/sbin/ssmtp -t -C/var/www/$pool/ssmtp.conf</pre> | ||
| + | |||
| + | == Работа с почтой == | ||
| + | === ssmtp === | ||
| + | [[ssmtp]] позволяет отправлять почту, используя внешний сервер smtp. | ||
| + | Для установки нужно выполнить | ||
| + | # apt-get install ssmtp | ||
| + | |||
| + | Есть возможность сопоставить персональный файл настроек каждому пользователю. | ||
| + | Для этого нужно изменить глобальную переменную PHP <tt>sendmail_path</tt>, например, на <tt>/usr/sbin/ssmtp -t -C/var/www/$pool/ssmtp.conf</tt> и создать в директории <tt>/var/www/{имя сайта}</tt> файл <tt>ssmtp.conf</tt> с таким содержанием (пример для gmail.com; <tt>{логин}</tt> и <tt>{пароль}</tt> нужно заменить своими значениями) | ||
| + | root={логин}@gmail.com | ||
| + | mailhub=smtp.gmail.com:587 | ||
| + | rewriteDOmain= | ||
| + | hostname=localhost | ||
| + | UseSTARTTLS=YES | ||
| + | FromLineOverride=YES | ||
| + | AuthUser={логин}@gmail.com | ||
| + | AuthPass={пароль} | ||
| + | Для безопасности нужно установить права доступа к файлу: | ||
| + | # chown {имя пользователя}:{имя пользователя} -R /var/www/{имя сайта}/ssmtp.conf | ||
| + | # chmod -R a-rwx,u+rw /var/www/{имя сайта}/ssmtp.conf | ||
| + | |||
| + | == PHP-акселератор == | ||
| + | Есть несколько акселераторов (ускорителей работы) для PHP. | ||
| + | Здесь рассматривается PHP-APC. | ||
| + | Он кэширует результат компиляции PHP-скрипта, которая без акселератора происходит при каждом обращении. | ||
| + | |||
| + | Установка | ||
| + | # apt-get install php-apc | ||
| + | После нужно перезапустить службу | ||
# service php5-fpm restart | # service php5-fpm restart | ||
| − | + | ||
| + | === Ссылки === | ||
| + | * [http://sitear.ru/material/apc-php APC в PHP: Понятие, установка, использование APC] | ||
| + | |||
| + | == Дополнительные модули == | ||
| + | Есть множество пакетов, дополняющих возможности [[PHP-FPM]]. | ||
| + | Для учета изменений после установки модулей нужно перезапустить службу | ||
| + | sudo service php7.0-fpm restart | ||
| + | |||
| + | === memcached === | ||
| + | Для кэширования данных в оперативной памяти. | ||
| + | sudo apt-get install memcached php-memcached | ||
| + | |||
| + | === MySQL === | ||
| + | Для работы с базой данных [[MySQL]]. | ||
| + | sudo apt-get install mysql-server mysql-client php-mysql | ||
| + | |||
| + | === php-gd === | ||
| + | Для обработки изображений. | ||
| + | sudo apt-get install php-gd | ||
| + | |||
| + | === php-imagick === | ||
| + | Для продвинутой обработки изображений. | ||
| + | sudo apt-get install imagemagick php-imagick | ||
== Ссылки == | == Ссылки == | ||
| − | * [http:// | + | * [http://habrahabr.ru/post/164401/ Nginx+php-fpm+perl под Debian Squeeze] |
* [http://rusadmin.biz/rukovodstva/ustanovka-i-nastrojka-php-fpm-na-debian/ Php-fpm + nginx на Debian 7: устанавливаем и настраиваем] | * [http://rusadmin.biz/rukovodstva/ustanovka-i-nastrojka-php-fpm-na-debian/ Php-fpm + nginx на Debian 7: устанавливаем и настраиваем] | ||
* [http://manualpages.pro/node/31 Полноценный http-сервер без Apache, на nginx+php-fpm под Debian Squeeze] | * [http://manualpages.pro/node/31 Полноценный http-сервер без Apache, на nginx+php-fpm под Debian Squeeze] | ||
Текущая версия на 03:32, 21 марта 2017
Содержание
Установка[править]
# apt-get install php-fpm
После установки для устранения уязвимости нужно в файле /etc/php/7.0/fpm/php.ini заменить
;cgi.fix_pathinfo=1
на
cgi.fix_pathinfo = 0
и перезагрузить службу
sudo service php7.0-fpm reload
Настройка директорий и пользователей[править]
В этом руководстве считается, что для хранения файлов каждого сайта используется директория /var/www/{имя сайта}/www/.
Поэтому нужно обеспечить существование этой директории ({имя сайта} нужно заменить своим значением)
sudo mkdir /var/www
sudo mkdir /var/www/{имя сайта}
sudo mkdir /var/www/{имя сайта}/www
sudo mkdir /var/www/{имя сайта}/save
sudo mkdir /var/www/{имя сайта}/tmp
Кроме того, с точки зрения безопасности, полезно, чтобы работа с разными сайтами осуществлялась от имен разных пользователей.
Поэтому нужно создать пользователя и предоставить ему права для работы с директорией ({имя пользователя} и {имя сайта} нужно заменить своими значениями)
sudo useradd {имя пользователя} -G www-data -m -U -s /bin/false
sudo chown {имя пользователя}:{имя пользователя} -R /var/www/{имя сайта}
sudo chmod -R a-rwx,u+rwX,g+rX /var/www/{имя сайта}
sudo adduser www-data {имя пользователя}
Настройка пулов[править]
Пулы используются для описания настроек PHP-FPM. Они позволяют использовать различные параметры PHP для разных сайтов. Настройки пулов хранятся в директории /etc/php/7.0/fpm/pool.d/, по одному файлу *.conf на пул.
Для учета изменений настроек нужно перезагрузить службу
sudo service php7.0-fpm reload
Пример настроек ({имя сайта}, {имя пользователя} и {имя группы} нужно заменить своими значениями)
;; Имя пула в квадратных скобках.
;; Присваивается переменной $pool, которую можно использовать в других директивах.
[{имя сайта}]
;; Пользователь и группа, от имени которых работает пул.
user = {имя пользователя}
group = {имя группы}
;; Подключение шаблона со стандартными настройками.
include = /etc/php/7.0/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 = dynamic
;; При запуски рабочие процессы не создаются, они будут ответвлены при подключении новых запросов.
; pm = ondemand
;; Максимальное количество процессов пула, которые могут существовать одновременно.
pm.max_children = 5
;; Количество рабочих процессов при запуске.
;; Используется только при pm = dynamic.
pm.start_servers = 2
;; Минимальное число простаивающих рабочих процессов.
;; Для экономии ресурсов можно приравнять к pm.start_servers.
;; Замечание: Используется и только при pm = dynamic, причём в этом случае обязательно.
pm.min_spare_servers = 1
;; Максимальное число простаивающих рабочих процессов.
;; От pm.min_spare_servers до pm.max_children.
;; Замечание: Используется и только при pm = dynamic, причём в этом случае обязательно.
pm.max_spare_servers = 3
;; Количество секунд, после которых простаивающий процесс будет убит.
;; Замечание: используется только при pm = ondemand.
; pm.process_idle_timeout = 10s;
;; Количество обработанных запросов, после которого процессы PHP-FPM будут перезагружены.
;; Значение по-умолчанию: 0.
pm.max_requests = 500
Шаблоны[править]
Благодаря директиве include в настройки пула можно включать внешние файлы. Шаблоны принято использовать для описания общих настроек. Файлы шаблонов можно сохранять, например, в директорию /etc/php/7.0/fpm/pool.d/templates/.
Например, стандартные настройки пула в файле /etc/php/7.0/fpm/pool.d/templates/default
;; Префикс для пула.
;; Виляет только на следующие директивы:
;; - 'access.log'
;; - 'slowlog'
;; - 'listen' (unixsocket)
;; - 'chroot'
;; - 'chdir'
;; - 'php_values'
;; - 'php_admin_values'
;; Если не задан, используется глобальный префикс (или /usr).
;; Примечание: эта директива может указывать относительный префикс к глобальному.
;; Значение по умолчанию: none.
; prefix = /path/to/pools/$pool
;; Порт и необязательный адрес или имя UNIX-сокета.
;; Используется для взаимодействия с WEB-сервером.
; listen = 127.0.0.1:9000
listen = /var/run/php/php7.0-fpm_$pool.sock
;; Размер очереди одновременно ожидающих подключений к сокету.
;; Значение по-умолучению: 511 (-1 on FreeBSD and OpenBSD)
; listen.backlog = 511
;; Пользователь и группа, которые владеют файлом UNIX-сокета, если он используется.
;; Пользователь, от имени которого работает WEB-сервер, должен иметь права на чтение.
;; По-умолчанию, совпадают с пользователем и группой, от имени которых запущен процесс.
listen.owner = www-data
listen.group = www-data
;; Права доступа к файлу UNIX-сокета.
; 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
;; 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.
; 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 корневой директорией для скриптов.
;; Нужно скорректировать все пути и обеспечить доступ к файлам сокетов и другим необходимым службам внутри этой директории.
; chroot = /var/www/$pool
;; Перейти в дирректорию после запуска.
;; Примечание: может быть использован относительный путь.
;; Значение по-умолчанию: текущая директория или / при использовании 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
Изменение глобальных настроек PHP[править]
С помощью директивы php_admin_value можно изменять глобальные настройки PHP для отдельного пула. Например
;; Каталог с файлами сайта. php_admin_value[open_basedir] = /var/www/$pool ;; Каталог для размещения временных файлов. php_admin_value[upload_tmp_dir] = /var/www/$pool/tmp ;; Каталог для хранения файлов сессий. php_admin_value[session.save_path] = /var/www/$pool/save ;; Ограничение памяти для выполнения скриптов. php_admin_value[memory_limit] = 50M ;; Настройки ssmtp. php_admin_value[sendmail_path] = /usr/sbin/ssmtp -t -C/var/www/$pool/ssmtp.conf
Работа с почтой[править]
ssmtp[править]
ssmtp позволяет отправлять почту, используя внешний сервер smtp. Для установки нужно выполнить
# apt-get install ssmtp
Есть возможность сопоставить персональный файл настроек каждому пользователю. Для этого нужно изменить глобальную переменную PHP sendmail_path, например, на /usr/sbin/ssmtp -t -C/var/www/$pool/ssmtp.conf и создать в директории /var/www/{имя сайта} файл ssmtp.conf с таким содержанием (пример для gmail.com; {логин} и {пароль} нужно заменить своими значениями)
root={логин}@gmail.com
mailhub=smtp.gmail.com:587
rewriteDOmain=
hostname=localhost
UseSTARTTLS=YES
FromLineOverride=YES
AuthUser={логин}@gmail.com
AuthPass={пароль}
Для безопасности нужно установить права доступа к файлу:
# chown {имя пользователя}:{имя пользователя} -R /var/www/{имя сайта}/ssmtp.conf
# chmod -R a-rwx,u+rw /var/www/{имя сайта}/ssmtp.conf
PHP-акселератор[править]
Есть несколько акселераторов (ускорителей работы) для PHP. Здесь рассматривается PHP-APC. Он кэширует результат компиляции PHP-скрипта, которая без акселератора происходит при каждом обращении.
Установка
# apt-get install php-apc
После нужно перезапустить службу
# service php5-fpm restart
Ссылки[править]
Дополнительные модули[править]
Есть множество пакетов, дополняющих возможности PHP-FPM. Для учета изменений после установки модулей нужно перезапустить службу
sudo service php7.0-fpm restart
memcached[править]
Для кэширования данных в оперативной памяти.
sudo apt-get install memcached php-memcached
MySQL[править]
Для работы с базой данных MySQL.
sudo apt-get install mysql-server mysql-client php-mysql
php-gd[править]
Для обработки изображений.
sudo apt-get install php-gd
php-imagick[править]
Для продвинутой обработки изображений.
sudo apt-get install imagemagick php-imagick