Nginx from entry to practice
1. Introduction to Nginx
In a traditional web server, each client connection is handled as a separate process or thread. When switching tasks, the CPU needs to be switched to a new task and a new runtime context is created, which consumes additional memory and CPU time. When concurrent As requests increase, the server responds more slowly, negatively impacting performance.
Nginx is an open-source, high-performance, highly reliable web and reverse proxy server, and it supports hot deployment. It can run almost 7 * 24 hours a day without restarting even if it runs for several months. In the case of service, hot update the software version. Performance is the most important consideration for Nginx. It occupies less memory, has strong concurrency capabilities, and can support up to 50,000 concurrent connections. Most importantly, Nginx is free and commercialized, and its configuration is relatively simple.
The most important usage scenarios of Nginx:
1. Static resource service, providing service through local file system;
2. Reverse proxy service, including caching, load balancing, etc.;
3. API service, OpenResty;
For the front end, Node.js is no stranger. Many concepts of Nginx and Node.js are similar, such as HTTP server, event-driven, asynchronous and non-blocking, etc., and most of the functions of Nginx can also be realized using Node.js, but Nginx and Node.js .js does not conflict, each has its own area of expertise. Nginx is good at the processing of underlying server-side resources (static resource processing and forwarding, reverse proxy, load balancing, etc.), while Node.js is better at processing specific business logic at the upper layer. The two can be perfectly combined to jointly help front-end development.
Let's focus on learning how to use Nginx.
2. Related concepts
2.1 Simple and non-simple requests
First, let's understand simple requests and non-simple requests. If the following two conditions are met at the same time, it is a simple request:
1. The request method is one of HEAD, GET, and POST;
2. The HTTP header information does not exceed the fields on the right: Accept, Accept-Language, Content-Language, Last-Event-IDContent-Type are limited to three values application/x-www-form-urlencoded, multipart/form-data , text/plain;
Any request that does not meet these two conditions at the same time is a non-simple request.
Browsers handle simple and non-simple requests differently:
simple request
For simple requests, the browser will add the Origin field in the header information and send it directly. The Origin field is used to indicate which source (protocol + domain name + port) this request comes from.
If the server finds that the origin specified by Origin is not within the permitted range, the server will return a normal HTTP response. After the browser gets the response, it finds that the header information of the response does not contain the Access-Control-Allow-Origin field, and throws an error to XHR error event;
If the server finds that the domain name specified by Origin is within the permitted range, the response returned by the server will have several more header fields beginning with Access-Control-.
non simple request
A non-simple request is a request that has special requirements on the server, for example, the request method is PUT or DELETE, or the Content-Type value is application/json. Before the official communication, the browser will send an HTTP pre-check OPTIONS request to ask the server whether the domain name of the current web page is in the server's permission list, and which HTTP request methods and header fields can be used. Only with an affirmative reply, the browser will send a formal XHR request, otherwise an error will be reported.
2.2 Cross domain
The process in which the currently visited website on the browser sends a request to another website to obtain data is a cross-domain request.
Cross-domain is determined by the same-origin policy of the browser. It is an important browser security policy, which is used to restrict the interaction between a document of one origin or a script loaded by it and resources of another source. It can help block malicious documents and reduce May be attacked by the vector, you can use the CORS configuration to lift this restriction.
There are already many explanations on the cross-domain network, so I won’t go into too much detail here. You can also read MDN’s document for further understanding. Here are a few examples of homology and different elements. I believe programmers can understand.
2.3 Forward proxy and reverse proxy
The reverse proxy (Reverse Proxy) corresponds to the forward proxy (Forward Proxy), their differences:
Forward proxy: The general access process is that the client directly sends a request to the target server and obtains content. After using the forward proxy, the client sends a request to the proxy server instead, and specifies the target server (original server), and then the proxy server Communicate with the original server, forward the requested and obtained content, and then return it to the client. The forward proxy hides the real client and sends and receives requests for the client, making the real client invisible to the server;
To give a specific example 🌰, your browser cannot directly access Google, at this time you can use a proxy server to help you access Google, then this server is called a forward proxy.
Reverse proxy: Compared with the general access process, after using the reverse proxy, the server that directly receives the request is a proxy server, and then forwards the request to the real processing server on the internal network, and returns the result to the client. The reverse proxy hides the real server, sends and receives requests for the server, and makes the real server invisible to the client. Generally, it is more commonly used when processing cross-domain requests. Now basically all large websites have set up reverse proxy.
To give a specific example🌰, when you go to a restaurant to eat, you can order Sichuan cuisine, Cantonese cuisine, Jiangsu and Zhejiang cuisine, and the restaurant also has three chefs 👨🍳, but you as a customer don’t care which chef cooks for you, just order That is, Xiaoer assigns the dishes in your menu to different chefs for specific processing, then this Xiaoer is a reverse proxy server.
To put it simply, generally, those who act as proxies for clients are forward proxies, and those who act as proxies for servers are reverse proxies.
2.4 Load Balancing
Under normal circumstances, the client sends multiple requests to the server, and the server processes the requests, some of which may need to operate some resources such as databases, static resources, etc. After the server finishes processing, the results are returned to the client.
For the early system, this mode has uncomplicated functional requirements, and it can still be competent when there are relatively few concurrent requests, and the cost is also low. As the amount of information continues to grow, the amount of access and data increases rapidly, and the complexity of system business continues to increase, this approach can no longer meet the requirements. When the amount of concurrency is particularly large, the server is prone to collapse.
Obviously, this is caused by the bottleneck of server performance. In addition to stacking machines, the most important thing to do is load balancing.
In the case of explosive growth of requests, no matter how strong the performance of a single machine is, it cannot meet the requirements. At this time, the concept of clusters came into being. For problems that cannot be solved by a single server, multiple servers can be used, and then the requests are distributed to each server. The load is distributed to different servers, which is load balancing, and the core is "pressure sharing". Nginx implements load balancing, which generally refers to forwarding requests to server clusters.
To give a specific example🌰, when taking the subway in the evening rush hour, there are often subway staff at the entrance with a loud horn saying "Please go to Exit B, there are few people at Exit B and the train is empty...." The role of this staff is to load balanced.
2.5 Static and dynamic separation
In order to speed up the parsing speed of the website, dynamic pages and static pages can be parsed by different servers to speed up the parsing speed and reduce the pressure on the original single server.
Generally speaking, it is necessary to separate dynamic resources from static resources. Due to the high concurrency and static resource caching of Nginx, static resources are often deployed on Nginx. If the request is for a static resource, go directly to the static resource directory to obtain the resource. If it is a request for a dynamic resource, use the principle of reverse proxy to forward the request to the corresponding background application for processing, thereby realizing the separation of dynamic and static.
After separating the front and back ends, the access speed of static resources can be greatly improved. Even if the dynamic service is unavailable, the access of static resources will not be affected.
In a traditional web server, each client connection is handled as a separate process or thread. When switching tasks, the CPU needs to be switched to a new task and a new runtime context is created, which consumes additional memory and CPU time. When concurrent As requests increase, the server responds more slowly, negatively impacting performance.
Nginx is an open-source, high-performance, highly reliable web and reverse proxy server, and it supports hot deployment. It can run almost 7 * 24 hours a day without restarting even if it runs for several months. In the case of service, hot update the software version. Performance is the most important consideration for Nginx. It occupies less memory, has strong concurrency capabilities, and can support up to 50,000 concurrent connections. Most importantly, Nginx is free and commercialized, and its configuration is relatively simple.
The most important usage scenarios of Nginx:
1. Static resource service, providing service through local file system;
2. Reverse proxy service, including caching, load balancing, etc.;
3. API service, OpenResty;
For the front end, Node.js is no stranger. Many concepts of Nginx and Node.js are similar, such as HTTP server, event-driven, asynchronous and non-blocking, etc., and most of the functions of Nginx can also be realized using Node.js, but Nginx and Node.js .js does not conflict, each has its own area of expertise. Nginx is good at the processing of underlying server-side resources (static resource processing and forwarding, reverse proxy, load balancing, etc.), while Node.js is better at processing specific business logic at the upper layer. The two can be perfectly combined to jointly help front-end development.
Let's focus on learning how to use Nginx.
2. Related concepts
2.1 Simple and non-simple requests
First, let's understand simple requests and non-simple requests. If the following two conditions are met at the same time, it is a simple request:
1. The request method is one of HEAD, GET, and POST;
2. The HTTP header information does not exceed the fields on the right: Accept, Accept-Language, Content-Language, Last-Event-IDContent-Type are limited to three values application/x-www-form-urlencoded, multipart/form-data , text/plain;
Any request that does not meet these two conditions at the same time is a non-simple request.
Browsers handle simple and non-simple requests differently:
simple request
For simple requests, the browser will add the Origin field in the header information and send it directly. The Origin field is used to indicate which source (protocol + domain name + port) this request comes from.
If the server finds that the origin specified by Origin is not within the permitted range, the server will return a normal HTTP response. After the browser gets the response, it finds that the header information of the response does not contain the Access-Control-Allow-Origin field, and throws an error to XHR error event;
If the server finds that the domain name specified by Origin is within the permitted range, the response returned by the server will have several more header fields beginning with Access-Control-.
non simple request
A non-simple request is a request that has special requirements on the server, for example, the request method is PUT or DELETE, or the Content-Type value is application/json. Before the official communication, the browser will send an HTTP pre-check OPTIONS request to ask the server whether the domain name of the current web page is in the server's permission list, and which HTTP request methods and header fields can be used. Only with an affirmative reply, the browser will send a formal XHR request, otherwise an error will be reported.
2.2 Cross domain
The process in which the currently visited website on the browser sends a request to another website to obtain data is a cross-domain request.
Cross-domain is determined by the same-origin policy of the browser. It is an important browser security policy, which is used to restrict the interaction between a document of one origin or a script loaded by it and resources of another source. It can help block malicious documents and reduce May be attacked by the vector, you can use the CORS configuration to lift this restriction.
There are already many explanations on the cross-domain network, so I won’t go into too much detail here. You can also read MDN’s
2.3 Forward proxy and reverse proxy
The reverse proxy (Reverse Proxy) corresponds to the forward proxy (Forward Proxy), their differences:
Forward proxy: The general access process is that the client directly sends a request to the target server and obtains content. After using the forward proxy, the client sends a request to the proxy server instead, and specifies the target server (original server), and then the proxy server Communicate with the original server, forward the requested and obtained content, and then return it to the client. The forward proxy hides the real client and sends and receives requests for the client, making the real client invisible to the server;
To give a specific example 🌰, your browser cannot directly access Google, at this time you can use a proxy server to help you access Google, then this server is called a forward proxy.
Reverse proxy: Compared with the general access process, after using the reverse proxy, the server that directly receives the request is a proxy server, and then forwards the request to the real processing server on the internal network, and returns the result to the client. The reverse proxy hides the real server, sends and receives requests for the server, and makes the real server invisible to the client. Generally, it is more commonly used when processing cross-domain requests. Now basically all large websites have set up reverse proxy.
To give a specific example🌰, when you go to a restaurant to eat, you can order Sichuan cuisine, Cantonese cuisine, Jiangsu and Zhejiang cuisine, and the restaurant also has three chefs 👨🍳, but you as a customer don’t care which chef cooks for you, just order That is, Xiaoer assigns the dishes in your menu to different chefs for specific processing, then this Xiaoer is a reverse proxy server.
To put it simply, generally, those who act as proxies for clients are forward proxies, and those who act as proxies for servers are reverse proxies.
2.4 Load Balancing
Under normal circumstances, the client sends multiple requests to the server, and the server processes the requests, some of which may need to operate some resources such as databases, static resources, etc. After the server finishes processing, the results are returned to the client.
For the early system, this mode has uncomplicated functional requirements, and it can still be competent when there are relatively few concurrent requests, and the cost is also low. As the amount of information continues to grow, the amount of access and data increases rapidly, and the complexity of system business continues to increase, this approach can no longer meet the requirements. When the amount of concurrency is particularly large, the server is prone to collapse.
Obviously, this is caused by the bottleneck of server performance. In addition to stacking machines, the most important thing to do is load balancing.
In the case of explosive growth of requests, no matter how strong the performance of a single machine is, it cannot meet the requirements. At this time, the concept of clusters came into being. For problems that cannot be solved by a single server, multiple servers can be used, and then the requests are distributed to each server. The load is distributed to different servers, which is load balancing, and the core is "pressure sharing". Nginx implements load balancing, which generally refers to forwarding requests to server clusters.
To give a specific example🌰, when taking the subway in the evening rush hour, there are often subway staff at the entrance with a loud horn saying "Please go to Exit B, there are few people at Exit B and the train is empty...." The role of this staff is to load balanced.
2.5 Static and dynamic separation
In order to speed up the parsing speed of the website, dynamic pages and static pages can be parsed by different servers to speed up the parsing speed and reduce the pressure on the original single server.
Generally speaking, it is necessary to separate dynamic resources from static resources. Due to the high concurrency and static resource caching of Nginx, static resources are often deployed on Nginx. If the request is for a static resource, go directly to the static resource directory to obtain the resource. If it is a request for a dynamic resource, use the principle of reverse proxy to forward the request to the corresponding background application for processing, thereby realizing the separation of dynamic and static.
After separating the front and back ends, the access speed of static resources can be greatly improved. Even if the dynamic service is unavailable, the access of static resources will not be affected.
Related Articles
-
A detailed explanation of Hadoop core architecture HDFS
Knowledge Base Team
-
What Does IOT Mean
Knowledge Base Team
-
6 Optional Technologies for Data Storage
Knowledge Base Team
-
What Is Blockchain Technology
Knowledge Base Team
Explore More Special Offers
-
Short Message Service(SMS) & Mail Service
50,000 email package starts as low as USD 1.99, 120 short messages start at only USD 1.00