1. Nginx long connection notes
The concept and advantages of long connection
- concept: HTTP long connection refers to the ability to send and receive multiple HTTP requests/responses continuously on a TCP connection without having to close the connection after each request, thereby reducing the overhead of TCP connection establishment and closing, improving performance and efficiency.
- Advantages: For scenarios where resources are frequently requested, such as the loading of multiple images, scripts, style sheets and other files in a web page, long connections can significantly reduce the time consumption of TCP connection handshake and waving, speed up the overall loading of the page, reduce server load, and improve user experience and server concurrent processing capabilities.
Instructions related to long connections in Nginx
-
keepalive_timeout
:-
grammar:
keepalive_timeout timeout [header_timeout];
-
effect: Set the timeout time for a long connection, that is, the server closes the connection without a new request after the server keeps the connection. The first parameter
timeout
It is the timeout time when the server waits for the next request, the second parameterheader_timeout
(Optional) is set in the response headerKeep-Alive: timeout=xxx
The value of is used to notify the client that the maximum time the connection is maintained. If only one parameter is set, it is used for both the server side and the response header. For example:keepalive_timeout 65;
It means that the long connection timeout between the server and the client is 65 seconds.
-
grammar:
-
keepalive_requests
:-
grammar:
keepalive_requests number;
-
effect: Sets the maximum number of requests allowed on a long connection. When this number is reached, the connection will be closed and a new connection will be re-established. For example:
keepalive_requests 100;
It means that a long connection can be closed after processing up to 100 requests.
-
grammar:
-
sendfile
:-
grammar:
sendfile on | off;
-
effect: Used to control whether to enable efficient file transfer mode. In the long connection scenario, turn on
sendfile
It can further improve file transfer performance and reduce the number of copies of data between kernel space and user space. For example:sendfile on;
Turn on this function (it is usually enabled by default, but different systems and versions may vary).
-
grammar:
-
tcp_nodelay
:-
grammar:
tcp_nodelay on | off;
-
effect: Controls whether the TCP_NODELAY option is enabled. In long connections, for some applications with high real-time requirements (such as some dynamic web interactions), turn on
tcp_nodelay
It can reduce data transmission delay and ensure that data is sent out as soon as possible; for some scenarios that do not require real-time and focus on transmission efficiency (such as large-scale file transfers), it can be turned off to improve transmission efficiency. For example:tcp_nodelay on;
Turn on this option (it is usually turned off by default, but different application scenarios may require adjustment).
-
grammar:
Configuration scenarios and precautions for long connections
Configuration scenario:
- Front-end optimization: For Nginx servers that provide web services, configuring long connections can speed up the loading of web pages, especially for web pages containing multiple static resources (such as images, CSS, JavaScript files). By reducing the number of TCP connections established and closed, the efficiency of resource concurrent acquisition is improved.
- Backend proxy: When Nginx is a proxy server for backend application servers (such as Tomcat, etc.), long connections can maintain persistent connections with backend servers, reduce the connection processing overhead of backend servers, improve the performance and throughput of backend servers, and also speed up the data transmission speed between Nginx and backend servers.
Things to note:
- Server resources: Long connections will keep the connection open for a period of time, so it is necessary to ensure that the server has sufficient resources (such as memory, file descriptors, etc.) to handle a large number of long connections. Otherwise, it may cause server performance to degrade or even exhaust resources.
- compatibility: While most modern browsers and servers support long HTTP connections, there may be compatibility issues in some specific environments or older clients. These factors need to be taken into account when configuring long connections, some compatibility testing may be required, or alternative short connection configuration options are provided.
- Safety considerations: Long connections may put the server at some security risks, such as long-term connections may be used by attackers for malicious attacks (such as connection hijacking, slow attacks, etc.). Therefore, when configuring long connections, it is necessary to combine other security measures (such as firewalls, intrusion detection systems, etc.) to ensure the security of the server.
2. Nginx long connection experiment
Preparation for experimental environment
operating system: CentOS 7 (or other compatible Linux distribution)
Install Nginx:
- use
yum
Install the package manager (taking CentOS as an example): - Update the system package list:
sudo yum update -y
- Install Nginx:
sudo yum install nginx -y
Create a test resource:
- In Nginx's default web directory (usually
/usr/share/nginx/html
Create some test files under ) to simulate resource loading in web pages. For example: - Create a simple HTML file
:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Nginx Long Connection Test</title> </head> <body> <h1>Nginx Long Connection Test</h1> <img src="" alt="Image 1"> <img src="" alt="Image 2"> <script src=""></script> </body> </html>
- Create two image files for testing
and
(You can use any small size picture), and a simple JavaScript file
:
("Script loaded successfully.");
Nginx configuration modification
- Open the main configuration file of Nginx (usually
/etc/nginx/
):sudo vi /etc/nginx/
- exist
http
Add the following long connection-related configurations in the block:
http { # Enable long connection and set the timeout to 60 seconds (server and client) keepalive_timeout 60; # The maximum number of requests allowed on a long connection is 100 keepalive_requests 100; # Enable efficient file transfer mode sendfile on; # Close TCP_NODELAY (can be adjusted according to actual situation) tcp_nodelay off; server { listen 80; server_name localhost; location / { root /usr/share/nginx/html; index ; } } }
Save and close the configuration file.
Experimental testing steps
Start Nginx service:sudo service nginx start
Test using a browser:
- Open the browser and visit
http://localhost
, the browser will loadFiles and pictures and JavaScript files referenced therein.
- In the browser's developer tools (usually press F12 to call it out), switch to the "Network" tab to observe the loading of resources. As you can see, multiple resources are loaded through the same TCP connection, rather than establishing a new TCP connection for each resource, which indicates that the long connection configuration is in effect.
- Pay attention to the time sequence and time-consuming of resource loading. It can be found that the overall page loading speed is improved compared to when there is no long connection configured, especially when loading multiple small resources, which reduces the overhead of connection establishment and closing.
Test with command line tools (optional):
- Can be used
curl
Commands to simulate HTTP requests and view connection-related information. For example:
curl -v http://localhost/
- exist
curl
In the output of , you can viewConnection
The header information should be displayed asKeep-Alive
, means that a long connection is used. At the same time, it can be executed multiple timescurl
Command to observe the reuse of the connection and when it reacheskeepalive_requests
After the maximum number of requests is set, whether the connection is re-established.
Further experiments and extensions
-
Adjust long connection parameters:Revise
keepalive_timeout
andkeepalive_requests
The value of observes the impact on page loading speed and server performance. For example, increasekeepalive_timeout
May keep long connections longer, may have better performance for frequently visited web pages, but will also occupy more server resources; reducekeepalive_requests
It may cause connections to be closed and re-established more frequently, suitable for scenarios where connection stability is high. -
Combined with backend application testing: If Nginx is the proxy for the backend application server, configure the long connection parameters of the backend application (different backend applications have different configuration methods, such as Tomcat, you can use it in
Configure connection-related parameters in the file), and then test the long connection performance between Nginx and the back-end application to observe the improvement of the performance of the entire application system.
-
Stress testing and performance analysis: Use tools (such as
ab
(Apache Benchmark) orwrk
, etc.) Perform stress tests on Nginx servers after long connections, simulate multiple concurrent users requesting web page resources, analyze the server's performance indicators (such as throughput, response time, number of concurrent connections, etc.), evaluate the advantages and potential problems of long connection configuration in high load situations, and further optimize the server configuration based on the test results.
Through the above experiments, we can gain an in-depth understanding of the configuration methods and actual effects of Nginx long connections, as well as how to optimize and adjust according to different application scenarios to improve the performance and user experience of the server. In an actual production environment, it is also necessary to combine specific business needs, server resources and network conditions, and comprehensively consider the configuration parameters of long connections to ensure the stable and efficient operation of the server.
This is the end of this article about nginx long connection configuration summary. For more related nginx long connection content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!