nginx最大连接数

单台nginx实例能够承载的最大连接数

1. 基本参数

可以参见这篇文档的综述:Nginx的配置说明
在nginx配置文件里有几个参数:

  1. worker_processes,这个是最大进程数
  2. worker_connections,单进程最大处理的链接数,和服务器的cpu、内存强相关
  3. worker_rlimit_nofile

一般nginx能够承载的链接数=worker_processes*worker_connections

2.状态

1
2
3
4
5
6
# 查看linux连接数
$ ss -s
# 也可以用这种方式查看当前连接数
$ netstat -n | awk '/^tcp/ {++S[$NF]} END {for(a in S) print a,S[a]}'
# 单独查看nginx进程的链接数
$ netstat -apn|grep 'nginx: worker'|wc -l

3.配置

worker_processes配置为你的cpu核数*2
worker_connections可以任意调整(会受限于linux的单进程/单用户的最大文件句柄数),建议5000起,如果发现链接数已经满了,而服务器的负载不高,那么可以调整这个数字

3.1.nginx配置

参考:
修改nginx配置:

1
2
3
4
5
6
7
8
9
10
11
12
$ vim /etc/nginx/nginx.conf
user nginx;
worker_processes 8;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

include /usr/share/nginx/modules/*.conf;

events {
worker_connections 10000;
}
worker_rlimit_nofile 1000000;

worker_rlimit_nofile需要配合linux系统参数和启动服务:
修改启动服务:

1
2
3
4
5
6
7
$ vim /usr/lib/systemd/system/nginx.service
PrivateTmp=true
#这里添加一行
LimitNOFILE=1000000

[Install]
WantedBy=multi-user.target

3.2.linux配置

首先检查

1
$ ulimit -a;

修改:

1
2
3
4
5
6
7
8
9
10
$ vim /etc/sysctl.conf
#追加一行
fs.file-max = 1000000
$ sysctl -p
#此文件修改需要重启或者退出重新登录
$ vim /etc/security/limits.conf
* hard nofile 1000000
* soft nofile 1000000
* hard nproc 1000000
* soft nproc 100000

4.其他常见配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
stream{
include /etc/nginx/conf.d/stream/*.conf;
log_format proxy '$remote_addr [$time_local] '
'$protocol $status $bytes_sent $bytes_received '
'$session_time "$upstream_addr" '
'"$upstream_bytes_sent" "$upstream_bytes_received" "$upstream_connect_time"';

access_log /var/log/nginx/tcp-access.log proxy ;
open_log_file_cache off;
}
http{
fastcgi_connect_timeout 30000;
fastcgi_send_timeout 300s;
fastcgi_read_timeout 300s;
keepalive_timeout 300s 300s;
keepalive_requests 10000;
client_body_timeout 60s;
client_header_timeout 10s;
send_timeout 120s;
client_max_body_size 5000m;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
types_hash_max_size 4096;
server_names_hash_bucket_size 512;
gzip on;
}

5.可能的端口问题

1
semanage port --add --type http_port_t --proto tcp 8080