So most of you are running (some sort of) a web-server. Mostly this is the usual LAMP stack, consisting out of
and there is nothing wrong with that. Built on top of a Centos 6 machine yields a pretty fast and stable server. Yet, with the default setting and repositories of CentOS 6 this would yield with a mod_php run Apache Server featuring a whooping PHP 5.3. To remedy the version issue and switch to fastcgi yields in a modern set-up that’s lighting fast on top.
I will show you how to build a LAMP stack with stack apache, mod_fastcgi and a current PHP 5.6.
Let’s get down to business.
yum install -y http://mirror.de.leaseweb.net/epel/6/i386/epel-release-6-8.noarch.rpm yum install -y http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.3-1.el6.rf.x86_64.rpm
These links are for a 64 bit Centos 6.
Once installed, we need to fetch a few packages in order to build PHP later on:
yum install libxml2-devel openssl-devel bzip2-devel curl-devel libjpeg-devel libpng-devel freetype-devel gmp-devel mysql-devel ncurses-devel unixODBC-devel net-snmp-devel mhash-devel libc-client-devel libicu-devel gcc postgresql-devel aspell-devel libxslt-devel gcc-c++ openldap-devel yum-priorities php-fpm mod_fastcgi
And finally we need the source of PHP. I suggest PHP 5.6 as it is the current version of PHP at the time of writing this how-to. To download visit php.net here.
cd /usr/local/src wget "http://de1.php.net/get/php-5.6.7.tar.bz2/from/this/mirror" mv mirror php-5.6.7.tar.bz2 tar xf php 5.6.7.tar.bz2
These command should yield you a /usr/local/src/php-5.6.7 directory with all the sources in it.
Go in there and configure PHP with this configure line:
./configure '--with-libdir=lib64' '--prefix=/usr/local/php-5.6-cgi' '--with-config-file-path=/usr/local/php-5.6-cgi/etc' '--disable-debug' '--with-pic' '--disable-rpath' '--with-bz2' '--with-curl' '--with-freetype-dir=/usr/local/php-5.6-cgi' '--with-png-dir=/usr/local/php-5.6-cgi' '--enable-gd-native-ttf' '--without-gdbm' '--with-gettext' '--with-gmp' '--with-iconv' '--with-jpeg-dir=/usr/local/php-5.6-cgi' '--with-openssl' '--with-pspell' '--with-pcre-regex' '--with-zlib' '--enable-exif' '--enable-ftp' '--enable-sockets' '--enable-sysvsem' '--enable-sysvshm' '--enable-sysvmsg' '--enable-wddx' '--with-kerberos' '--with-unixODBC=/usr' '--enable-shmop' '--enable-calendar' '--without-sqlite3' '--with-libxml-dir=/usr/local/php-5.6-cgi' '--enable-pcntl' '--with-imap' '--with-imap-ssl' '--enable-mbstring' '--enable-mbregex' '--with-gd' '--enable-bcmath' '--with-xmlrpc' '--with-ldap' '--with-ldap-sasl' '--with-mysql=/usr' '--with-snmp' '--enable-soap' '--with-xsl' '--enable-xmlreader' '--enable-xmlwriter' '--enable-pdo' '--with-pdo-mysql' '--with-pdo-pgsql' '--with-pear=/usr/local/php-5.6-cgi/pear' '--enable-intl' '--without-pdo-sqlite' '--with-config-file-scan-dir=/usr/local/php-5.6-cgi/php.d' '--enable-cgi' --with-fpm-user=apache --with-fpm-group=apache --enable-fpm --with-mysqli=/usr/bin/mysql_config --enable-zip
If you installed all the prerequisites above this completes without error. If there are any errors you have no installed all the needed packages. I am assuming you are using (a form of) MySQL (either real mysql, percona or mariadb). If configure complains about mysql at any point, install the “-dev” packages, like these for MySQL 5.1:
yum install mysql-devel
Proceed with compiling PHP:
If you know how many CPUs you have in there, run this many compile processes (cutting the compile time down significantly:
make -j 8
This should take a few minutes and run through just fine. Now install your brand new PHP:
You now have a PHP 5.6 (or whatever version you have chosen) under /usr/local/php-5.6-cgi/. This however, will not be executed by your system at this point. Its “alien” software, lying around. So we need to introduce it to your system. But first, we need to make your mod_php a “php non-grata”. cd into /etc/httpd/conf.d, and move php.conf out of the way or delete it:
cd /etc/httpd/conf.d mv php.conf php.conf.off
if there are any “fastcgi.conf” or “fcgid.conf” in there, move them out of the way as well. Now create our fastcgi.conf file, contents follow:
User apache Group apache LoadModule fastcgi_module modules/mod_fastcgi.so FastCgiIpcDir /var/run/mod_fastcgi FastCgiConfig -idle-timeout 20 -maxClassProcesses 1 DirectoryIndex index.php AddType application/x-httpd-php .php # # PHP 5.3 # AddHandler php5-fcgi .php Action php5-fcgi /php5-fcgi Alias /php5-fcgi /var/www/cgi-bin/php-wrapper FastCgiExternalServer /var/www/cgi-bin/php-wrapper -socket /var/run/php5-fpm.sock -pass-header Authorization # # PHP 5.6 # Alias /php5.6-fcgi /var/www/cgi-bin/php5.6-wrapper Action php5.6-fcgi /php5.6-fcgi FastCgiExternalServer /var/www/cgi-bin/php5.6-wrapper -socket /var/run/php5.6-fpm.sock -pass-header Authorization
What this actually does is enabling two PHP Versions at the same time. If you have older Scripts that need the (stock) PHP 5.3 it works out of the box, while also enabling PHP 5.6 with just a single line, more on that later. You can also reverse that logic, setting 5.6 as the default an doing 5.3 as fall-back. Simply change this line
AddHandler php5-fcgi .php
AddHandler php5.6-fcgi .php
Recap so far
Anyway – we are getting ahead of ourselves. So far we have:
- Installed the necessary packages to compile and run a custom PHP Version,
- compiled and installed a custom PHP Version,
- removed the support for mod_php,
- enabled and configured the apache side of fastcgi.
Noticed how I said “apache side“? So far the apache would check
for a running php-fpm process, but nothing is there. Let’s remedy that. Create the file /usr/local/php-5.6-cgi/etc/php-fpm.conf:
;;;;;;;;;;;;;;;;;;;;; ; FPM Configuration ; ;;;;;;;;;;;;;;;;;;;;; ; All relative paths in this configuration file are relative to PHP's install ; prefix (/usr/local/php-5.6-cgi). This prefix can be dynamically changed by using the ; '-p' argument from the command line. ; 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. ; Relative path can also be used. They will be prefixed by: ; - the global prefix if it's been set (-p argument) ; - /usr/local/php-5.6-cgi otherwise include=etc/fpm.d/*.conf ;;;;;;;;;;;;;;;;;; ; Global Options ; ;;;;;;;;;;;;;;;;;; [global] ; Pid file ; Note: the default prefix is /usr/local/php-5.6-cgi/var ; Default Value: none ;pid = run/php-fpm.pid ; Error log file ; If it's set to "syslog", log is sent to syslogd instead of being written ; in a local file. ; Note: the default prefix is /usr/local/php-5.6-cgi/var ; Default Value: log/php-fpm.log error_log = /var/log/httpd/php-fpm.log ; syslog_facility is used to specify what type of program is logging the ; message. This lets syslogd specify that messages from different facilities ; will be handled differently. ; See syslog(3) for possible values (ex daemon equiv LOG_DAEMON) ; Default Value: daemon ;syslog.facility = daemon ; syslog_ident is prepended to every message. If you have multiple FPM ; instances running on the same server, you can change the default value ; which must suit common needs. ; Default Value: php-fpm ;syslog.ident = php-fpm ; 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 ; The maximum number of processes FPM will fork. This has been design to control ; the global number of processes when using dynamic PM within a lot of pools. ; Use it with caution. ; Note: A value of 0 indicates no limit ; Default Value: 0 ; process.max = 128 ; Specify the nice(2) priority to apply to the master process (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 process will inherit the master process priority ; unless it specified otherwise ; Default Value: no set ; process.priority = -19 ; Send FPM to background. Set to 'no' to keep FPM in foreground for debugging. ; Default Value: yes ;daemonize = yes ; Set open file descriptor rlimit for the master process. ; Default Value: system defined value ;rlimit_files = 1024 ; Set max core size rlimit for the master process. ; Possible Values: 'unlimited' or an integer greater or equal to 0 ; Default Value: system defined value ;rlimit_core = 0 ; Specify the event mechanism FPM will use. The following is available: ; - select (any POSIX os) ; - poll (any POSIX os) ; - epoll (linux >= 2.5.44) ; - kqueue (FreeBSD >= 4.1, OpenBSD >= 2.9, NetBSD >= 2.0) ; - /dev/poll (Solaris >= 7) ; - port (Solaris >= 10) ; Default Value: not set (auto detection) ;events.mechanism = epoll ; When FPM is build with systemd integration, specify the interval, ; in second, between health report notification to systemd. ; Set to 0 to disable. ; Available Units: s(econds), m(inutes), h(ours) ; Default Unit: seconds ; Default value: 10 ;systemd_interval = 10
and also /etc/php-fpm.conf:
;;;;;;;;;;;;;;;;;;;;; ; 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 = /var/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 = yes ;;;;;;;;;;;;;;;;;;;; ; Pool Definitions ; ;;;;;;;;;;;;;;;;;;;; ; See /etc/php-fpm.d/*.conf
Likewise, create two directories:
and place a www.conf in there, this time it’s identical:
; 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 listen = /var/run/php5.6-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 listen.owner = apache listen.group = apache 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 ;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 ; 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 firstname.lastname@example.org ;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
Now for the starter script. It is executed for each PHP script called, setting variables and what not. I am running my own server with only me, myself and I on it, so I do not use user separation (which is very easy to implement). Create the starter-script directory:
and edit the new file php-wrapper in there:
#!/bin/bash PHPRC="/etc/php.ini" PHP_FCGI_CHILDREN=4 PHP_FCGI_MAX_REQUESTS=1000 export PHPRC export PHP_FCGI_CHILDREN export PHP_FCGI_MAX_REQUESTS #exec /usr/local/php-5.6-cgi/bin/php-cgi exec /usr/bin/php-cgi
chmod 755 php-wrapper chown apache:apache php-wrapper
You need a php.ini for your new PHP 5.6 installation. You can go two way: Having a seperate php.ini file for 5.3 and 5.6 or just link them for identical configuration. Pick either:
Copy: cp /etc/php.ini /usr/local/php-5.6-cgi/etc/ Link: ln -s /etc/php.ini /usr/local/php-5.6-cgi/etc/
Make it Boot-Sticky
So once in a while even a Linux system has to reboot. So we want everything to start at boot-time:
-fpm chmod 755 /etc/init.d/php5.6-fpm chkconfig php-fpm on chkconfig php5.6-fpm on
While on the subject, let’s start the php-fpm’s!
/etc/init.d/php-fpm start /etc/init.d/php5.6-fpm start
ps ax | grep process
and you should see something along the lines of
5115 ? Ss 0:00 php-fpm: master process (/usr/local/php-5.6-cgi/etc/php-fpm.conf) 10068 ? Ss 0:08 php-fpm: master process (/etc/php-fpm.conf)
So php-fpm is working. Stop apache:
and switch from slow prefor to thread based which you were not able to do before because you were running mod_php instead of fastCGI. Edit /etc/sysconfig/httpd:
# # The default processing model (MPM) is the process-based # 'prefork' model. A thread-based model, 'worker', is also # available, but does not work with some modules (such as PHP). # The service must be stopped before changing this variable. # HTTPD=/usr/sbin/httpd.worker
Just remove the “#” before the “HTTPD=” Line. Restart apache:
and the new thread-based process should appear:
ps waux | grep http root 11765 0.0 0.0 115444 1164 ? Ss Mar28 0:05 /usr/sbin/httpd.worker apache 11768 0.0 0.1 2098104 3196 ? Sl Mar28 0:18 /usr/sbin/httpd.worker apache 11777 0.0 0.1 2098104 3264 ? Sl Mar28 0:17 /usr/sbin/httpd.worker apache 11834 0.0 0.1 2098104 3244 ? Sl Mar28 0:18 /usr/sbin/httpd.worker
Now, edit a vhost of your choice in which you want PHP 5.6 to be running, and simply add this line:
This is the magic line that makes this vhost run PHP 5.6, for PHP 5.3 do not add (or remove) the line.
Create a test.php file inside your docroot:
<?PHP phpinfo(); ?>
And browse to it:
Et Voila. Speed. Custom PHP. Twice.
As always. If ther are problems contact me.