Introduction to LNMP architecture, installation of PHP (php-fpm)

12.1 Introduction to LNMP Architecture

LNMP stands for: Nginx+MySQL+PHP web server architecture under Linux system. PHP in Nginx is combined with Nginx in the way of fastcgi, which can be understood as Nginx proxying PHP's fastcgi.

LNMP working mode

  • Unlike LAMP, LNMP provides web services using Nginx.
  • In the LNMP architecture, PHP exists as an independent service called php-fpm.
  • Nginx directly handles static requests (supports higher concurrency and is faster than Apache), and forwards dynamic requests to php-fpm for processing.

CGI, FastCGI, PHP-CGI and PHP-FPM concepts

CGI

The full name of CGI is "Common Gateway Interface" (Common Gateway Interface), a tool for the HTTP server to "talk" with programs on your or other machines, and the programs must run on the network server.
CGI can be written in any language as long as the language has standard input, output and environment variables. Such as php, perl, tcl and so on.

FastCGI

FastCGI is like a resident (long-live) CGI, it can be executed all the time, as long as it is activated, it will not take time to fork every time (this is the most criticized fork-and-execute mode of CGI ). It also supports distributed computing, that is, FastCGI programs can execute on hosts other than web servers and accept requests from other web servers.
FastCGI is a language-independent, scalable architecture open extension to CGI whose main behavior is to keep the CGI interpreter process in memory and thus achieve high performance. As we all know, the repeated loading of CGI interpreter is the main reason for the low performance of CGI. If the CGI interpreter is kept in memory and is scheduled by the FastCGI process manager, it can provide good performance, scalability, Fail-Over characteristics and so on.

FastCGI Features:

  1. FastCGI is language independent
  2. FastCGI's in-process applications, which run independently of the core web server, provide a more secure environment than APIs. APIs link the application's code with the core web server, which means that an application with a wrong API can damage other applications or the core server. A malicious API's application code can even steal another application's or core server's keys.
  3. FastCGI technology currently supports languages: C/C++, Java, Perl, Tcl, Python, SmallTalk, Ruby, etc. Related modules are also available on popular servers like Apache, ISS, Lighttpd, etc.
  4. FastCGI does not depend on the internal architecture of any web server, so even if the server technology changes, FastCGI remains stable.

How FastCGI works:

  1. Load FastCGI Process Manager (IIS ISAPI or Apache Module) when Web Server starts
  2. The FastCGI process manager initializes itself, starts multiple CGI interpreter processes (multiple php-cgi visible) and waits for a connection from the Web Server.
  3. When a client request arrives at the Web Server, the FastCGI process manager selects and connects to a CGI interpreter. The web server sends CGI environment variables and standard input to the FastCGI subprocess php-cgi.
  4. The FastCGI subprocess returns standard output and error messages from the same connection to the Web Server after processing. The request is processed when the FastCGI child process closes the connection. The FastCGI child process then waits for and handles the next connection from the FastCGI process manager (running in the Web Server). In CGI mode, php-cgi exits here.

In the above case, you can imagine how slow CGI is usually. Every web request PHP has to reparse php.ini, reload all extensions and reinitialize all data structures. With FastCGI, all this happens only once when the process starts. An added bonus is that persistent database connections work.

Disadvantages of FastCGI:
Because it is multi-process, it consumes more server memory than CGI multi-threading. The PHP-CGI interpreter consumes 7 to 25 megabytes of memory per process. Multiplying this number by 50 or 100 is a large number of memory.
Nginx 0.8.46+PHP 5.2.14 (FastCGI) server consumes 150M memory (15M* 10=150M) under 30,000 concurrent connections, and 64 php-cgi processes open consume 1280M memory (20M *64=1280M), plus the memory consumed by the system itself, consumes less than 2GB of memory in total. If the server memory is small, only 25 php-cgi processes can be opened, so that the total memory consumed by php-cgi is only 500M.

PHP-CGI

PHP-CGI is the FastCGI manager that comes with PHP.
Disadvantages of PHP-CGI:

  1. After php-cgi changes the php.ini configuration, you need to restart php-cgi to make the new php-ini take effect, and it cannot restart smoothly.
  2. Kill the php-cgi process directly, and php will not run. (PHP-FPM and Spawn-FCGI do not have this problem, the daemon will smoothly respawn new child processes.)

PHP-FPM

PHP-FPM is a PHP FastCGI manager for PHP only and can be downloaded at  http://php-fpm.org/download  .
PHP-FPM is actually a patch to the PHP source code, designed to integrate FastCGI process management into PHP packages. It must be patched into your PHP source code before it can be used after compiling and installing PHP.
PHP5.3.3 has integrated php-fpm and is no longer a third-party package. PHP-FPM provides a better PHP process management method, which can effectively control memory and processes, and can smoothly reload PHP configuration. It has more advantages than spawn-fcgi, so it is officially included by PHP. You can enable PHP-FPM with the --enable-fpm parameter in ./configure.

Spawn-FCGI

Spawn-FCGI is a general FastCGI management server, which is a part of lighttpd. Many people use Lighttpd's Spawn-FCGI for management in FastCGI mode, but there are many shortcomings. The emergence of PHP-FPM has alleviated some problems to some extent, but PHP-FPM has a disadvantage that it needs to be recompiled, which may have a lot of risk (refer) for some already running environments. It can be used directly in php 5.3.3 PHP-FPM too.
Spawn-FCGI has now become an independent project, which is more stable and brings convenience to the configuration of many Web sites. There are already many sites that use it with nginx to solve dynamic web pages.
Note:  The latest Spawn-FCGI can go to lighttpd.net website and search for "Spawn-FCGI" to find its latest release address.

PHP-FPM vs spawn-CGI

The use of PHP-FPM is very convenient, the configuration is in the file of PHP-FPM.ini, and the startup and restart can be performed from php/sbin/PHP-FPM. What is more convenient is that after modifying php.ini, you can directly use PHP-FPM reload to load, and you can complete the modification and loading of php.ini without killing the process.
The results show that using PHP-FPM can make php have no small performance improvement. The CPU recovery speed of the process controlled by PHP-FPM is relatively slow, and the memory allocation is very uniform.
The CPU of the process controlled by Spawn-FCGI drops rapidly, and the memory allocation is uneven. There are a lot of processes that seem to be unallocated, while others are very busy. It may be caused by uneven distribution of process tasks. And this also led to a drop in overall responsiveness. The reasonable distribution of PHP-FPM results in the mention of the overall response and the average of the tasks.

This section is taken from:  http://www.nowamagic.net/librarys/veda/detail/1319/

12.2 Installing MySQL

Uninstall MySQL

Directly delete related files during MySQL installation.

[root@1 ~]# rm -rf /usr/local/mysql 
[root@1 ~]# rm -rf /etc/init.d/mysqld 
[root@1 ~]# rm -rf /data/mysql

Install MySQL

The method of installing MySQL in LNMP environment and LAMP environment is the same.

12.3-12.4 PHP Installation

It is different from installing PHP with LAMP, you need to open the php-fpm service.

Ready to work

Uninstall & unzip the installation package

[root@1 ~]# cd /usr/local/src/

下载安装包:
[root@1 src]# wget http://cn2.php.net/distributions/php-5.6.30.tar.gz  

解压:
[root@1 src]# tar zxvf php-5.6.30.tar.gz

Create an account

[root@1 src]# useradd -s /sbin/nologin php-fpm

Note:  This account is used to run the php-fpm service, because in the LNMP environment, PHP exists independently as a service.

install php

If you have installed PHP before, you need to clear its original configuration:

[root@1 src]# cd php-5.6.30
[root@1 src]# make clean

Environment configuration

[root@1 src]# cd php-5.6.30

[root@1 src]# ./configure --prefix=/usr/local/php-fpm --with-config-file-path=/usr/local/php-fpm/etc --enable-fpm --with-fpm-user=php-fpm --with-fpm-group=php-fpm --with-mysql=/usr/local/mysql --with-mysqli=/usr/local/mysql/bin/mysql_config --with-pdo-mysql=/usr/local/mysql --with-mysql-sock=/tmp/mysql.sock --with-libxml-dir --with-gd --with-jpeg-dir --with-png-dir --with-freetype-dir --with-iconv-dir --with-zlib-dir --with-mcrypt --enable-soap --enable-gd-native-ttf --enable-ftp --enable-mbstring --enable-exif --with-pear --with-curl  --with-openssl  

Error:
Error 1:

configure: error: xml2-config not found. Please check your libxml2 installation.

Solution:

[root@1 php-5.6.30]# yum list |grep libxml2  

查找相关库的安装包:
[root@1 php-5.6.30]# yum list |grep libxml2
libxml2.x86_64                          2.9.1-6.el7_2.3                @anaconda
libxml2.i686                            2.9.1-6.el7_2.3                base     
libxml2-devel.i686                      2.9.1-6.el7_2.3                base     
libxml2-devel.x86_64                    2.9.1-6.el7_2.3                base     
libxml2-python.x86_64                   2.9.1-6.el7_2.3                base     
libxml2-static.i686                     2.9.1-6.el7_2.3                base     
libxml2-static.x86_64                   2.9.1-6.el7_2.3                base     

选择包进行安装:  
[root@1 php-5.6.30]# yum install -y libxml2 libxml2-devel

Error 2:

configure: error: Cannot find OpenSSL's <evp.h>

Solution:

[root@1 php-5.6.30]# yum install -y openssl openssl-devel

Error 3:

configure: error: Please reinstall the libcurl distribution -
    easy.h should be in <curl-dir>/include/curl/

Solution:

[root@1 php-5.6.30]# yum install -y libcurl libcurl-devel

Error 3:

configure: error: jpeglib.h not found.

Solution:

[root@1 php-5.6.30]# yum install -y libjpeg libjpeg-turbo-devel 

Error 4:

configure: error: png.h not found.

Solution:

[root@1 php-5.6.30]# yum install -y libpng libpng-devel

Mistake 5:

configure: error: freetype-config not found.

Solution:

[root@1 php-5.6.30]# yum install -y freetype freetype-devel

Mistake 6:

configure: error: mcrypt.h not found. Please reinstall libmcrypt.

Solution:

[root@1 php-5.6.30]# yum install -y libmcrypt libmcrypt-devel

Description:  After each error is reported, follow the prompts to find the installation package of the corresponding library, select the package to install, and reconfigure it after the installation is complete!

Check after the configuration is complete:

[root@1 php-5.6.30]# echo $?
0

To summarize the packages that need to be installed:

[root@1 php-5.6.30]#  yum install  -y  gcc gcc-c++ libxml2-devel openssl-devel libcurl-devel libjpeg-devel libpng-devel freetype libmcrypt-devel

Compile & Install

Compile:

[root@1 php-5.6.30]# make 

Error: virtual memory exhausted: Cannot allocate memory #Virtual memory exhausted: Cannot allocate memory

Solutions:
1. Stop the processes that are not in use in the virtual machine
2. Temporarily increase the memory of the swap partition:

[root@1 ~]# dd if=/dev/zero of=/tmp/newdisk bs=1M count=100  手动创建一个新分区
记录了100+0 的读入
记录了100+0 的写出
104857600字节(105 MB)已复制,5.72931 秒,18.3 MB/秒
[root@1 ~]# du -sh /tmp/newdisk
100M	/tmp/newdisk
[root@1 ~]# mkswap /tmp/newdisk  格式化该swap分区
正在设置交换空间版本 1,大小 = 102396 KiB
无标签,UUID=d42e907a-aae0-4d5f-bf58-586fac415f48
[root@1 ~]# free -m  
              total        used        free      shared  buff/cache   available
Mem:            984         114         626           6         244         706
Swap:          2047           0        2047
[root@1 ~]# swapon /tmp/newdisk  挂载到原swap分区
swapon: /tmp/newdisk:不安全的权限 0644,建议使用 0600。
[root@1 ~]# free -m
              total        used        free      shared  buff/cache   available
Mem:            984         114         626           6         244         707
Swap:          2147           0        2147
[root@1 ~]# chmod 0600 /tmp/newdisk  更改权限以保安全

待PHP编译完成后要卸载掉该分区
[root@1 ~]# swapoff /tmp/newdisk   卸载分区

Install:

[root@1 php-5.6.30]# make install

php-fpm related commands:

Two ways to execute PHP related commands:

方法1:
[root@1 php-fpm]# /usr/local/php-fpm/sbin/php-fpm -m

方法2:
[root@1 php-fpm]# /usr/local/php-fpm/bin/php -m

php-fpm configuration file syntax detection:

[root@1 php-fpm]# /usr/local/php-fpm/sbin/php-fpm -t

configure

Add configuration file

Add the configuration file to the php-fpm configuration files directory:

[root@1 php-5.6.30]# cp php.ini-production /usr/local/php-fpm/etc/php.ini

Profile debugging

切换至配置文件所在目录:
[root@1 php-5.6.30]# cd /usr/local/php-fpm/etc/  

手动添加配置文件,写入如下内容:
[root@1 etc]# vim php-fpm.conf

[global]
#定义全局参数
pid = /usr/local/php-fpm/var/run/php-fpm.pid
error_log = /usr/local/php-fpm/var/log/php-fpm.log
[www]
listen = /tmp/php-fcgi.sock
#监听地址,也可以写:listen = 127.0.0.1::9000,本地监听,也可以监听其他IP:port
#此处格式会影响配置Nginx和PHP结合时Nginx寻址PHP的路径
listen.mode = 666
#当监听的为socket文件时该部分才生效,用于指定.sock文件的权限
user = php-fpm
group = php-fpm
#定义php-fpm服务的用户
pm = dynamic
pm.max_children = 50
pm.start_servers = 20
pm.min_spare_servers = 5
pm.max_spare_servers = 35
pm.max_requests = 500
rlimit_files = 1024
#以上部分为进程相关信息

Configure startup scripts

切换至文件源目录:
[root@1 etc]# cd /usr/local/src/php-5.6.30

添加启动脚本到系统配置:
[root@1 php-5.6.30]#  cp sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm

更改文件权限:
[root@1 php-5.6.30]# chmod 755 /etc/init.d/php-fpm

添加到系统服务:
[root@1 php-5.6.30]# chkconfig --add php-fpm
设置开机启动:
[root@1 php-5.6.30]# chkconfig php-fpm on  

启动php-fpm服务:
[root@1 php-5.6.30]# service php-fpm start
Starting php-fpm  done

12.5 Introduction to Nginx

Nginx ("engine x") is a lightweight web server/reverse proxy server and email (IMAP/POP3) proxy server distributed under a BSD-like protocol. Its characteristics are that it occupies less memory and has strong concurrency capability. In fact, the concurrency capability of nginx is indeed better among web servers of the same type. Users of nginx websites in mainland China include: Baidu, Sina, NetEase, Tencent, Taobao, etc.

Nginx application scenarios:

web server, reverse proxy, load balancing

Nginx branch

Taobao's Tengine based on Nginx is used in the same way as Nginx. The service name and configuration file name are the same. The biggest difference from Nginx is that Tengine has added some customized modules, which are outstanding in terms of security speed limit. In addition, it supports js, css merge.

Nginx core + lua related components and modules form a high-performance web container openresty that supports lua, refer to http://jinnianshilongnian.iteye.com/blog/2280928

OpenResty

OpenResty is a high-performance web platform based on Nginx and Lua, which integrates a large number of sophisticated Lua libraries, third-party modules and most of its dependencies. It is used to easily build dynamic web applications, web services and dynamic gateways that can handle ultra-high concurrency and scalability.
OpenResty effectively turns Nginx into a powerful general-purpose web application platform by bringing together various well-designed Nginx modules (mainly developed by the OpenResty team). In this way, web developers and system engineers can use the Lua scripting language to mobilize various C and Lua modules supported by Nginx to quickly construct high-performance web application systems that are capable of 10K or even more than 1000K single-machine concurrent connections.
The goal of OpenResty® is to let your web services run directly inside Nginx services, taking full advantage of Nginx's non-blocking I/O model, not only for HTTP client requests, but even for remote backends such as MySQL, PostgreSQL, Memcached and Redis etc. for a consistent high-performance response.
This section is taken from:  http://openresty.org/cn/

take

Lua is a lightweight, embeddable scripting language that can be easily embedded in other languages. In addition, Lua provides coroutine concurrency, that is, asynchronous execution in the form of synchronous calls to achieve concurrency. Compared with the concurrency of the callback mechanism, the code is easier to write and understand, and it is easier to troubleshoot problems. Lua also provides a closure mechanism, functions can be passed as First Class Value parameters, and it implements mark-to-clear garbage collection.
Because Lua is small and lightweight, you can embed a Lua VM in Nginx, create a VM when the request is made, and recycle the VM when the request ends.

ngx_lua

ngx_lua is a module of Nginx, which embeds Lua into Nginx, so that Lua can be used to write scripts, so that application scripts can be written in Lua and deployed to Nginx to run, that is, Nginx becomes a web container; so that developers can You can use Lua language to develop high-performance web applications.
ngx_lua provides many APIs for interacting with Nginx (API is a calling interface left by the operating system to the application. The application makes the operating system execute the command/action of the application by calling the API of the operating system.), for developers You only need to learn these APIs to develop functions. For developing web applications, if you have contacted Servlet, its development is similar to Servlet. It is nothing more than knowing how to receive requests, parse parameters, process functions, and return responses. What the API looks like in a few steps.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325431950&siteId=291194637