Benutzer-Werkzeuge

Webseiten-Werkzeuge


tachtler:apache_http_server_centos_7_-_php-fpm_-_alternativer_php-interpreter

Dies ist eine alte Version des Dokuments!


Apache HTTP Server CentOS 7 - php-fpm - Alternativer PHP-Interpreter

Der Apache HTTP Server ist ein Open Source Webserver und der seit 1996 am meisten im Internet eingesetzte Webserver weltweit. Der freie und quell offenen Webserver wird von der Apache Software Foundation zur Verfügung gestellt und weiterentwickelt.

Um den Apache HTTP Server als Server mit PHP zu betreiben, kann zur Kommunikation FPM/FastCGI zum Einsatz kommen.

PHP-FPM startet gleich mehrere PHP-Interpreter-Prozesse, die ständig im Hintergrund laufen und auf Aufträge warten. Eingehende Anfragen nimmt PHP-FPM vom Webserver Apache HTTP Server entgegen und verteilt sie an die wartenden PHP-Interpreter.

Hierbei gibt es drei Möglichkeiten, die die Kommunikation zwischen dem Apache HTTP Server und dem PHP bewerkstelligen können:

  1. mod_php - Standard, Aufruf von PHP innerhalb des Webservers Apache HTTP Server.
  2. mod_fcgid - Nutzung von CGI/FastCGI durch Aufruf innerhalb des Apache HTTP Server durch starten eines externen Prozess durch den Apache HTTP Server
  3. php-fpm - Nutzung von FPM/FastCGI durch Aufruf außerhalb des Apache HTTP Server, über einen separat gestarteten Dienstes/Daemon.

Nachfolgend soll die Variante php-fpm genutzt werden!

Ab hier werden root-Rechte zur Ausführung der nachfolgenden Befehle benötigt. Um root zu werden geben Sie bitte folgenden Befehl ein:

$ su -
Password: 

Vorteile von PHP-FPM

Nachfolgende Vorteile besitzt PHP-FPM gegenüber den anderen Möglichkeiten, PHP im Webserver einzubinden:

  1. PHP Prozesse müssen nicht in der gleichen Umgebung, mit dem gleichen User- und der gleichen GruppenID, wie der Webserver laufen.
  2. Es ist möglich die PHP Prozesse neu zu starten, ohne ankommende „Requests“ zu verlieren.
  3. In der PHP-FPM-Konfiguration kann man verschiedene Prozess Pools definieren. Für jeden Pool kann man definieren, mit welchen Rechten die Prozesse laufen, man kann die Prozesse sogar in ein Chroot einsperren oder sie mit einer anderen php.ini starten.
  4. Jeder Prozesspool lauscht auf einem eigenen Port oder einem Unix Domain Socket, so ist es möglich in einem Webserver zu Konfigurieren wohin die „Requests“ gestellt werden sollen.
  5. Es können PHP Prozesse neu gestartet werden, ohne „Requests“ zu verlieren. Auch können PHP Prozesse nach Zeit N automatisch terminiert werden.
  6. Ein Möglichkeit ist die Nutzung der Konfigurationsvariable request_slowlog_timeout. Braucht ein „Request“ länger als definiert, wird automatisch ein „Backtrace“ des „Requests“ in ein LOG-Datei geschrieben.
  7. PHP-FPM ist seit der PHP Version 5.3.3 fest in PHP integriert.
  8. Der Austausch der PHP-Version ist einfacher möglich, als dies bei der Nutzung von mod_php möglich wäre.
  9. Bessere Performance gegenüber z.B. mod_php
  10. Nutzung des

Installation

Zur Installation von PHP-FPM - php-fpm muss nachfolgendes Paket

  • php-fpm - ist im base/updates-Repository von CentOS enthalten

installiert werden.

Mit nachfolgendem Befehl, wird das Pakete php-fpm installiert:

# yum install php-fpm
Loaded plugins: changelog, priorities
365 packages excluded due to repository priority protections
Resolving Dependencies
--> Running transaction check
---> Package php-fpm.x86_64 0:5.4.16-42.el7 will be installed
--> Finished Dependency Resolution

Changes in packages about to be updated:


Dependencies Resolved

================================================================================
 Package          Arch            Version                   Repository     Size
================================================================================
Installing:
 php-fpm          x86_64          5.4.16-42.el7             base          1.4 M

Transaction Summary
================================================================================
Install  1 Package

Total download size: 1.4 M
Installed size: 4.5 M
Is this ok [y/d/N]: y
Downloading packages:
php-fpm-5.4.16-42.el7.x86_64.rpm                           | 1.4 MB   00:00     
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : php-fpm-5.4.16-42.el7.x86_64                                 1/1 
  Verifying  : php-fpm-5.4.16-42.el7.x86_64                                 1/1 

Installed:
  php-fpm.x86_64 0:5.4.16-42.el7                                                

Complete!

Mit nachfolgendem Befehl kann überprüft werden, welche Inhalte mit dem Paket php-fpm installiert wurden.

# rpm -qil php-fpm
Name        : php-fpm
Version     : 5.4.16
Release     : 42.el7
Architecture: x86_64
Install Date: Thu 22 Dec 2016 08:39:08 AM CET
Group       : Development/Languages
Size        : 4700640
License     : PHP and Zend and BSD
Signature   : RSA/SHA256, Sun 20 Nov 2016 09:03:44 PM CET, Key ID 24c6a8a7f4a80eb5
Source RPM  : php-5.4.16-42.el7.src.rpm
Build Date  : Sun 06 Nov 2016 01:38:25 AM CET
Build Host  : worker1.bsys.centos.org
Relocations : (not relocatable)
Packager    : CentOS BuildSystem <http://bugs.centos.org>
Vendor      : CentOS
URL         : http://www.php.net/
Summary     : PHP FastCGI Process Manager
Description :
PHP-FPM (FastCGI Process Manager) is an alternative PHP FastCGI
implementation with some additional features useful for sites of
any size, especially busier sites.
/etc/logrotate.d/php-fpm
/etc/php-fpm.conf
/etc/php-fpm.d
/etc/php-fpm.d/www.conf
/etc/sysconfig/php-fpm
/run/php-fpm
/usr/lib/systemd/system/php-fpm.service
/usr/lib/tmpfiles.d/php-fpm.conf
/usr/sbin/php-fpm
/usr/share/doc/php-fpm-5.4.16
/usr/share/doc/php-fpm-5.4.16/fpm_LICENSE
/usr/share/doc/php-fpm-5.4.16/php-fpm.conf.default
/usr/share/fpm
/usr/share/fpm/status.html
/usr/share/man/man8/php-fpm.8.gz
/var/log/php-fpm

Dienst/Deamon-Start einrichten

Um den PHP-FPM, welcher als Dienst/Deamon als Hintergrundprozess läuft, auch nach einem Neustart des Servers zur Verfügung zu haben, soll der Dienst/Daemon mit dem Server mit gestartet werden, was mit nachfolgendem Befehl realisiert werden kann:

# systemctl enable php-fpm.service
Created symlink from /etc/systemd/system/multi-user.target.wants/php-fpm.service to /usr/lib/systemd/system/php-fpm.service.

:!: HINWEIS - Sollte keine Ausgabe nach Ausführung des Befehls erfolgen, wurde dieser mit der Installation bereits eingerichtet.

Eine Überprüfung, ob beim Neustart des Server der php-fpm-Dienst/Daemon wirklich mit gestartet wird, kann mit nachfolgendem Befehl erfolgen und sollte eine Anzeige, wie ebenfalls nachfolgend dargestellt ausgeben:

# systemctl list-unit-files --type=service | grep -e php-fpm.service
php-fpm.service                               enabled

bzw.

# systemctl is-enabled php-fpm.service
enabled

Konfiguration

Das Ansprechen von PHP über PHP-FPM durch Apache HTTP Server php-fpm wird in nachfolgenden Konfigurationsdateien durchgeführt:

  • /etc/httpd/conf.modules.d/00-proxy.conf - Einstellungen zum Laden des Moduls: mod_proxy_fcgi überprüfen!
  • /etc/httpd/conf.modules.d/00-mpm.conf - Wechseln zum Modus: event, siehe den externen Link Apache MPM event
  • /etc/httpd/conf.modules.d/10-php.conf - Einstellungen zum Laden des Moduls: mod_php überprüfen!
  • /etc/httpd/conf.d/php.conf - Konfigurationsdatei von mod_php, welche falls vorhanden, angepasst werden muss.
  • /etc/httpd/conf.d/vhost.conf - Handler für die Interpretation des PHP-Code hinzufügen.
  • /ect/php-fpm.d/www.conf - Konfigurationsdatei für die Interpretationseinstellungen durch den Apache HTTP Server
  • /ect/php-fpm.conf - Konfigurationsdatei für den PHP-FPM Dienst/Daemon.

/etc/httpd/conf.modules.d/00-proxy.conf

Hier sollte überprüft werden, ob das Modul mod_proxy_fcgi auch geladen wird, was mit nachfolgendem Befehl durchgeführt werden kann (Das Modul sollte standardmäßig geladen werden):

# cat /etc/httpd/conf.modules.d/00-proxy.conf | grep mod_proxy_fcgi
LoadModule proxy_fcgi_module modules/mod_proxy_fcgi.so

:!: HINWEIS - Falls das Modul nicht aktiv sein sollte, muss dieses aktiviert werden, in dem die Auskommentierung der Zeile aufgehoben wird!

/etc/httpd/conf.modules.d/00-mpm.conf

In dieser Konfigurationsdatei wird festgelegt, wie der Apache HTTP Server die Anfragen abarbeitet. Hierzu muss eine der nachfolgenden Möglichkeiten konfiguriert sein:

:!: WICHTIG - Durch die Auswahl des Moduls: event wird automatisch das Modul: mod_php deaktiviert!

Nachfolgende Konfigurationen in der Konfigurationsdatei /etc/httpd/conf.modules.d/00-mpm.conf sollen durchgeführt werden, damit das Modul Apache MPM event durch den Apache HTTP Server verwendet wird:

(Komplette Konfigurationsdatei)

# Select the MPM module which should be used by uncommenting exactly
# one of the following LoadModule lines:
 
# prefork MPM: Implements a non-threaded, pre-forking web server
# See: http://httpd.apache.org/docs/2.4/mod/prefork.html
# Tachtler - disabled - 
# default: LoadModule mpm_prefork_module modules/mod_mpm_prefork.so
#LoadModule mpm_prefork_module modules/mod_mpm_prefork.so
 
# worker MPM: Multi-Processing Module implementing a hybrid
# multi-threaded multi-process web server
# See: http://httpd.apache.org/docs/2.4/mod/worker.html
#
#LoadModule mpm_worker_module modules/mod_mpm_worker.so
 
# event MPM: A variant of the worker MPM with the goal of consuming
# threads only for connections with active processing
# See: http://httpd.apache.org/docs/2.4/mod/event.html
#
# Tachtler - enabled -
# default: #LoadModule mpm_event_module modules/mod_mpm_event.so
LoadModule mpm_event_module modules/mod_mpm_event.so

/etc/httpd/conf.modules.d/10-php.conf

Ausgehend davon, das das Modul mod_php durch die Installation es rpm-Pakets - php bereits vorhanden ist, soll hier nur überprüft werden, ob beim Wechsel des Moduls von alt: prefork auf neu: event das Modul mod_php nicht verwendet wird. Dies wird durch die Bedingung IFModule, wie nachfolgend gezeigt, gewährleistet:

(Komplette Konfigurationsdatei)

#
# PHP is an HTML-embedded scripting language which attempts to make it
# easy for developers to write dynamically generated webpages.
#
<IfModule prefork.c>
  LoadModule php5_module modules/libphp5.so
</IfModule>

Falls das Modul definitiv und explizit deaktiviert werden soll, kann nachfolgende Anpassung an der Konfigurationsdatei durchgeführt werden:

(Komplette Konfigurationsdatei)

#
# PHP is an HTML-embedded scripting language which attempts to make it
# easy for developers to write dynamically generated webpages.
#
<IfModule prefork.c>
  # Tachter - disabled -
  # LoadModule php5_module modules/libphp5.so
</IfModule>

/etc/httpd/conf.d/php.conf

Falls das Modul mod_php installiert wurde, ist auch die Konfigurationsdatei

  • /etc/httpd/conf.d/php.conf

vorhanden.

Damit der Apache HTTP Server auf den PHP-FPM Dienst/Daemon zugreifen kann, könnte nachfolgende Einstellungen hier hinzugefügt werden, siehe auch den externen Link:

Da die Inhalte sich teilweise mit der Installation des PHP-FPM überschneiden, ist es erforderlich nachfolgende Zeilen anzupassen und auszukommentieren:

(Komplette Konfigurationsdatei)

#
# Cause the PHP interpreter to handle files with a .php extension.
#
<FilesMatch \.php$>
    # Tachtler
    # default:    SetHandler application/x-httpd-php
    # TCP/IP-Port
    SetHandler "proxy:fcgi://127.0.0.1:9000"
    # UNIX-Socket - Since Apache 2.4.9 / CentOS 7 use Apache 2.4.6 !!!
    # SetHandler "proxy:unix:/var/run/php-fpm-www.sock|fcgi://localhost/"
</FilesMatch>
 
#
# Allow php to handle Multiviews
#
AddType text/html .php
 
#
# Add index.php to the list of files that will be served as directory
# indexes.
#
DirectoryIndex index.php
 
#
# Uncomment the following lines to allow PHP to pretty-print .phps
# files as PHP source code:
#
#<FilesMatch \.phps$>
#    SetHandler application/x-httpd-php-source
#</FilesMatch>
 
#
# Apache specific PHP configuration options
# those can be override in each configured vhost
#
# Tachtler - disabled -
# default: php_value session.save_handler "files"
# default: php_value session.save_path    "/var/lib/php/session"
# php_value session.save_handler "files"
# php_value session.save_path    "/var/lib/php/session"

Erläuterungen zu den Änderungen

  • SetHandler "proxy:fcgi://127.0.0.1:9000"

Setzen des „Handlers“ auf TCP/IP-Port über das Apache HTTP Server-Modul mod_proxy_fcgi.

:!: WICHTIG - Erst ab Apache HTTP Server Version 2.4.9 wird UNIX-Socket unterstützt!

:!: HINWEIS - Falls die Einstellungen des Handlers (SetHandler) hier durchgeführt wurden, sind dies ggf. NICHT mehr in einem VHOST durchzuführen!

  • # php_value session.save_handler "files"
    # php_value session.save_path    "/var/lib/php/session"

Deaktivieren von doppelten Konfigurationen, welche bereits in /etc/php-fpm.d/www.conf durchgeführt werden!

/etc/httpd/conf.d/vhost.conf

Damit der Apache HTTP Server auf den PHP-FPM Dienst/Daemon zugreifen kann, sind nachfolgende Einstellungen - hier z.B. in einem VHOST, hinzuzufügen, siehe auch den externen Link:

Aktulle Möglichkeit: TCP/IP-Port

    <FilesMatch \.php$>
    	SetHandler "proxy:fcgi://127.0.0.1:9000"
    </FilesMatch>

Zukünftige Möglichkeit: UNIX-Socket

:!: WICHTIG - Erst ab Apache HTTP Server Version 2.4.9 wird UNIX-Socket unterstützt!

(Nur relevanter Ausschnitt)

    <FilesMatch \.php$>
    	SetHandler "proxy:unix:/var/run/php-fpm-www.sock|fcgi://localhost/"
    </FilesMatch>

:!: HINWEIS - Ein UNIX-Socket bietet mehr Möglichkeiten als ein TCP/IP-Port, ist jedoch erst ab Apache HTTP Server Version 2.4.9 verfügbar!!!

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

Diese Konfigurationsdatei erstellt einen Pool, welcher später für den Dienst/Daemon die einzelnen „Child-Threats“ startet, welche dann letztendlich die Anfragen vom Apache HTTP Server entgegennehmen und ausführen.

Die Änderungen an dieser Konfigurationsdatei sind davon abhängig, welches Verfahren zur Kommunikation mit PHP-FPM zum Einsatz kommen soll.

  • TCP/IP-Port
  • UNIX-Socket

Nachfolgende Änderungen sind an dieser Konfigurationsdatei durchzuführen:

Aktuelle Möglichkeit: TCP-IP/Port

(Komplette Konfigurationsdatei)

; Start a new pool named 'www'.
[www]

; The address on which to accept FastCGI requests.
; Valid syntaxes are:
;   'ip.add.re.ss:port'    - to listen on a TCP socket to a specific address on
;                            a specific port;
;   'port'                 - to listen on a TCP socket to all addresses on a
;                            specific port;
;   '/path/to/unix/socket' - to listen on a unix socket.
; Note: This value is mandatory.
listen = 127.0.0.1:9000

; Set listen(2) backlog. A value of '-1' means unlimited.
; Default Value: -1
;listen.backlog = -1
 
; List of ipv4 addresses 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

; Set permissions for unix socket, if one is used. In Linux, read/write
; permissions must be set in order to allow connections from a web server. Many
; BSD-derived systems allow connections regardless of permissions. 
; Default Values: user and group are set as the running user
;                 mode is set to 0666
;listen.owner = nobody
;listen.group = nobody
;listen.mode = 0666

; Unix user/group of processes
; Note: The user is mandatory. If the group is not set, the default user's group
;       will be used.
; RPM: apache Choosed to be able to access some dir as httpd
user = apache
; RPM: Keep a group allowed to write in log dir.
group = apache

; Choose how the process manager will control the number of child processes.
; Possible Values:
;   static  - a fixed number (pm.max_children) of child processes;
;   dynamic - the number of child processes are set dynamically based on the
;             following directives:
;             pm.max_children      - the maximum number of children that can
;                                    be alive at the same time.
;             pm.start_servers     - the number of children created on startup.
;             pm.min_spare_servers - the minimum number of children in 'idle'
;                                    state (waiting to process). If the number
;                                    of 'idle' processes is less than this
;                                    number then some children will be created.
;             pm.max_spare_servers - the maximum number of children in 'idle'
;                                    state (waiting to process). If the number
;                                    of 'idle' processes is greater than this
;                                    number then some children will be killed.
; Note: This value is mandatory.
pm = dynamic

; The number of child processes to be created when pm is set to 'static' and the
; maximum number of child processes to be created when pm is set to 'dynamic'.
; This value sets the limit on the number of simultaneous requests that will be
; served. Equivalent to the ApacheMaxClients directive with mpm_prefork.
; Equivalent to the PHP_FCGI_CHILDREN environment variable in the original PHP
; CGI.
; Note: Used when pm is set to either 'static' or 'dynamic'
; Note: This value is mandatory.
pm.max_children = 50

; The number of child processes created on startup.
; Note: Used only when pm is set to 'dynamic'
; Default Value: min_spare_servers + (max_spare_servers - min_spare_servers) / 2
pm.start_servers = 5

; The desired minimum number of idle server processes.
; Note: Used only when pm is set to 'dynamic'
; Note: Mandatory when pm is set to 'dynamic'
pm.min_spare_servers = 5

; The desired maximum number of idle server processes.
; Note: Used only when pm is set to 'dynamic'
; Note: Mandatory when pm is set to 'dynamic'
pm.max_spare_servers = 35
 
; The number of requests each child process should execute before respawning.
; This can be useful to work around memory leaks in 3rd party libraries. For
; endless request processing specify '0'. Equivalent to PHP_FCGI_MAX_REQUESTS.
; Default Value: 0
;pm.max_requests = 500

; The URI to view the FPM status page. If this value is not set, no URI will be
; recognized as a status page. By default, the status page shows the following
; information:
;   accepted conn    - the number of request accepted by the pool;
;   pool             - the name of the pool;
;   process manager  - static or dynamic;
;   idle processes   - the number of idle processes;
;   active processes - the number of active processes;
;   total processes  - the number of idle + active processes.
; The values of 'idle processes', 'active processes' and 'total processes' are
; updated each second. The value of 'accepted conn' is updated in real time.
; Example output:
;   accepted conn:   12073
;   pool:             www
;   process manager:  static
;   idle processes:   35
;   active processes: 65
;   total processes:  100
; By default the status page output is formatted as text/plain. Passing either
; 'html' or 'json' as a 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
; 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 
; Tachtler
; default: ;pm.status_path = /status
pm.status_path = /php-fpm-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
 
; 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
 
; The timeout for serving a single request after which a PHP backtrace will be
; dumped to the 'slowlog' file. A value of '0s' means 'off'.
; Available units: s(econds)(default), m(inutes), h(ours), or d(ays)
; Default Value: 0
;request_slowlog_timeout = 0
 
; The log file for slow requests
; Default Value: not set
; Note: slowlog is mandatory if request_slowlog_timeout is set
slowlog = /var/log/php-fpm/www-slow.log
 
; 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
 
; Chroot to this directory at the start. This value must be defined as an
; absolute path. When this value is not set, chroot is not used.
; Note: chrooting is a great security feature and should be used whenever 
;       possible. However, all PHP paths will be relative to the chroot
;       (error_log, sessions.save_path, ...).
; Default Value: not set
;chroot = 
 
; Chdir to this directory at the start. This value must be an absolute path.
; Default Value: current directory or / when 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.
; Default Value: no
;catch_workers_output = yes
 
; 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

; Pass environment variables like LD_LIBRARY_PATH. All $VARIABLEs are taken from
; the current environment.
; Default Value: clean env
;env[HOSTNAME] = $HOSTNAME
;env[PATH] = /usr/local/bin:/usr/bin:/bin
;env[TMP] = /tmp
;env[TMPDIR] = /tmp
;env[TEMP] = /tmp

; Additional php.ini defines, specific to this pool of workers. These settings
; overwrite the values previously defined in the php.ini. The directives are the
; same as the PHP SAPI:
;   php_value/php_flag             - you can set classic ini defines which can
;                                    be overwritten from PHP call 'ini_set'. 
;   php_admin_value/php_admin_flag - these directives won't be overwritten by
;                                     PHP call 'ini_set'
; For php_*flag, valid values are on, off, 1, 0, true, false, yes or no.

; Defining 'extension' will load the corresponding shared extension from
; extension_dir. Defining 'disable_functions' or 'disable_classes' will not
; overwrite previously defined php.ini values, but will append the new value
; instead.

; Default Value: nothing is defined by default except the values in php.ini and
;                specified at startup with the -d argument
;php_admin_value[sendmail_path] = /usr/sbin/sendmail -t -i -f www@my.domain.com
;php_flag[display_errors] = off
php_admin_value[error_log] = /var/log/php-fpm/www-error.log
php_admin_flag[log_errors] = on
;php_admin_value[memory_limit] = 128M

; Set session path to a directory owned by process user
php_value[session.save_handler] = files
php_value[session.save_path] = /var/lib/php/session

Erläuterungen zu den Änderungen

  • pm.status_path = /php-fpm-status

Aktivieren der Statusseite durch setzen des Pfades für den Aufruf!


Zukünftige Möglichkeit: UNIX-Socket

(Komplette Konfigurationsdatei)

; Start a new pool named 'www'.
[www]

; The address on which to accept FastCGI requests.
; Valid syntaxes are:
;   'ip.add.re.ss:port'    - to listen on a TCP socket to a specific address on
;                            a specific port;
;   'port'                 - to listen on a TCP socket to all addresses on a
;                            specific port;
;   '/path/to/unix/socket' - to listen on a unix socket.
; Note: This value is mandatory.
; Tachtler
; default: listen = 127.0.0.1:9000
listen = /var/run/php-fpm.sock

; Set listen(2) backlog. A value of '-1' means unlimited.
; Default Value: -1
;listen.backlog = -1
 
; List of ipv4 addresses 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

; Set permissions for unix socket, if one is used. In Linux, read/write
; permissions must be set in order to allow connections from a web server. Many
; BSD-derived systems allow connections regardless of permissions. 
; Default Values: user and group are set as the running user
;                 mode is set to 0666
; Tachtler
; default: ;listen.owner = nobody
listen.owner = apache
; Tachtler
; default: ;listen.group = nobody
listen.group = apache
; Tachtler
; default: ;listen.mode = 0666
listen.mode = 0660

; Unix user/group of processes
; Note: The user is mandatory. If the group is not set, the default user's group
;       will be used.
; RPM: apache Choosed to be able to access some dir as httpd
user = apache
; RPM: Keep a group allowed to write in log dir.
group = apache

; Choose how the process manager will control the number of child processes.
; Possible Values:
;   static  - a fixed number (pm.max_children) of child processes;
;   dynamic - the number of child processes are set dynamically based on the
;             following directives:
;             pm.max_children      - the maximum number of children that can
;                                    be alive at the same time.
;             pm.start_servers     - the number of children created on startup.
;             pm.min_spare_servers - the minimum number of children in 'idle'
;                                    state (waiting to process). If the number
;                                    of 'idle' processes is less than this
;                                    number then some children will be created.
;             pm.max_spare_servers - the maximum number of children in 'idle'
;                                    state (waiting to process). If the number
;                                    of 'idle' processes is greater than this
;                                    number then some children will be killed.
; Note: This value is mandatory.
pm = dynamic

; The number of child processes to be created when pm is set to 'static' and the
; maximum number of child processes to be created when pm is set to 'dynamic'.
; This value sets the limit on the number of simultaneous requests that will be
; served. Equivalent to the ApacheMaxClients directive with mpm_prefork.
; Equivalent to the PHP_FCGI_CHILDREN environment variable in the original PHP
; CGI.
; Note: Used when pm is set to either 'static' or 'dynamic'
; Note: This value is mandatory.
pm.max_children = 50

; The number of child processes created on startup.
; Note: Used only when pm is set to 'dynamic'
; Default Value: min_spare_servers + (max_spare_servers - min_spare_servers) / 2
pm.start_servers = 5

; The desired minimum number of idle server processes.
; Note: Used only when pm is set to 'dynamic'
; Note: Mandatory when pm is set to 'dynamic'
pm.min_spare_servers = 5

; The desired maximum number of idle server processes.
; Note: Used only when pm is set to 'dynamic'
; Note: Mandatory when pm is set to 'dynamic'
pm.max_spare_servers = 35
 
; The number of requests each child process should execute before respawning.
; This can be useful to work around memory leaks in 3rd party libraries. For
; endless request processing specify '0'. Equivalent to PHP_FCGI_MAX_REQUESTS.
; Default Value: 0
;pm.max_requests = 500

; The URI to view the FPM status page. If this value is not set, no URI will be
; recognized as a status page. By default, the status page shows the following
; information:
;   accepted conn    - the number of request accepted by the pool;
;   pool             - the name of the pool;
;   process manager  - static or dynamic;
;   idle processes   - the number of idle processes;
;   active processes - the number of active processes;
;   total processes  - the number of idle + active processes.
; The values of 'idle processes', 'active processes' and 'total processes' are
; updated each second. The value of 'accepted conn' is updated in real time.
; Example output:
;   accepted conn:   12073
;   pool:             www
;   process manager:  static
;   idle processes:   35
;   active processes: 65
;   total processes:  100
; By default the status page output is formatted as text/plain. Passing either
; 'html' or 'json' as a 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
; 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 
; Tachtler
; default: ;pm.status_path = /status
pm.status_path = /php-fpm-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
 
; 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
 
; The timeout for serving a single request after which a PHP backtrace will be
; dumped to the 'slowlog' file. A value of '0s' means 'off'.
; Available units: s(econds)(default), m(inutes), h(ours), or d(ays)
; Default Value: 0
;request_slowlog_timeout = 0
 
; The log file for slow requests
; Default Value: not set
; Note: slowlog is mandatory if request_slowlog_timeout is set
slowlog = /var/log/php-fpm/www-slow.log
 
; 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
 
; Chroot to this directory at the start. This value must be defined as an
; absolute path. When this value is not set, chroot is not used.
; Note: chrooting is a great security feature and should be used whenever 
;       possible. However, all PHP paths will be relative to the chroot
;       (error_log, sessions.save_path, ...).
; Default Value: not set
;chroot = 
 
; Chdir to this directory at the start. This value must be an absolute path.
; Default Value: current directory or / when 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.
; Default Value: no
;catch_workers_output = yes
 
; 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

; Pass environment variables like LD_LIBRARY_PATH. All $VARIABLEs are taken from
; the current environment.
; Default Value: clean env
;env[HOSTNAME] = $HOSTNAME
;env[PATH] = /usr/local/bin:/usr/bin:/bin
;env[TMP] = /tmp
;env[TMPDIR] = /tmp
;env[TEMP] = /tmp

; Additional php.ini defines, specific to this pool of workers. These settings
; overwrite the values previously defined in the php.ini. The directives are the
; same as the PHP SAPI:
;   php_value/php_flag             - you can set classic ini defines which can
;                                    be overwritten from PHP call 'ini_set'. 
;   php_admin_value/php_admin_flag - these directives won't be overwritten by
;                                     PHP call 'ini_set'
; For php_*flag, valid values are on, off, 1, 0, true, false, yes or no.

; Defining 'extension' will load the corresponding shared extension from
; extension_dir. Defining 'disable_functions' or 'disable_classes' will not
; overwrite previously defined php.ini values, but will append the new value
; instead.

; Default Value: nothing is defined by default except the values in php.ini and
;                specified at startup with the -d argument
;php_admin_value[sendmail_path] = /usr/sbin/sendmail -t -i -f www@my.domain.com
;php_flag[display_errors] = off
php_admin_value[error_log] = /var/log/php-fpm/www-error.log
php_admin_flag[log_errors] = on
;php_admin_value[memory_limit] = 128M

; Set session path to a directory owned by process user
php_value[session.save_handler] = files
php_value[session.save_path] = /var/lib/php/session

Erläuterungen zu den Änderungen

  • listen = /var/run/php-fpm.sock

Hier wird Anstelle eines TCP/IP-Port eine UNIX-Socket eröffnet.

  • listen.owner = apache

Setzen des Besitzers für den zu erstellenden UNIX-Socket auf den Benutzer apache.

  • listen.group = apache

Setzen der Gruppe für den zu erstellenden UNIX-Socket auf die Gruppe apache.

  • listen.mode = 0660

Setzen der Dateirechte für den zu erstellenden UNIX-Socket. Hier sollen die Rechte etwas restriktiver gesetzt werden, als dies grundsätzlich der Standard wäre.

  • pm.status_path = /php-fpm-status

Aktivieren der Statusseite durch setzen des Pfades für den Aufruf!

/ect/php-fpm.conf

Die ist eigentlich die Hauptkonfigurationsdatei des PHP-FPM.

Grundsätzlich ist es nicht erforderlich hier Anpassungen vor zu nehmen!:

(Komplette Konfigurationsdatei):

;;;;;;;;;;;;;;;;;;;;;
; FPM Configuration ;
;;;;;;;;;;;;;;;;;;;;;

; All relative paths in this configuration file are relative to PHP's install
; prefix.

; Include one or more files. If glob(3) exists, it is used to include a bunch of
; files from a glob(3) pattern. This directive can be used everywhere in the
; file.
include=/etc/php-fpm.d/*.conf

;;;;;;;;;;;;;;;;;;
; Global Options ;
;;;;;;;;;;;;;;;;;;
 
[global]
; Pid file
; Default Value: none
pid = /run/php-fpm/php-fpm.pid

; Error log file
; Default Value: /var/log/php-fpm.log
error_log = /var/log/php-fpm/error.log

; Log level
; Possible Values: alert, error, warning, notice, debug
; Default Value: notice
;log_level = notice

; If this number of child processes exit with SIGSEGV or SIGBUS within the time
; interval set by emergency_restart_interval then FPM will restart. A value
; of '0' means 'Off'.
; Default Value: 0
;emergency_restart_threshold = 0

; Interval of time used by emergency_restart_interval to determine when 
; a graceful restart will be initiated.  This can be useful to work around
; accidental corruptions in an accelerator's shared memory.
; Available Units: s(econds), m(inutes), h(ours), or d(ays)
; Default Unit: seconds
; Default Value: 0
;emergency_restart_interval = 0

; Time limit for child processes to wait for a reaction on signals from master.
; Available units: s(econds), m(inutes), h(ours), or d(ays)
; Default Unit: seconds
; Default Value: 0
;process_control_timeout = 0

; Send FPM to background. Set to 'no' to keep FPM in foreground for debugging.
; Default Value: yes
daemonize = no

;;;;;;;;;;;;;;;;;;;;
; Pool Definitions ; 
;;;;;;;;;;;;;;;;;;;;

; See /etc/php-fpm.d/*.conf

Status-Abfrage

PHP-FPM beinhaltet auch die Möglichkeit, eine Status-Abfrage in drei Formaten

  • einfacher Textanzeige (plain/text)
  • JSON-Fromat
  • HTML-Format

Nachfolgende Konfigurationen sind dazu notwendig:

Aktulle Möglichkeit: TCP/IP-Port

(Nur relevanter Ausschnitt)

    <Location /php-fpm-status>
    	SetHandler "proxy:fcgi://127.0.0.1:9000"
    </Location>

Zukünftige Möglichkeit: UNIX-Socket

:!: WICHTIG - Erst ab Apache HTTP Server Version 2.4.9 wird UNIX-Socket unterstützt!

(Nur relevanter Ausschnitt)

    <Location /php-fpm-status>
    	SetHandler "proxy:unix:/var/run/php-fpm-www.sock|fcgi://localhost/"
    </Location>

Anschließend kann die Status-Abfrage dann wie folgt über z.B. einen Browser aufgerufen werden, falls dieser entsprechend konfiguriert ist. Eine Ausgabe, wie nachfolgende, sollte erscheinen:

pool:                 www
process manager:      dynamic
start time:           22/Dec/2016:10:03:30 +0100
start since:          77181
accepted conn:        3263
listen queue:         0
max listen queue:     1
listen queue len:     128
idle processes:       9
active processes:     1
total processes:      10
max active processes: 7
max children reached: 0
slow requests:        0

Erster Start: php-fpm

Falls vorstehende Änderungen (natürlich an die jeweiligen Bedürfnisse angepasst) durchgeführt wurden, sollte ein erster Start von PHP-FPM nichts mehr im Wege stehen.

Danach kann der php-fpm-Server mit nachfolgendem Befehle gestartet werden:

# systemctl start php-fpm.service

Mit nachfolgendem Befehl kann der Status des abgefragt werden:

# systemctl status php-fpm.service
● php-fpm.service - The PHP FastCGI Process Manager
   Loaded: loaded (/usr/lib/systemd/system/php-fpm.service; enabled; vendor preset: disabled)
   Active: active (running) since Thu 2016-12-22 08:45:20 CET; 6s ago
 Main PID: 18687 (php-fpm)
   Status: "Ready to handle connections"
   CGroup: /system.slice/php-fpm.service
           ├─18687 php-fpm: master process (/etc/php-fpm.conf)
           ├─18689 php-fpm: pool www
           ├─18690 php-fpm: pool www
           ├─18691 php-fpm: pool www
           ├─18692 php-fpm: pool www
           └─18693 php-fpm: pool www

Dec 22 08:45:20 server60.idmz.tachtler.net systemd[1]: Starting The PHP FastCGI Process Manager...
Dec 22 08:45:20 server60.idmz.tachtler.net systemd[1]: Started The PHP FastCGI Process Manager.

Nachfolgender Befehl kann ebenfalls zur Überprüfung der Lauffähigkeit des php-fpm-Servers genutzt werden und zeigt die laufenden Prozesse und deren genutzte „Pool“'s, hier (pool www):

# ps auxwwwf | grep php
root     18842  0.0  0.0 112648   924 pts/0    S+   08:46   0:00                      \_ grep --color=auto php
root     18687  0.1  0.8 524464 17820 ?        Ss   08:45   0:00 php-fpm: master process (/etc/php-fpm.conf)
apache   18689  0.0  0.3 524464  7692 ?        S    08:45   0:00  \_ php-fpm: pool www
apache   18690  0.0  0.3 524464  7696 ?        S    08:45   0:00  \_ php-fpm: pool www
apache   18691  0.0  0.3 524464  7696 ?        S    08:45   0:00  \_ php-fpm: pool www
apache   18692  0.0  0.3 524464  7696 ?        S    08:45   0:00  \_ php-fpm: pool www
apache   18693  0.0  0.3 524464  7696 ?        S    08:45   0:00  \_ php-fpm: pool www

Neustart: httpd

Bevor weitere Konfigurationsschritte erfolgen, sollte einem Neustart nichts im Wege stehen:

# systemctl restart httpd.service

:!: HINWEIS - Es erfolgen keine weiteren Ausgaben, wenn der Start erfolgreich war !

Test

Mit nachfolgendem Befehl, kann eine einfache Datei mit PHP Inhalt erzeugt werden, welcher dann die bekannte PHP-Statusseite zur Anzeige bringen sollte. Hier nachfolgendes Beispiel:

# echo '<?php phpinfo(); ?>' > /var/www/html/phpinfo.php 

Anschließend kann diese Datei dann wie folgt über z.B. einen Browser aufgerufen werden, falls dieser entsprechend konfiguriert ist. Eine Ausgabe, wie nachfolgende, sollte erscheinen:

PHP-Info Abfrage

:!: WICHTIG - Es muss hier die Anzeige

  • Server-API FPM/FastCGI

erscheinen!

Diese Website verwendet Cookies. Durch die Nutzung der Website stimmen Sie dem Speichern von Cookies auf Ihrem Computer zu. Außerdem bestätigen Sie, dass Sie unsere Datenschutzbestimmungen gelesen und verstanden haben. Wenn Sie nicht einverstanden sind, verlassen Sie die Website.Weitere Information
tachtler/apache_http_server_centos_7_-_php-fpm_-_alternativer_php-interpreter.1482476228.txt.gz · Zuletzt geändert: 2016/12/23 07:57 von klaus