search
HomeBackend DevelopmentPHP TutorialUnderstand PHP-FPM configuration and usage summary in one minute

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
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)