search
HomeOperation and MaintenanceNginxHow to use nginx keepalive

How to use nginx keepalive

May 19, 2023 pm 02:13 PM
nginxkeepalive

The default http1.1 protocol request header is to enable keepalive by default, as shown in the figure:

nginx keepalive如何使用

So what is keepalive? What is the function?

keepalive is a mechanism in TCP that can detect dead connections. Its function is to keep long socket connections from being disconnected. It is a function of the TCP layer and does not belong to the application layer.

How does the tcp layer maintain a long connection?

Let’s first look at the usage of keepalive: there are three parameters, open to the application layer.

sk->keepalive_probes:探测次数,重试次数
sk->keepalive_time 探测的心跳间隔,tcp链接在多少秒之后没有数据报文传输启动探测报文
sk->keepalive_intvl 探测间隔,未收到回复时,重试的时间间隔

Default configuration view:

[***@*** ~]$ cat /proc/sys/net/ipv4/tcp_keepalive_time
7200
[***@*** ~]$ cat /proc/sys/net/ipv4/tcp_keepalive_intvl
75
[***@*** ~]$ cat /proc/sys/net/ipv4/tcp_keepalive_probes
9

Usage method:

int keepalive = 1; // 开启keepalive属性
int keepidle = 60; // 如该连接在60秒内没有任何数据往来,则进行探测
int keepinterval = 5; // 探测时发包的时间间隔为5 秒
int keepcount = 3; // 探测尝试的次数。如果第1次探测包就收到响应了,则后2次的不再发。并且清零该计数
setsockopt(rs, sol_socket, so_keepalive, (void *)&keepalive , sizeof(keepalive ));
setsockopt(rs, sol_tcp, tcp_keepidle, (void*)&keepidle , sizeof(keepidle ));
setsockopt(rs, sol_tcp, tcp_keepintvl, (void *)&keepinterval , sizeof(keepinterval ));
setsockopt(rs, sol_tcp, tcp_keepcnt, (void *)&keepcount , sizeof(keepcount ));

After the application layer is set like this, the default configuration will be overwritten and the manually set configuration will be adopted.

For an established tcp connection. If there is no data packet transmission between the two parties within the keepalive_time, the end that turns on the keepalive function will send a keepalive data heartbeat packet. If no response is received, the data packet will be sent again every keepalive_intvl time and keepalive_probes times. If no response is received, an rst packet is sent to close the connection. If a reply is received, the timer is cleared.

Capture the packet to verify the content of the tcp heartbeat packet

nginx keepalive如何使用

Continue to analyze the content of the heartbeat packet sent and replied by keepalive based on the packet capture:

The source code of the tcp header structure is:

typedef struct _tcp_header
{
 short m_ssourport;          // 源端口号16bit
 short m_sdestport;           // 目的端口号16bit
 unsigned int m_uisequnum;      // req字段 序列号32bit
 unsigned int m_uiacknowledgenum; //ack字段 确认号32bit
 short m_sheaderlenandflag;     // 前4位:tcp头长度;中6位:保留;后6位:标志位
 short m_swindowsize;         //win字段 窗口大小16bit
 short m_schecksum;          // 检验和16bit
 short m_surgentpointer;        // 紧急数据偏移量16bit
}__attribute__((packed))tcp_header, *ptcp_header;

Look at the content of the heartbeat packet sent:

0000 d4 6d 50 f5 02 7f f4 5c  89 cb 35 29 08 00    //mac头 14字节:
                         45 00 // ip头 20字节 :
0010 00 28 10 f4 00 00 40 06  5b dd ac 19 42 76 0a b3
0020 14 bd
      e4 4a 1f 7c 32 7e  7a cb 4c bc 55 08 50 10  // tcp头 20字节 
0030 10 00 3f 00 00 00
//分析tcp头部内容
e4 4a //源端口号16bit 10进制为:58442 
1f 7c //目的端口号16bit 10进制为 : 8060 
32 7e 7a cb // req字段 序列号32bit 10进制为 : 
4c bc 55 08 // ack字段 确认号32bit 
5 // 前4位:tcp头长度 5*4 =20 字节 没问题 
0 10 /// 中6位:保留;后6位:标志位 10 代表倒数第5位为1, 标识改tcp包为 ack 确认包 
0030 10 00 3f 00 00 00

Continue to look at the content of the reply heartbeat packet:

0000 f4 5c 89 cb 35 29 d4 6d 50 f5 02 7f 08 00 45 00 
0010 00 34 47 28 40 00 36 06 ef 9c 0a b3 14 bd ac 19 
0020 42 76 // 前面数据不解读 
1f 7c
e4 4a
4c bc 55 08
32 7e 7a cc
8// tcp头长度为8 * 4 = 32 除了头部 还有 选项数据 12字节 
0 10  // 中6位:保留;后6位:标志位 10 代表倒数第5位为1, 标识该tcp包为 ack 确认包 
0030 01 3f //win字段 窗口大小16bit
4e 0d // 检验和16bit
00 00 // 紧急数据偏移量16bit
01 01 08 0a 00 59 be 1c 39 13 
0040 cf 12 // 选项数据 12字节

From above It can be seen that the heartbeat packet of tcp maintaining a long connection is that the browser first sends an ack packet to the server, and then the server replies with an ack packet with option data

How will nginx handle it? What will be done with keepalive requests?

首先做的是版本判断 :http协议版本低于1.1时,该链接的keepalive置为0
if (r->http_version < ngx_http_version_11) {
  r->keepalive = 0;
} 
ngx_http_process_connection 函数中 ngx_http_request_t 中带有keep-alive则把改链接标识起来 
if (ngx_strcasestrn(h->value.data, "keep-alive", 10 - 1)) {
  r->headers_in.connection_type = ngx_http_connection_keep_alive;
}
ngx_http_handler函数中对r->headers_in.connection_type 判断,给r->keepalive赋值为1
  switch (r->headers_in.connection_type) {
  case ngx_http_connection_keep_alive:
    r->keepalive = 1;
    break;
  }
ngx_configure_listening_sockets函数中,当keepalive为1时,对该连接开启keepalive,之后tcp底层就会对该连接fd做检测死连接的机制,保持长连接,不断开。
if (ls[i].keepalive) {
  value = (ls[i].keepalive == 1) ? 1 : 0;

  if (setsockopt(ls[i].fd, sol_socket, so_keepalive,//开启keepalive功能
          (const void *) &value, sizeof(int))
    == -1)
  
}

When will nginx’s long connection be disconnected?

After nginx opens keepalive through setsockopt(ls[i].fd, sol_socket, so_keepalive,(const void *) &value, sizeof(int)), it will always maintain a long connection with the client. This will cause a very serious problem. The number of connections that each worker can maintain is limited (ep = epoll_create(cycle->connection_n / 2); cycle->connection_n / 2 is the upper limit of fd that epoll can manage) , as a result, the number of connections is quickly exhausted. How should nginx handle this?

In order to find this answer, let’s look at the two configuration parameters of nginx about keeoalive

keepalive_timeout

keepalive_timeout timeout [header_timeout];

The first parameter: Set the keep-alive client to connect to the server The timeout value for keeping the client open (default 75s); a value of 0 will disable the keep-alive client connection;

Second parameter: Optional, set a value "keep-alive" in the header field of the response : timeout=time”; usually no need to set;

Note: keepalive_timeout defaults to 75s

keepalive_requests

The keepalive_requests command is used to set the requests that can be served on a keep-alive connection The maximum number of connections to close when the maximum number of requests is reached, a value of 0 will also disable keep-alive client connections; The default is 100.
The answer is obvious. Use keepalive_timeout keepalive_requests to manage long connections.

  • When a tcp connection survives longer than keepalive_timeout, it will be closed. The specific implementation of nginx is through a timer. Made to do

  • When the maximum number of love letters in a tcp connection exceeds keepalive_requests, it will also be closed

Guaranteed through these two mechanisms The number of connections per worker will not exceed the number that epoll can manage.

The above is the detailed content of How to use nginx keepalive. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
NGINX vs. Apache: Performance, Scalability, and EfficiencyNGINX vs. Apache: Performance, Scalability, and EfficiencyApr 19, 2025 am 12:05 AM

NGINX and Apache are both powerful web servers, each with unique advantages and disadvantages in terms of performance, scalability and efficiency. 1) NGINX performs well when handling static content and reverse proxying, suitable for high concurrency scenarios. 2) Apache performs better when processing dynamic content and is suitable for projects that require rich module support. The selection of a server should be decided based on project requirements and scenarios.

The Ultimate Showdown: NGINX vs. ApacheThe Ultimate Showdown: NGINX vs. ApacheApr 18, 2025 am 12:02 AM

NGINX is suitable for handling high concurrent requests, while Apache is suitable for scenarios where complex configurations and functional extensions are required. 1.NGINX adopts an event-driven, non-blocking architecture, and is suitable for high concurrency environments. 2. Apache adopts process or thread model to provide a rich module ecosystem that is suitable for complex configuration needs.

NGINX in Action: Examples and Real-World ApplicationsNGINX in Action: Examples and Real-World ApplicationsApr 17, 2025 am 12:18 AM

NGINX can be used to improve website performance, security, and scalability. 1) As a reverse proxy and load balancer, NGINX can optimize back-end services and share traffic. 2) Through event-driven and asynchronous architecture, NGINX efficiently handles high concurrent connections. 3) Configuration files allow flexible definition of rules, such as static file service and load balancing. 4) Optimization suggestions include enabling Gzip compression, using cache and tuning the worker process.

NGINX Unit: Supporting Different Programming LanguagesNGINX Unit: Supporting Different Programming LanguagesApr 16, 2025 am 12:15 AM

NGINXUnit supports multiple programming languages ​​and is implemented through modular design. 1. Loading language module: Load the corresponding module according to the configuration file. 2. Application startup: Execute application code when the calling language runs. 3. Request processing: forward the request to the application instance. 4. Response return: Return the processed response to the client.

Choosing Between NGINX and Apache: The Right Fit for Your NeedsChoosing Between NGINX and Apache: The Right Fit for Your NeedsApr 15, 2025 am 12:04 AM

NGINX and Apache have their own advantages and disadvantages and are suitable for different scenarios. 1.NGINX is suitable for high concurrency and low resource consumption scenarios. 2. Apache is suitable for scenarios where complex configurations and rich modules are required. By comparing their core features, performance differences, and best practices, you can help you choose the server software that best suits your needs.

How to start nginxHow to start nginxApr 14, 2025 pm 01:06 PM

Question: How to start Nginx? Answer: Install Nginx Startup Nginx Verification Nginx Is Nginx Started Explore other startup options Automatically start Nginx

How to check whether nginx is startedHow to check whether nginx is startedApr 14, 2025 pm 01:03 PM

How to confirm whether Nginx is started: 1. Use the command line: systemctl status nginx (Linux/Unix), netstat -ano | findstr 80 (Windows); 2. Check whether port 80 is open; 3. Check the Nginx startup message in the system log; 4. Use third-party tools, such as Nagios, Zabbix, and Icinga.

How to close nginxHow to close nginxApr 14, 2025 pm 01:00 PM

To shut down the Nginx service, follow these steps: Determine the installation type: Red Hat/CentOS (systemctl status nginx) or Debian/Ubuntu (service nginx status) Stop the service: Red Hat/CentOS (systemctl stop nginx) or Debian/Ubuntu (service nginx stop) Disable automatic startup (optional): Red Hat/CentOS (systemctl disabled nginx) or Debian/Ubuntu (syst

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment