>/etc/rc.localecho "ulimit-HSn65536">>/root/.bash_profileulimit-HSn655362, 최대 TCP 연결 수 제한을 다음과 같이 변경합니다. 네트워크 커널. /etc/sysctl.conf 1. Linux 플랫폼의 경우,"/> >/etc/rc.localecho "ulimit-HSn65536">>/root/.bash_profileulimit-HSn655362, 최대 TCP 연결 수 제한을 다음과 같이 변경합니다. 네트워크 커널. /etc/sysctl.conf 1. Linux 플랫폼의 경우,">

 >  기사  >  시스템 튜토리얼  >  높은 동시성에서 웹 서버 및 캐시 서버에 대한 최대 소켓 연결 제한 수를 조정하는 방법

높은 동시성에서 웹 서버 및 캐시 서버에 대한 최대 소켓 연결 제한 수를 조정하는 방법

PHPz
PHPz원래의
2024-07-18 18:44:23341검색

高并发下 web 服务器和 cache 服务器 socket 最大连接数限制调整方法

Web サーバーとキャッシュ サーバー、高い同時実行性では、ソケット接続の最大数の制限が調整されます:

1. ユーザープロセスが開くことができるファイルの最大数の制限を変更します。

即時有効: ulimit-nxxx

永久に有効:

echo "ulimit-HSn65536">>/etc/rc.local

echo "ulimit-HSn65536">>/root/.bash_profile

ulimit-HSn65536

2. TCP 接続の最大数に関するネットワーク カーネル制限を変更します。

/etc/sysctl.conf

一、

Linux プラットフォームでは、クライアント プログラムを作成しているかサーバー プログラムを作成しているかに関係なく、広範囲の同時 TCP 接続を処理する場合、同時実行の最大数は、ユーザーが同時に開くことができるファイルの数に関するシステムの制限の影響を受けます。 (これは、システムが TCP 接続ごとにソケット ハンドルを作成し、各ソケット ハンドルがファイル ハンドルでもあるためです)。例: 1 つのプロセスのみを開始する Redis プログラムは、1024 個のファイルしか開くことができません (デフォルトは 1024) (1024 個の TCP 接続 = 1024 個のソケット接続ハンドル = 1024 個のファイル ハンドル)、

ulimit コマンドを使用して、システムが現在のユーザー プロセスが開くことを許可するファイル数の制限を確認できます。

$ulimit-n

1024

これは、現在のユーザーの各プロセスが同時に最大 1024 個のファイル (標準入力、標準出力、標準エラー、サーバー盗聴ソケット、およびプロセス間通信の Unix ドメイン) を開くことができることを意味します。各プロセスで開く必要があるソケットおよびその他のファイルは削除する必要があるため、クライアントのソケット接続に使用できるファイルの数は約 1024-10=1014 のみになります。つまり、デフォルトでは、Linux ベースの通信プログラムは同時に最大 1014 の同時 TCP 接続を許可します。

より多くの同時 TCP 接続をサポートしたい通信ハンドラーの場合、現在のユーザーのプロセスに対して Linux が同時にオープンするファイルの数を変更する必要があります。

ソフトリミット: 現在のシステムが耐えられる範囲内で、ユーザーが同時に開くことができるファイルの数をさらに制限する Linux を指します。

ハードリミット: システムが同時に開くことができるファイルの最大数は、システムのハードウェア リソース (主にシステム ビデオ メモリ) に基づいて推定されます。

通常、ソフト制限はハード制限以上です

単一プロセスによって開かれるファイルの最大数の制限を変更する最も簡単な方法は、ulimit コマンドを使用することです:

[speng@as4~]$ulimit-n

上記のコマンドでは、単一プロセスが開くことを許可されるファイルの最大数を指定します。システムが「Operationnotpermitted」のようなメッセージをエコーする場合、実際には、手元で指定した値が、ユーザーが開いたファイルの数に対する Linux システムのソフト制限またはハード制限を超えているため、上記の制限の変更が失敗したことを意味します。したがって、ユーザーが開くファイルの数に関する Linux システムのソフト制限とハード制限を変更する必要があります。

最初のステップは、/etc/security/limits.conf ファイルを変更し、次の行をファイルに追加することです。

spengsoftnofile10240

spenghardnofile10240

speng specifies the limit on the number of open files for that user to be changed. The '*' sign can be used to indicate changing the limit for all users;

soft or hard specifies whether to change the soft limit or the hard limit; 10240 specifies the new limit value you want to change, that is, the maximum number of open files (please note that the soft limit value must be greater than or equal to the hard limit). Save the file after making changes.

The second step is to change the /etc/pam.d/login file and add the following lines to the file:

sessionrequired/lib/security/pam_limits.so This tells Linux that after the user completes the system login, the pam_limits.so module should be called to set the system’s maximum limit on the number of various resources that the user can use (including the maximum number of resources that the user can open) file number limit), and the pam_limits.so module will read the configuration from the /etc/security/limits.conf file to set this limit value. Save this file after making changes.

The third step is to check the Linux system-level limit on the maximum number of open files, use the following command:

[speng@as4~]$cat/proc/sys/fs/file-max

12158

This shows that this Linux system can allow up to 12158 files to be opened at the same time (that is, including the total number of files opened by all users), which is a Linux system-level hard limit. All user-level limits on the number of open files should not exceed this value. Generally, this system-level hard limit is the best maximum limit on the number of files opened at the same time based on the system hardware resources when the Linux system is started. If there is no special need, this limit should not be changed unless you want to limit the number of files opened at the user level. Set a value that exceeds this limit.

The way to change this hard limit is to change the /etc/rc.local script and add the following line to the script:

linux tcp连接数限制_限制连接数的固件_限制连接数量

echo22158>/proc/sys/fs/file-max

This is to force Linux to set the system-level hard limit on the number of open files to 22158 after the startup is completed. Save this file after the change.

After completing the above steps, restart the system. Normally, you can set the maximum number of files that the Linux system allows a single process of a specified user to open at the same time to a specified value. If after restarting, you use the ulimit-n command to check that the limit on the number of files that a user can open is always higher than the maximum value set in the above steps, this may be because the ulimit-n command in the user login script /etc/profile has already disabled the number of files that the user can open at the same time. The number of files is limited. Because when you use ulimit-n to change the system's limit on the maximum number of files that a user can open at the same time, the new changed value can only be greater than or equal to the value previously set by ulimit-n. Therefore, it is impossible to use this command to reduce this limit value. .

So, if the above problem exists, you can only open the /etc/profile script file and search in the file to see if ulimit-n is used to limit the maximum number of files that the user can open at the same time. If found, delete this line command, or change the value set to an appropriate value, save the file, and then the user can exit and log in to the system again. Through the above steps, the system limit on the number of open files is lifted for the communication processing program that supports high-concurrency TCP connection processing.

2. Modify the network kernel’s restrictions on TCP connections

When writing a client communication handler on Linux that supports high-concurrency TCP connections, you sometimes find that although the system has lifted the limit on the number of files users can open at the same time, there will still be problems when the number of concurrent TCP connections drops to a certain number. It also fails to successfully establish a new TCP connection. There are many reasons for these occurrences.

첫 번째 이유는 Linux 네트워크 커널이 로컬 포트 ​​번호 범위에 제한이 있기 때문일 수 있습니다. 이때 TCP 연결을 완료할 수 없는 이유를 자세히 분석해 보면 connect() 호출이 반환되지 않는 것이 문제라는 것을 알 수 있습니다. 동시에, "요청한 주소를 할당할 수 없습니다." 이때 tcpdump 도구를 사용하여 네트워크를 모니터링하면 TCP 연결 중에 클라이언트가 SYN 패킷을 보낼 네트워크 트래픽이 없는 것으로 나타났습니다. 이 상황은 문제가 로컬 Linux 시스템 커널의 제한 사항에 있음을 나타냅니다.

문제의 근본 원인은 Linux 커널의 TCP/IP 계약 구현 모듈이 시스템의 모든 클라이언트 TCP 연결에 해당하는 로컬 포트 ​​번호 범위를 제한한다는 것입니다(예: 커널은 로컬 포트 ​​범위를 제한합니다) 숫자는 1024~32768 사이). 특정 시간에 시스템에 너무 많은 TCP 클라이언트 연결이 있는 경우, 각 TCP 클라이언트 연결이 고유한 로컬 포트 ​​번호를 차지하기 때문에(이 포트 번호는 시스템의 로컬 포트 ​​번호 범위 제한 내에 있음) 일부 TCP 클라이언트 연결에 모든 로컬 포트 ​​번호를 점유하고 있으며 새 TCP 클라이언트 연결을 위한 로컬 포트 ​​번호를 할당하기가 어렵습니다. 이러한 이유로 시스템은 이러한 경우에 connect() 호출을 반환하고 오류 메시지를 "Can"으로 설정합니다. '요청된 주소 할당'.

이 제어 로직의 경우 Linux 커널 소스 코드를 볼 수 있습니다. linux2.6 커널을 예로 들면 tcp_ipv4.c 파일에서 다음 기능을 볼 수 있습니다.

staticinttcp_v4_hash_connect(structsock*sk)

위 함수에서 sysctl_local_port_range 변수에 대한 액세스 제어를 참고하세요. sysctl_local_port_range 변수의 초기화는 tcp.c 파일의 다음 함수에서 설정됩니다.

void__inittcp_init(무효)

커널 컴파일 시 설정된 기본 로컬 포트 ​​번호 범위가 너무 작을 수 있으므로 이 로컬 포트 ​​범위 제한을 변경해야 합니다.

첫 번째 단계는 /etc/sysctl.conf 파일을 변경하여 Linux 시스템 이미지를 다운로드하고 파일에 다음 줄을 추가하는 것입니다.

net.ipv4.ip_local_port_range=102465000

이는 시스템의 로컬 포트 ​​범위 제한이 1024~65000 사이로 설정되어 있음을 나타냅니다. 로컬 포트 ​​범위의 최소값은 1024보다 작거나 같아야 하며 포트 범위의 최대값은 65535보다 크거나 같아야 합니다. 변경한 후 이 파일을 저장하십시오.

두 번째 단계는 sysctl 명령을 실행하는 것입니다:

限制连接数量_限制连接数的固件_linux tcp连接数限制

[speng@as4~]$sysctl-p

시스템에 오류 메시지가 없으면 새 로컬 포트 ​​범위가 성공적으로 설정되었음을 의미합니다. 위의 포트 범위에 따라 설정하면 이론적으로 단일 프로세스가 동시에 60,000개 이상의 TCP 클라이언트 연결을 완료할 수 있습니다.

TCP 연결 완료에 실패하는 두 번째 이유는 Linux 네트워크 커널의 방화벽에 추적되는 최대 TCP 연결 수에 제한이 있기 때문일 수 있습니다. 이때 프로그램은 종료된 것처럼 connect() 호출에서 차단된 것으로 나타납니다. tcpdump 도구를 사용하여 네트워크를 모니터링하면 클라이언트가 SYN을 보낼 네트워크 트래픽도 없는 것을 알 수 있습니다. TCP 연결 중 패킷. 방화벽은 커널의 각 TCP 연결 상태를 추적하므로 추적 정보는 커널 메모리에 있는 conntrack 데이터베이스에 저장됩니다. 시스템에 TCP 연결이 너무 많으면 이 데이터베이스의 크기가 제한됩니다. 데이터베이스 용량이 부족하여 IP_TABLE이 새 TCP 연결에 대한 추적 정보를 구축하지 못하여 connect() 호출이 차단된 것으로 나타났습니다. 이 시점에서 추적되는 최대 TCP 연결 수에 대한 커널 제한을 변경해야 합니다. 이 기술은 로컬 포트 ​​번호 범위에 대한 커널 제한을 변경하는 것과 유사합니다.

첫 번째 단계는 /etc/sysctl.conf 파일을 변경하고 파일에 다음 줄을 추가하는 것입니다.

net.ipv4.ip_conntrack_max=10240

這表示將系統對最大追蹤的TCP聯接數限制設為10240.請注意,此限制值要盡量小,以節約對內核顯存的佔用。

第二步,執行sysctl指令:

[speng@as4~]$sysctl-p

假如係統沒有錯誤提示,就表示系統對新的最大追蹤的TCP連結數限制變更成功。如果依照上述參數進行設置,則理論上單獨一個進程最多可以同時完善10000多個TCP客戶端連接。

三、

使用支援高並發網路I/O的程式技術在Linux上編撰高並發TCP連接應用程式時,必須使用適當的網路I/O技術和I/O風波分派機制。可用的I/O技術有同步I/O,非阻塞式同步I/O(亦稱反應式I/O),以及異步I/O.在高TCP並發的情形下,假如使用同步I/O,這會嚴重阻塞程式的運轉,除非為每位TCP聯接的I/O建立一個執行緒。

然而linux tcp連線數限制,過多的執行緒又會因係統對執行緒的調度而造成巨大開支。為此,在高TCP並發的情況下使用同步I/O是不可取的,這時可以考慮使用非阻塞式同步I/O或非同步I/O.非阻塞式同步I/O的技術包括使用select (),poll(),epoll等機制。非同步I/O的技術就是使用AIO.

從I/O風波分派機制來看,使用select()是不合適的,由於它所支援的並發聯接數有限(一般在1024個以內)。假如考慮性能,poll()也是不合適的linux tcp連接數限制,雖然它可以支持的較高的TCP並發數,並且因為其採用"協程"機制,當並發數較高時,其運行效率相當低,並可能存在I/O風波分派不均,造成部份TCP連結上的I/O出現"飢餓"現象。而假如使用epoll或AIO,則沒有上述問題(初期Linux核心的AIO技術實作是透過在內核中為每位I/O懇求創建一個線程來實現的,這些實現機制在高並發TCP聯接的情況下使用似乎也有嚴重的效能問題。

綜上所述,在開發支援高並發TCP聯接的Linux應用程式時,應盡量使用epoll或AIO技術來實現並發的TCP聯接上的I/O控制,這將為提高程序對高並發TCP聯接的支援提供有效的I/O保證。

核心參數sysctl.conf的最佳化

/etc/sysctl.conf是拿來控制linux網路的設定文件,對於依賴網路的程式(如web伺服器和cache伺服器)十分重要,RHEL預設提供的最好調整。

建議設定(把原/etc/sysctl.conf內容清除,把下邊內容複製進去):

限制连接数量_限制连接数的固件_linux tcp连接数限制

cp/etc/sysctl.conf/etc/sysctl.conf.bak

echo"">/etc/sysctl.conf

vim/etc/sysctl.conf

net.ipv4.ip_local_port_range=102465535

net.core.rmem_max=16777216

net.core.wmem_max=16777216

net.ipv4.tcp_rmem=409687380167777216

net.ipv4.tcp_wmem=40966553616777216

net.ipv4.tcp_fin_timeout=10

net.ipv4.tcp_tw_recycle=1

net.ipv4.tcp_timestamps=0

net.ipv4.tcp_window_scaling=0

net.ipv4.tcp_sack=0

dev_max_backlog=30000

net.ipv4.tcp_no_metrics_save=1

net.core.somaxconn=10240

net.ipv4.tcp_syncookies=0

限制连接数量_linux tcp连接数限制_限制连接数的固件

net.ipv4.tcp_max_orphans=262144

net.ipv4.tcp_max_syn_backlog=262144

net.ipv4.tcp_synack_retries=2

net.ipv4.tcp_syn_retries=2

본 구성은 캐시 서버 바니시 권장 구성과 썬원 서버 시스템 최적화 권장 구성을 의미합니다.

그러나 Varnish에서 권장하는 구성에는 문제가 있습니다. 실제 작동에서는 "net.ipv4.tcp_fin_timeout=3" 구성으로 인해 네티즌이 웹사이트를 방문한 후 IE6 브라우저를 사용할 때 종종 페이지가 열리지 않는 것으로 나타났습니다. 해당 기간 동안 모든 웹페이지를 열 수 없으며 브라우저를 다시 시작한 후에는 정상적으로 작동됩니다. 미국의 인터넷 속도가 빠르기 때문일 수도 있지만, 우리 국가 상황에 따라 "net.ipv4.tcp_fin_timeout=10"을 조정해야 한다고 판단합니다. 10초의 경우 모든 것이 정상입니다(실제 동작 추론).

변경이 완료된 후 다음을 실행하세요.

sysctl-p/etc/sysctl.conf

sysctl-wnet.ipv4.route.flush=1

명령이 적용됩니다. 안전을 위해 시스템을 재부팅할 수도 있습니다.

열린 파일 핸들의 최대 수를 조정합니다(단일 프로세스의 최대 TCP 연결 수 = 단일 프로세스의 최대 소켓 연결 수):

Linux 시스템의 네트워크를 최적화한 후 대규모 동시성을 지원하려면 시스템에서 열 수 있는 파일 수를 늘려야 합니다. 기본 1024로는 충분하지 않습니다.

실행 명령:

쉘 코드

echo "ulimit-HSn65536">>/etc/rc.local

echo "ulimit-HSn65536">>/root/.bash_profile

ulimit-HSn65535

위 내용은 높은 동시성에서 웹 서버 및 캐시 서버에 대한 최대 소켓 연결 제한 수를 조정하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.