Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to optimize php-fpm to improve performance

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly explains "how to optimize php-fpm to improve performance". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to optimize php-fpm to improve performance".

PHP is ubiquitous and can be said to be the most widely used language in Internet Web applications.

However, its high performance is not known, especially when it comes to highly concurrent systems. That's why languages such as Node (yes, I know it's not a language), Go, and Elixir are taking over such a particular use case.

That is, there are many things you can do to improve PHP performance on the server. This article focuses on php-fpm, which is the default configuration on the server if you use Nginx.

If you know what php-fpm is, please skip directly to the optimization section.

What is php-fpm?

Many developers are not interested in the knowledge of DevOps, and even those who are interested in it know very little about its underlying principles. Interestingly, when a browser sends a request to a server running PHP, PHP is not the first service to process the request; instead, the HTTP server, Apache and Nginx are the two main ones. The "web server" decides how to communicate with PHP, and then passes the type of request, data, and header information to the PHP process.

The above image shows the request-response life cycle of the PHP project (image source: ProinerTech)

In modern PHP applications, the "find file" section is the index.php file, which is the agent configured in the server configuration file to handle all requests.

Today, exactly how Web servers connect to PHP is evolving, and if we want to delve deeper into the details, the length of this article will soar. But roughly speaking, during the period when Apache was the preferred Web server, PHP was included as a module within the server.

So every time a request is received, the server will start a new process, which will automatically contain the PHP and execute the request. This method is called mod_php, an abbreviation for "PHP as a module". This approach has its limitations, and Nginx and php-fpm overcome it.

In php-fpm, the responsibility for managing PHP lies with the PHP program inside the server. In other words, the Web server (Nginx, in this case) doesn't care where or how PHP works, as long as it knows how to send and receive data. If necessary, in this case, you can think of PHP as another server that manages some of the child PHP processes of incoming requests (so we send the request to the server, which is received and passed on to the server-- crazy! :-P).

If you have used Nginx, you will see this code:

Location ~\ .php$ {try_files $uri = 404; fastcgi_split_path_info ^ (. +\ .php) (/. +) $; fastcgi_pass unix:/run/php/php7.2-fpm.sock; fastcgi_index index.php; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;}

For this line: fastcgi_pass unix:/run/php/php7.2-fpm.sock;, tells Nginx to communicate with the php process through php7.2-fpm.sock 's socket. Therefore, for each incoming request, Nginx writes data through this file and, after receiving the output, sends it back to the browser.

I must stress again that this is not the most complete or accurate for how to run it, but it is completely accurate for most DevOps tasks.

In addition, let's review what we have learned so far:

PHP does not receive requests sent by browsers directly. Web servers like Nginx will intercept it first.

The Web server knows how to connect to the PHP process and passes all the request data (paste everything) to the PHP.

When PHP completes its duties, it sends the response back to the Web server and then back to the client (in most cases, the browser).

The flow chart is as follows:

How do PHP and Nginx work together? (photo Source: data Dog)

So far so good, so the key question is: what exactly is PHP-FPM?

FPM in PHP stands for "fast process manager". Fancy interpretation means that the PHP running on the server is not a single process, but a number of PHP processes that are derived, controlled, and terminated by this FPM process manager. This is the process manager that the web server passes the request to.

PHP-FPM itself is a complete rabbit hole, so feel free to explore if you like, but these explanations are sufficient for our purpose. ?

Why optimize php-fpm?

In general, under normal operation, why should optimization be considered? Why not leave things as they are.

Ironically, I usually give advice for most use cases. If your settings work well and there are no special use cases, use the default settings. However, if you want to expand the power outside of a machine, it is essential to squeeze the maximum processing power out of a machine because it can reduce your server's cost in half (or more! ).

Another thing to note is that Nginx is built to handle huge workloads. It can handle thousands of connections at the same time, but if your PHP settings are not reasonable, you will waste a lot of resources, because Nginx must wait for PHP to complete the current processing before accepting the next request, and ultimately Nginx does not provide any advantage to your service!

So, let's take a look at exactly what we want to optimize when we try to optimize php-fpm.

How to optimize PHP-FPM?

Php-fpm 's configuration files may have different locations on different servers, so you need to do some research to determine its location. On UNIX, you can use the find command. On my Ubuntu, its path is / etc/php/7.2/fpm/php-fpm.conf. Of course, 7. 2 is the version of PHP I'm running.

Here are the first few lines of code for this file:

;; FPM Configuration;; All relative paths in this configuration file are relative to PHP's install; prefix (/ usr) This prefix can be dynamically changed by using the;'- p 'argument from the command line.; Global Options; [global]; Pid file; Note: the default prefix is / var; Default Value: nonepid = / run/php/php7.2-fpm.pid; Error log file; If it's set to "syslog", log is sent to syslogd instead of being written; into a local file. Note: the default prefix is / var; Default Value: log/php-fpm.logerror_log = / var/log/php7.2-fpm.log

It's obvious: this line pid = / run/php/php7.2-fpm.pid tells us which file contains the process id of the php-fpm process.

We also see that / var/log/php7.2-fpm.log is where php-fpm stores the logs.

In this file, add three variables like this:

Emergency_restart_threshold 10emergency_restart_interval 1mprocess_control_timeout 10s

The first two settings are warning, telling the php-fpm process that if 10 child processes fail within a minute, the main php-fpm process should restart itself.

This may not sound robust enough, but PHP is a short process that leaks memory, so restarting the main process in the event of a high failure can solve a lot of problems.

The third option is process_control_timeout, which tells the child process to wait so long before executing the signal received from the parent process. This setting is very useful. For example, when the parent process sends a termination signal, the child process is dealing with something. In ten seconds, they will have a better chance of completing the task and quitting gracefully.

Surprisingly, this is not the core configuration of php-fpm! This is because php-fpm has created a new process pool for web request services, which will have a separate configuration. In my example, the name of the process pool is www and the file I want to edit is / etc/php/7.2/fpm/pool.d/www.conf.

Let's look at the contents of the file:

; Start a new pool named 'www'.; the variable $pool can be used in any directive and will be replaced by the; pool name (' www' here) [www]; Per pool prefix; It only applies on the following directives:;-'access.log'; -' slowlog';-'listen' (unixsocket); -' chroot';-'chdir'; -' php_values';-'php_admin_values'; When not set, the global prefix (or / usr) applies instead. Note: This directive can also be relative to the global prefix.; Default Value: none;prefix = / path/to/pools/$pool; Unix user/group of processes; Note: The user is mandatory. If the group is not set, the default user's group; will be used.user = www-datagroup = www-data

Take a quick look at the end of the code snippet above and you can see why the server process is running as www-data. If you encounter file permissions problems when setting up a Web site, you may want to change the owner or group of directories to www-data, allowing the PHP process to write log files, upload documents, and so on.

Finally, we got to the root of the problem, the process Manager (pm) setting. In general, the default value is as follows:

Pm = dynamicpm.max_children = 5pm.start_servers = 3pm.min_spare_servers = 2pm.max_spare_servers = 4pm.max_requests = 200

So, what does "dynamic" mean here? I think the official documentation best explains this (I mean, this should already be part of the file you are editing, but I copied it here in case it isn't):

; 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. With this process management, there will be; always at least 1 children.; 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.; ondemand-no children are created at startup. Children will be forked when; new requests will connect. The following parameter are used:; pm.max_children-the maximum number of children that; can be alive at the same time.; pm.process_idle_timeout-The number of seconds after which; an idle process will be killed.; Note: This value is mandatory.

Thus, there are three available values:

Static: in any case, a fixed number of PHP processes will be maintained.

Dynamic: we need to specify the minimum and maximum number of processes that php-fpm will keep active at any given point in time.

Ondemand: create and destroy processes as required.

So what is the impact of these settings?

In short, if you have a site with small traffic, the "dynamic" setting is a waste of resources most of the time. Suppose your pm.min_spare_servers is set to 3, then three PHP processes will be created and kept running, even when the site has no traffic. In this case, "ondemand" is a better choice, allowing the system to decide when to start a new process.

On the other hand, sites with heavy traffic or must respond quickly will be punished in this case. It is best to avoid the extra overhead of creating a new PHP process, make it part of the pool, and monitor it.

Use pm = static to fix the number of child processes so that the maximum system resources are used for service requests instead of managing PHP. If you are sure to go this way, note that it has its guidelines and traps.

Thank you for your reading, the above is the content of "how to optimize php-fpm to improve performance". After the study of this article, I believe you have a deeper understanding of how to optimize php-fpm to improve performance, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report