Table of Contents
Linux system parameter optimization
File descriptor limit
TCP connection queue length
Temporary port
Nginx parameter optimization
Worker process
KeepAlive
Access-Log缓存
文件描述符限制
Home Operation and Maintenance Nginx Nginx performance optimization methods

Nginx performance optimization methods

May 28, 2023 am 08:01 AM
nginx

Nginx performance optimization methods

Linux system parameter optimization

Some of the configurations mentioned below require a newer Linux (2.6 or above) kernel. It can be supported. The author uses CentOS 7.4 and kernel version 3.10. If it does not meet the needs, it is best to upgrade accordingly. After all, patching is a thankless task. For system-level tuning, we usually just modify the file descriptor limit, buffer queue length, and number of temporary ports.

File descriptor limit

Since each TCP connection occupies a file descriptor, once the file descriptors are exhausted, a new connection will return "Too many open files" like this error, in order to improve performance, we need to modify it: 1. System-level restriction editing file /etc/sysctl.conf, add the following content:

fs.file-max =10000000
fs.nr_open =10000000
Copy after login

User-level restriction editing file /etc/security /limits.conf, add the following content:

 *      hard   nofile      1000000
 *      soft   nofile      1000000
Copy after login

We need to ensure that the user-level limit is lower than the system-level limit, otherwise it will result in the inability to log in through SSH. After the modification is completed, execute the following command:

 $ sysctl -p
Copy after login

You can check whether the modification is successful by executing the command ulimit -a.

TCP connection queue length

Edit the file /etc/sysctl.conf and add the following content:

# The length of the syn quenenet.ipv4.tcp_max_syn_backlog =65535# The length of the tcp accept queuenet.core.somaxconn =65535
Copy after login

Among them, tcp_max_syn_backlog is used to specify the semi-connection SYN queue length. When a new connection is made, When it arrives, the system will detect the semi-connected SYN queue. If the queue is full, the SYN request cannot be processed and the statistical counts will be added to ListenOverflows and ListenDrops in /proc/net/netstat. somaxconn is used to specify the full-connected ACCEPT queue length. When the queue is full, the ACK packet sent by the client will not be processed correctly and the error "connection reset by peer" will be returned. Nginx will record an error log "no live upstreams while connecting to upstreams". If the above error occurs, we You need to consider increasing the configuration of these two items.

Temporary port

Since Nginx is used as a proxy, each TCP connection to the upstream web service will occupy a temporary port, so we need to modify the ip_local_port_range parameter to modify the /etc/sysctl.conf file , add the following content:

net.ipv4.ip_local_port_range =102465535
net.ipv4.ip_local_reserved_ports =8080,8081,9000-9010
Copy after login

Among them, the parameter ip_local_reserved_ports is used to specify the reserved port. This is to prevent the service port from being occupied and unable to start.

Nginx parameter optimization

Nginx parameter optimization mainly focuses on the nginx.conf configuration file, which will not be described in detail below.

Worker process

An important reason for Nginx’s powerful performance is that it adopts a multi-process non-blocking I/O model, so we must make good use of this:

  • worker_processes By default, Nginx has only one master process and one worker process. We need to modify it. It can be set to a specified number or to auto, which is the number of CPU cores of the system. Increasing the number of workers may cause competition between processes for CPU resources, resulting in unnecessary context switches. So we just set it to the number of CPU cores: worker_processes auto

  • worker_connections The number of concurrent connections each worker can handle, the default value of 512 is not quite enough If used, we will increase it appropriately: worker_connections 4096

  • Nginx supports the following I/O multiplexing methods to handle connections: select, poll, kqueue, epoll, rtsig , /dev/poll, eventport. Different operating systems use different tools, and in Linux systems, epoll is the most efficient

KeepAlive

In order to avoid frequent changes from Nginx to Web services To establish and disconnect connections, we can enable the KeepAlive long connection feature supported from HTTP 1.1, which can significantly reduce CPU and network overhead. In our actual combat, it is also the biggest improvement in performance. Keepalive must be used in conjunction with proxy_http_version and proxy_set_header. The reference configuration is as follows:

upstream BACKEND {
    keepalive 300;
     server 127.0.0.1:8081;
 }
server {
     listen 8080;
    location /{
        proxy_pass http://BACKEND;
        proxy_http_version 1.1;
        proxy_set_header Connection"";
 }
}
Copy after login

where keepalive is neither timeout nor the number of connection pools. The official explanation is as follows:

The connections parameter sets the maximum number of idle keepalive connections to upstream servers that are preserved in the cache of each worker process. When this number is exceeded, the least recently used connections are closed.

It can be seen that it means "maximum number of idle long connections" ”, idle long connections exceeding this number will be recycled. When the number of requests is stable and smooth, the number of idle long connections will be very small (close to 0), but in reality the number of requests cannot always be smooth and stable. When the number of requests fluctuates, the number of idle long connections also fluctuates:

  1. #When the number of idle long connections is greater than the configured value, the part of the long connections that is greater than the configured value will be recycled ;

  2. When the long connection is not enough, a new long connection will be re-established.

如果该值过小,连接池会经常进行回收、分配和再回收操作。为了避免这种情况出现,可以根据实际情况适当调整这个值,在我们实际情况中,目标QPS为6000,Web服务响应时间约为200ms,因此需要约1200个长连接,而 keepalive值取长连接数量的10%~30%就可以了,这里我们取300,如果不想计算,直接设为1000也是可行的。

Access-Log缓存

记录日志的I/O开销比较高,好在Nginx支持日志缓存,我们可以利用这个功能,降低写日志文件的频率,从而提高性能。结合使用buffer和flush两个参数可以控制缓存行为

  access_log /var/logs/nginx-access.log buffer=64k gzip flush=1m
Copy after login

其中 buffer制定了缓存大小,当缓冲区达到 buffer所指定的大小时,Nginx就会将缓存起来的日志写到文件中;flush指定了缓存超时时间,当 flush指定的时间到达时,也会触发缓存日志写入文件操作。

文件描述符限制

Nginx配置中同样有相应的配置项:worker_rlimit_nofile, 理论上这个值应该设置为 /etc/security/limits.conf 中的值除以 worker_processes, 但实际中不可能每个进程均匀分配,所以这里只要设置成和 /etc/security/limits.conf 一样就可以了

 worker_rlimit_nofile 1000000;
Copy after login

The above is the detailed content of Nginx performance optimization methods. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to check the name of the docker container How to check the name of the docker container Apr 15, 2025 pm 12:21 PM

You can query the Docker container name by following the steps: List all containers (docker ps). Filter the container list (using the grep command). Gets the container name (located in the "NAMES" column).

How to configure nginx in Windows How to configure nginx in Windows Apr 14, 2025 pm 12:57 PM

How to configure Nginx in Windows? Install Nginx and create a virtual host configuration. Modify the main configuration file and include the virtual host configuration. Start or reload Nginx. Test the configuration and view the website. Selectively enable SSL and configure SSL certificates. Selectively set the firewall to allow port 80 and 443 traffic.

How to configure cloud server domain name in nginx How to configure cloud server domain name in nginx Apr 14, 2025 pm 12:18 PM

How to configure an Nginx domain name on a cloud server: Create an A record pointing to the public IP address of the cloud server. Add virtual host blocks in the Nginx configuration file, specifying the listening port, domain name, and website root directory. Restart Nginx to apply the changes. Access the domain name test configuration. Other notes: Install the SSL certificate to enable HTTPS, ensure that the firewall allows port 80 traffic, and wait for DNS resolution to take effect.

How to check whether nginx is started How to check whether nginx is started Apr 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 check nginx version How to check nginx version Apr 14, 2025 am 11:57 AM

The methods that can query the Nginx version are: use the nginx -v command; view the version directive in the nginx.conf file; open the Nginx error page and view the page title.

How to create containers for docker How to create containers for docker Apr 15, 2025 pm 12:18 PM

Create a container in Docker: 1. Pull the image: docker pull [mirror name] 2. Create a container: docker run [Options] [mirror name] [Command] 3. Start the container: docker start [Container name]

How to start containers by docker How to start containers by docker Apr 15, 2025 pm 12:27 PM

Docker container startup steps: Pull the container image: Run "docker pull [mirror name]". Create a container: Use "docker create [options] [mirror name] [commands and parameters]". Start the container: Execute "docker start [Container name or ID]". Check container status: Verify that the container is running with "docker ps".

How to start nginx server How to start nginx server Apr 14, 2025 pm 12:27 PM

Starting an Nginx server requires different steps according to different operating systems: Linux/Unix system: Install the Nginx package (for example, using apt-get or yum). Use systemctl to start an Nginx service (for example, sudo systemctl start nginx). Windows system: Download and install Windows binary files. Start Nginx using the nginx.exe executable (for example, nginx.exe -c conf\nginx.conf). No matter which operating system you use, you can access the server IP

See all articles