FastCGI is a language-independent, scalable architecture CGI open extension, its main behavior is to convert the CGI interpreter The process remains in memory and therefore achieves higher performance. As we all know, repeated loading of the CGI interpreter is the main reason for low CGI performance. If the CGI interpreter remains in memory and accepts FastCGI process manager scheduling, it can provide good performance, scalability, Fail-Over features, etc.
The working principle of FastCGI is:
(1) The FastCGI process manager initializes itself, starts multiple CGI interpreter processes (multiple php-cgi processes) and waits for connections from the Web Server. In this article, the PHP-FPM process manager is used to start multiple php-cgi FastCGI processes. When starting the php-cgi FastCGI process, you can configure it to start in two ways: TCP and UNIX socket.
(2) When the client request reaches the Web server (Nginx), the Web server forwards the request to the FastCGI main process using the TCP protocol or UNIX socket method. The FastCGI main process selects and connects to a CGI interpreter (sub- process). The web server sends CGI environment variables and standard input to the FastCGI child process php-cgi.
(3)
After the FastCGI sub-process completes processing, it returns the standard output and error information to the Web server (Nginx) from the same connection.
When the FastCGI sub-process closes the connection, the request is notified that the processing is completed. The FastCGI child process then waits for and handles the next connection from the FastCGI process manager. In the normal CGI mode, php-cgi exits here.
So, you can imagine how slow normal CGI mode is. Every web request PHP must reparse php.ini, reload all extensions and reinitialize all data structures. With FastCGI, all of this happens only once, when the process starts. An added bonus is that persistent database connections work.
Advantages of PHP FastCGI:
(1) PHP scripts run faster. The PHP interpreter is loaded into memory instead of being read from memory each time it is needed, which greatly improves the performance of sites that rely on scripts.
(2) Requires less system resources. Since the server doesn't have to load the PHP interpreter every time it's needed, you can speed up your site a lot without increasing the load on the CPU.
(3) No changes to existing code are required. Programs running on Apache PHP can be adapted to PHP's FastCGI without modification.