Home Backend Development PHP Tutorial Understand PHP-FPM configuration and usage summary in one minute

Understand PHP-FPM configuration and usage summary in one minute

Jun 28, 2021 am 11:47 AM
fpm php

We have learned so much about PHP. I wonder if you have fully mastered the PHP-FPM configuration and usage summary. If not, then follow this article to continue learning

PHP-FPM configuration and usage summary:

PHP-FPM is a PHP FastCGI manager. It is actually a patch of the PHP source code, designed to convert the FastCGI process Management is introduced into the PHP software package. We must patch it into the PHP source code and then compile it before it can be used. Now we can open and use it directly in PHP 5.3.2 and newer versions, because PHP has included it in the software package from this version, so it no longer exists as a patch package.

· An understanding of several concepts

· Nginx PHP configuration

· Php-Fpm operation

1. An understanding of several concepts

1), CGI

CGI's full name is "Common Gateway Interface" (Common Gateway Interface). It is the interface through which the HTTP server communicates with programs on other machines. Its programs must run on the network server.

NOTE:

CGI can be written in any language as long as the language has standard input, output and environment variables.

2), FastCGI

FastCGI is a resident 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 important thing about CGI). The much-criticized fork-and-execute pattern). It also supports distributed computing, that is, FastCGI programs can be executed on hosts other than the website server and accept requests from other website servers.

FastCGI is a language-independent, scalable architecture CGI open extension. Its main behavior is to keep the CGI interpreter process in memory and thus obtain higher performance. We know that repeated loading of the CGI interpreter is the main reason for low CGI performance. If the CGI interpreter is stored in memory and accepted by the FastCGI process manager, it can provide good performance, scalability, etc.

Advantages:

1. FastCGI is language-independent;

2. FastCGI runs independently from the core web server, providing a more secure environment than API. APIs link an application's code with the core web server, meaning an application with the wrong API could break other applications or the core server. The malicious API application code can even steal the key of another application or core server;

3. FastCGI technology currently supports the following languages: C/C, Java, Perl, Tcl, Python, SmallTalk , Ruby, etc. Related modules are also available on popular servers such as Apache, ISS, Lighttpd;

4. FastCGI does not depend on the internal architecture of any web server, so even if server technology changes, FastCGI remains stable;

Disadvantages:

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. Multiply this number by 50 Or 100 is a very large memory number.

Nginx 0.8.46 PHP 5.2.14 (FastCGI) server has 30,000 concurrent connections. The 10 Nginx processes opened consume 150M memory (15M*10=150M), and the 64 php-cgi processes opened It consumes 1280M of memory (20M*64=1280M), plus the memory consumed by the system itself, the total consumption is less than 2GB of memory. If the server memory is small, you can only open 25 php-cgi processes, so that the total memory consumed by php-cgi is only 500M.

The above data is excerpted from Nginx 0.8.x PHP 5.2.13 (FastCGI) to build a web server that is ten times better than Apache (version 6).

Principle:

1. When the Web server starts, the FastCGI process manager is loaded;

2. The FastCGI process manager is initialized and starts multiple CGI interpreter processes ( PHP-CGI) and wait for the connection from the Web server;

3. When the client request reaches the Web server, the FastCGI process manager selects and connects to a CGI interpreter, and the Web server transfers the CGI environment variables and standard Input is sent to the FastCGI child process PHP-CGI.

4. After the FastCGI subprocess completes processing, it returns standard output and error information to the Web server from the same connection. When the FastCGI child process closes the connection, the request is processed. FastCGI The 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 situation, you can imagine how slow CGI is usually. Every Web request to PHP must re-parse php.ini, reload all extensions, and re-initialize all data structures. With FastCGI, all of this happens only once, when the process starts. Also, database persistent connections work.

NOTE:

The main advantage of FastCGI is to separate dynamic languages ​​​​from HTTP Server, so Nginx and PHP/PHP-FPM are often deployed on different servers to share the pressure on the front-end Nginx server and enable Nginx to exclusively handle static requests. and forward dynamic requests, while the PHP/PHP-FPM server exclusively parses PHP dynamic requests.

3), PHP-CGI

PHP-CGI is the FastCGI manager that comes with PHP.

Disadvantages of PHP-CGI:

1. After changing the php.ini configuration in php-cgi, you need to restart php-cgi to make the new php-ini take effect, and smooth restart is not possible.

2. If you kill the php-cgi process directly, php will not be able to run (PHP-FPM and Spawn-FCGI do not have this problem, the daemon process will smoothly regenerate new child processes).

4), Spawn-FCGI

Spawn-FCGI is a general FastCGI management server. It is part of lighttpd. Many people use Lighttpd. Spawn-FCGI performs management work in FastCGI mode, but it has many shortcomings. The emergence of PHP-FPM has somewhat alleviated some problems, but one disadvantage of PHP-FPM is that it needs to be recompiled, which may cause considerable risks (refer) to some already running environments. PHP can be used directly in PHP 5.3.3 -FPM.

Spawn-FCGI has now become a separate project, which is more stable and brings convenience to the configuration of many Web sites. Many sites have paired it with nginx to solve dynamic web pages. The latest lighttpd does not include this piece (http://www.lighttpd.net/search?q=Spawn-FCGI), but it can be found in previous versions. It is included in the lighttpd-1.4.15

version (http://www.lighttpd.net/download/lighttpd-1.4.15.tar.gz). The current download address of Spawn-FCGI is http ://redmine.lighttpd.net/projects/spawn-fcgi, the latest version is http://www.lighttpd.net/download/spawn-fcgi-1.6.3.tar.gz.

NOTE:

For the latest Spawn-FCGI, you can search for "Spawn-FCGI" on the lighttpd.net website to find its latest version release address.

5), compared to Spawn-FCGI

PHP-FPM is very convenient to use. The configuration is in the PHP-FPM.ini file, and startup and restart can be done from php/sbin /PHP-FPM. What is more convenient is that after modifying php.ini, you can directly use PHP-FPM reload to load it. 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 a lot of functions. performance improvement. The CPU recycling speed of the process controlled by PHP-FPM is relatively slow, and the memory is allocated evenly.

The CPU of the process controlled by Spawn-FCGI drops quickly, and the memory allocation is relatively uneven. There are many processes that appear to be unallocated, while others are highly occupied. It may be caused by uneven distribution of process tasks. This also leads to a decrease in overall response speed. The reasonable distribution of PHP-FPM leads to the mention of overall response and the average of tasks.

2. Nginx PHP configuration

1. Process number optimization

pm = dynamic

pm.max_children = 300

pm. start_servers = 20

pm.min_spare_servers = 5

pm.max_spare_servers = 35

2. Optimization of the maximum number of requests

pm.max_requests = 10240

NOTE:

This is used to deal with memory leaks caused by the PHP parser or referenced third-party libraries.

Maximum number of requests: refers to the number of requests that a php-fpm worker process will terminate after processing.

3. Maximum execution time optimization (php.ini)

request_terminate_timeout = 20

NOTE:

This is used to process the PHP execution time Solution to 502 error when it is too long.

This duration configuration can be configured in php.ini (max_execution_time) or php-fpm.conf. In order not to affect the global configuration, it can be implemented in php-fpm.conf.

It is worth noting that it needs to be configured in conjunction with max_fail (turn it larger) and fail_timeout (turn it smaller) in nginx.conf.

nginx.conf:

location ~ \.php$ {

fastcgi_connect_timeout 180;

fastcgi_read_timeout 600 ;

fastcgi_send_timeout       600;

}

NOTE:

The maximum execution time of the script set by PHP-FPM is already long enough However, when executing the time-consuming PHP script, I found that the Nginx error changed to a 504 error. This is because we only modified the PHP configuration, and Nginx also has configuration factcgi_connect/read/send_timeout regarding the timeout for communication with the upstream server.

4. php-fpm high CPU usage troubleshooting

top command:

After directly executing the top command, enter 1 to see the CPU usage of each core:


sar command:

Installation of sar and iostat commands:

sysstat.x86_64 : The sar and iostat systemmonitoring commands

yum install -y sysstat.x86_64

Execution:

$sar -P ALL 1 100

NOTE:

-P ALL means monitoring all cores;

1 means collecting every 1 second;

100 means collecting 100 times;

5, enable slow log

slowlog = log/$pool.log.slow

request_slowlog_timeout = 2

NOTE:

The above is the slow log of opening php-fpm, the time threshold is 2 seconds;

Execution:

grep -v "^$" php.slow.log | cut -d " " -f 3,2 | sort |uniq -c | sort -k1,1nr | head -n 50

NOTE:

sort: Sort words

uniq -c: Display the only line, and add the number of times this line appears in the file at the beginning of each line

Sort -k1,1nr: Sort by the first field, value, and in reverse order

head –n 10: Get the first 10 rows of data

PS:

The purpose of turning on the slow log is to track and analyze which php script execution time exceeds the set request_slowlog_timeout time , if this set time is exceeded, the script will be recorded.

3. Php-Fpm operation

php-fpm under PHP5.3.3 no longer supports php-fpm’s previous /usr/local/php/sbin/php-fpm(start |stop|reload) and other commands need to use signal control:

The master process can understand the following signals

INT, TERM terminate immediately;

QUIT terminate smoothly;

USR1 Reopen the log file;

USR2 Smoothly reload all worker processes and reload configuration and binary modules;

Example:

php-fpm Close: kill -INT`cat /usr/local/php/var/run/php-fpm.pid`

php-fpm Restart: kill -USR2`cat /usr/local/php/var/run/php -fpm.pid`

View the number of php-fpm processes:

$ps aux | grep -c php-fpm

Recommended learning: "PHP video tutorial

The above is the detailed content of Understand PHP-FPM configuration and usage summary in one minute. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

See all articles