The operating principle of appache and nginx

Web server

Web server, also known as WWW (WORLD WIDE WEB) server, the main function is to provide online information browsing service.

HTTP application layer protocol.

HTML document format.

Browser Uniform Resource Locator (URL).

Web servers often B / S (Browser / Server) mode to provide services. Browser and server interaction is as follows:


 GET /index.php HTTP/1.1

 +---------------+                   +----------------+
 |               +------------------->                |
 |   Browser     |                   |   Server       |
 |               <-------------------+                |
 +---------------+                   +----------------+

                   HTTP/1.1 200 OK
 

Browser sends an HTTP request (Request) to the server.

Browser server receives the request data, after analysis, the response data (the Response) to the browser output.

Browser receives the response data to the server, after analysis, the final results are displayed in the browser.

Apache and Nginx belong to the Web server, both of which have achieved the HTTP 1.1 protocol.

Apache Overview

Apache HTTPServer is an open source web server Apache Software Foundation, can run on most computer operating system, due to its cross-platform and security. Is widely used Web server software is one of the most popular. It is fast, reliable, and can be expanded through a simple API, the Perl / Python, etc. interpreter built into the server. -- Wikipedia

Apache components

Apache is based on modular design, it is not much of the core code, most of the functions are distributed among the various modules, each module loaded on demand when the system starts.


"text">         +----------+
      +- | Module   | -----------------+
      |  +----------+                  |
      |                          +------------+
+-----------+   Apache HTTPD     | php module |
| Module    |                    +------------+
+-----------+              +----------+|
      +----------+-------- |  MPM     |+
                 |         +----+---+-+
               +-v-----------+  |   |
               |    ARP      <--+   |
               +------+------+      |
                      |             |
      +---------------v-------------v--+
      |      Operating  System         |
      +--------------------------------+
 

MPM (Multi -ProcessingModules, multiprocessing module) is one of the core components of Apache, Apache to use the resources of the operating system by MPM, for process and thread pool management. Apache In order to obtain the best operating performance for different platforms (Unix / Linux, Window) is optimized to provide a different MPM for different platforms, users can choose according to the actual situation, in which the most commonly used are MPM prefork and worker two kinds. As far as your server is running in what way, depending on the installation process of Apache MPM compile parameters specified in the X default compiler parameters for the prefork.

Since most Unix does not support true threads, so the use of pre-derived sub-process (prefork) way, like Windows or Solaris threads support these platforms, based on multi-process multi-threaded mixed mode worker is a good choice. In Apache Another important component is the APR (Apacheportable RuntimeLibrary), namely Apache Portable Runtime library, which is a library of abstract operating system calls, using Apache used to implement the internal components of the operating system, improve the system's portability sex. Apache to parse php, that is, by many in the php Module Module to complete.

Apache life cycle
"text"> + ------------------------------------------ + --------------------
   | + --------------------- + start-up phase |
   | | system startup configuration | |
   | + ---------- + ---------- + |
   | | |
   | + ---------- v --- + ------- |
   | | module initialization | |
   | + - + -------- + -------- + - + |
   | | | | |
   | + - ----------- + | + ------ v ------- + | + -------------- + |
   | | Sub-process initialization | <+ | sub-process initialization | +> | sub-process initialization | |
   | + ------ + ------ + ---- + ------- + - + + ------- + ------ + |
   + ----------------------------- + ---------------------------------
   | | | | operational phase |
   | + ---- V - - + v + ---- + ---- + ---- + ---- v |
   | | request circulation | | request circulation | | request circulation | |
   | + ---- + --- - + + ---- + ---- + + ---- + ---- + |
   | | | | |
   | + ------ + ------ + --- v v ------ + ------ + --- v ------ + |
   | | child process ends | | end child process | | end child process | |
   | + ---- --------- + + ------------- + + ------------- + |
   +--------------------------------------------------------------+
 

This life cycle is a schematic perfork at work, it can be seen from the figure, Apache must start a separate process for each request to process.

Apache's mode of operation prefork the working principle

A single control process (the parent) is responsible for producing the child, the child process for monitoring these requests and respond. Apache always tries to keep some spare (spare) or sub-processes are idle for the impending request. The client will not have to wait to produce the child before to get the service. On Unix systems, the parent process is usually port 80 for bonding to run as root, while Apache child processes generated typically run at a low privileged user. User and Group instructions for low-privileged user to configure the child process. Users running child process must have permission to read the contents of his services, but other resources outside services must have the least possible privileges.

worker works

The number of threads per process can have is fixed. The server will increase or decrease the number of processes depending on the load. A single control process (the parent) is responsible for establishing the child process. Each child process to establish ThreadsPerChild number of service threads and a listening thread, the listener thread listens access request and delivery service threading and reply to. Apache always tries to maintain a standby (spare) or idle service thread pool. In this way, clients do not need to wait for the establishment of a new process or a new thread can be processed. In Unix, to be able to bind to port 80, the parent process is generally started as root, then, Apache child processes and threads in order to establish a low-privileged user. User and Group Permissions instructions for configuring Apache child processes. Although the child must have read access to their content provided, but should give him less privileged as possible. In addition, unless the suexec, otherwise, these instructions to configure the permissions will be inherited by CGI scripts.

Apache running start-up phase

During the startup phase, Apache main configuration file parsing (e.g. http.conf Include instructions and setting configuration file, etc.), load module (e.g. MOD php.so, MOD perl.so etc.) initialization and system resources (such as log files, shared memory segment, etc.) work. At this stage, Apache in order to obtain maximum system resources usage rights will be privileged user root (X systems) or super administrator administrator (Windows systems) to complete startup.

This process can be used to understand by the following figure:


"text"> + -------- +
       | start |
       + ---- + --- +
            |
 + ---------- ---------- v - + http.conf parses the main configuration file in the configuration information,
 | analytical profile | like the LoadModule, the AddType
 + ---------- + ----------------------- + instructions such as is loaded into memory
            |
 + ------------ + ---------- v basis AddModule, LoadModule and other instructions
 | load static / dynamic module | loaded Apache modules, like mod_php5. so is
 + ---------- + ------------ + loaded into memory, the address space mapped to the Apache.
            |
 + ------------ + ---------- v log files, shared memory segments, database links
 | resources system initialization | such as initialization
 + ------- + ------------ + ---
            |
        + --- v ---- +
        | end |
        + -------- +


operational phase

In the operational phase, Apache main job is to handle user service requests. At this stage, Apache users to give up privilege levels, use ordinary authority, which is mainly based on security considerations, to prevent security breaches due to defects in the code caused.

Since the Apache Hook mechanism, allowing Apache module (includes an internal module and the external modules, e.g. mod_php5.so, mod_perl.so etc.) injected into the custom function request processing cycle. mod_php5.so/php5apache2.dll custom function is to contain, by injection into Apache Hook mechanism, responsible for handling the request at each stage of Apache php processing flow.

Apache request processing cycle is divided into 11 phases, followed by: Post-Read-Request, URITranslation, Header Parsing, AccessControl, Authentication, Authorization, MIME TypeChecking, FixUp, Response, Logging, CleanUp.

Apache http request processing lifecycle:

 

Post-Read-Request Phase: normal request processing flow, which is the first stage module can be inserted into the hook. For those who want early into the processing module requests, this stage may be utilized.

URI Translation stage: Apache main job at this stage: URL maps request to the local file system. Hook module can be inserted at this stage, to perform their own mapping logic. mod_alias is the use of this phase of the work.

Header Parsing stage: Apache in the main work phases: check request header. Since the module may perform the inspection task request header at any point request processing flow, so that the hook is rarely used. mod_setenvif is the use of this phase of the work.

Access Control stage: Apache main work in this phase: Depending on the configuration file to check whether to allow resource access requests. Apache standard logic commands to achieve the allow and deny. MOD authz Host is the use of this phase of the work.

Authentication phase: Apache main work in this phase: a user is authenticated in accordance with the policy profile settings, and set the user name field. Hook module can be inserted at this stage, to implement a authentication method.

Authorization phase: Apache main work in this phase: whether to allow authenticated user perform the requested operation according to the profile. Hook module can be inserted at this stage, to achieve a method of user rights management.

MIME Type Checking phase: Apache main job at this stage: the rules according to the MIME type of the requested resource to be used determines the content handlers. Standard modules MOD negotiation and MOD MIME implements this hook.

FixUp Phase: This is a common stage, prior to allowing the content generator module, any necessary operation processes. And Post the Read Request Similarly, it is a hook able to capture any information, the hook is the most commonly used.

Response phase: Apache main work in this phase: generating content returned to the client, the client is responsible to send an appropriate reply. This stage is the core part of the overall treatment process.

Logging stage: Apache main work in this phase: After recording the transaction reply has been sent to the client. Apache modules may modify or replace the standard logging.

CleanUp stage: Apache at this stage the main work: cleaning up this request after the completion of the transaction legacy environment, such as processing files, directories or Socket closed and so on, this is the last time a stage of Apache request processing.

Nginx Overview

Nginx (pronounced with engine x) is developed by a Russian programmer IgorSysoev lightweight web server, reverse proxy server and e-mail (IMAP / POP3) proxy server. Russia initially for a large portal and search engine Rambler (Russian: Рамблер) use. -- Wikipedia

The module works with Nginx

Nginx by the kernel and modules, where the kernel is very small and compact design, the work done is very simple, just by looking profile client requests mapped to a locationblock (location is a command Nginx configuration for URL match), and each instruction in this location will be configured in different modules to start to complete the work.

Nginx modules are divided into core modules, base modules and third-party modules from the structure:

Core modules: HTTP module, EVENT modules and module MAIL

The base module: HTTP Access module, HTTP FastCGI module, HTTP Proxy module and HTTPRewrite module,

Third-party modules: HTTP Upstream Request Hash module, Notice modules and HTTP AccessKey module.

The module is divided into the following three categories Nginx from the function:

The Handlers (processor modules). Such modules directly process the request, and outputs the content information and the like headers and modification operations. Handlers processor modules typically have only one.

The Filters (filter block). Such other content module of the processor module output modification operations, the final output from the Nginx.

The Proxies (proxy class module). These modules are the HTTPUpstream like Nginx modules, some of the main and back-end services such as FastCGI, etc. interact to achieve service proxy and load balancing capabilities.


"text">                     +                    ^
        Http Request |                    |  Http Response
                     |                    |
    +---------+------v-----+         +----+----+
    |  Conf   | Nginx Core |         | FilterN |
    +---------+------+-----+         +----^----+
                     |                    |
                     |               +----+----+
                     |               | Filter2 |
choose a handler     |               +----^----+
based conf           |                    |
                     |               +----+----+
                     |               | Filter1 |
                     |               +----^----+
                     |                    | Generate content
               +-----v--------------------+----+
               |           Handler             |
               +-------------------------------+
 

Nginx itself do little actual work, when it received an HTTP request, it is only by looking up the configuration file to map the request to a locationblock, and each instruction in this location will be configured in different modules to start to complete the work, so the module can be seen as Nginx real labor workers. In a location generally involves a command handler module and a plurality of filter modules (of course, a plurality of location can be shared with the same module). handler module is responsible for handling requests, generated in response to the completion of the content, and content filter module for processing the response.

Nginx architecture and workflow

 

The figure is Nginx of architecture that is similar to the Apache Worker working condition, Nginx each Worker process manages a large number of threads, the thread is the real deal with requests under the Worker.

In fact all the business logic in worker process. worker process has a function to perform an infinite loop, constantly processing requests from clients received and processed until the entire nginx service is stopped. Worker in this function is executed reads as follows:

Mechanisms (such as epoll, kqueue, etc.) generated by the operating system-related events.

Receiving and processing these events, the case received data, the resulting higher level of request object.

The processing request header and body.

Respond and send back to the client.

The completion of the processing request.

Re-initialize the timer and other events.

Nginx和FastCGI FastCGI

FastCGI is telescopically a high speed interface for communicating between the HTTP server and dynamic scripting language. The most popular HTTPserver support FastCGI, including Apache, Nginx and lighttpd and so on. At the same time, FastCGI also many scripting languages, among them PHP.

FastCGI is the development of improvements comes from CGI. The main drawback of traditional CGI interface mode is poor performance, as you will need to restart the script every time the parser encounters HTTP server program to perform dynamic resolution, then returns the results to the HTTP server. It is almost not available when dealing with high concurrent access. In addition traditional CGI interface mode security is also poor, is now rarely used.

FastCGI interface mode using C / S structure, and can be distinguished from the HTTP server script analyzing server, start script analyzing the one or more script analyzing daemon on the server. When the HTTP server every time they meet a dynamic program that can be delivered directly to the FastCGI process is performed, then the result will be returned to the browser. This way you can make an HTTP server requests exclusively dealing with static or dynamic result script server back to the client, which improves the performance of the entire application system to a large extent.

Nging and FastCGI cooperation

Nginx does not support direct calls to external programs or resolve all external programs (including PHP) must be called via FastCGI interface. FastCGI interface is a socket under Linux (This socket can be a file socket, can also be ipsocket).

The next process to run under Nginx PHP to illustrate. PHP-FPM is managed FastCGI a manager, it exists as a PHP plug-ins.

FastCGI Process Manager php-fpm own initialization, starts the main process php-fpm and start start_servers a child CGI process. The main process php-fpm mainly fastcgi child process management, listening 9000 port. fastcgi child process waits for a connection from the WebServer.

When a client request arrives Web ServerNginx is, by location Nginx instruction to all php suffix 127.0.0.1:9000 file to be processed, i.e. by location Nginx instruction to all the file with the extension php are cross to 127.0.0.1:9000 to deal with.

FastCGI Process Manager PHP-FPM selected and connected to a sub-process CGI interpreter. Webserver will be sent to the child process FastCGI CGI environment variables and the standard input.

FastCGI child process to complete the process after the standard output and error messages from the same connection returns WebServer. When the child FastCGI process closes the connection request will come to complete the process.

FastCGI child process then waits for and FastCGI process manager process from the lower (running in the WebServer) is connected.

Apache and Nginx compare feature comparison

Nginx and Apache, are HTTP server software, implement the same functions are modular design, supports universal language interface, such as PHP, Perl, Python, etc., and also supports forward and reverse proxy, web hosting, URL rewriting, compression and transmission, SSL encryption transmission.

Implement the same functions, all Apache modules supported by the dynamic and static compilation, and Nginx modules are statically compiled,

For FastCGI support, Apache support Fcgi bad, but Nginx support for Fcgi is very good;

In the connection process, Nginx support epoll, but does not support Apache;

On the use of space, Nginx installation package is only a few hundred K, compared with Apache and Nginx is definitely a monster.

Nginx advantages relative apache

Lightweight, also from the web service, take up less memory than apache and resources

Static process, Nginx static processing performance more than three times higher than the Apache

Anti concurrent, non-blocking Nginx processing request is asynchronous, and the apache is blocked type, low resource consumption Nginx high performance can be maintained under high concurrency. In Apache + PHP (prefork) mode, if a large front-end PHP or slow processing of cases under pressure, it is prone to Apache soaring number of processes, thereby denying the phenomenon services.

Highly modular design, relatively simple to write a module

Community activists, all kinds of high-performance modules produced rapidly ah

apache advantages relative nginx

rewrite, rewrite nginx powerful than the

Module over more basic thought can be found

Little bug, nginx relatively large number of bug

Ultra-stable

Apache support for PHP is relatively simple, Nginx need to cooperate with other back-end

Select Nginx's advantage

As a Web server: Nginx static files, index files, automatic indexing efficiency is very high.

As a proxy server, Nginx can be achieved without caching reverse proxy to accelerate and improve site speed.

As a load balancing server, Nginx either directly support within the Rails and PHP, it can also support HTTP proxy server in foreign service, and also supports the use of a simple algorithm of fault tolerance and load balancing.

In terms of performance, Nginx is designed for performance optimization and development, achieve great emphasis on efficiency. It uses the kernel Poll model (epoll and kqueue), can support more concurrent connections can support up to 50 respond to 000 concurrent connections, and only takes a very low memory resources.

In terms of stability, Nginx has taken a phased resource allocation technology, making the CPU and memory occupancy rate is very low. Nginx official said, Nginx does not keep the 10 000 active connections, but these connections occupies only 2.5MB of memory, therefore, DOS attacks like this for Nginx is basically no effect.

In terms of high availability, Nginx supports hot deployment, especially startup speed quickly, so you can, or configure the software version upgrade without interruption of service, even if the run for months without restarting too, can be done almost 7 × 24 hours run uninterrupted.

Use Nginx and Apache

Because of Nginx and Apache respective advantages, many people chose to let the two coexist in the server. On the server side so that the front Nginx, Apache after. The Nginx to do load balancing and reverse proxy, and static files, speak dynamic requests (such as PHP applications) to Apache to handle

Released eight original articles · won praise 13 · views 60000 +

Guess you like

Origin blog.csdn.net/qq_37655695/article/details/60966926