Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux 資源限制完全指南:ulimit、limits.conf、PAM 與系統級調優實戰

編輯:Linux 教學

Linux 對每個使用者、每個進程都施加資源配額。預設值(如開檔數 1024)在高併發、大型資料庫、微服務叢集下極易成為瓶頸。本文系統梳理 ulimit 暫時/永久調整、/etc/security/limits.conf 系統級配置、PAM 模組載入、以及 Solaris 對照參考。

ulimit:會話級暫時調整

ulimit -a          # 查看所有限制
ulimit -n 4096     # 開啟檔案描述符上限
ulimit -u 10000    # 最大進程數
ulimit -d unlimited # 資料段
ulimit -m unlimited # 住留記憶體
ulimit -s unlimited # 堆疊大小
ulimit -t unlimited # CPU 時間
ulimit -v unlimited # 虛擬記憶體
  • -H 硬限制(root 可提高,一般使用者只能降低)
  • -S 軟限制(使用者可在硬限制內自由調整)

永久生效:三層配置策略

1. /etc/security/limits.conf(推薦,系統級)

# 格式:   
*           soft    nofile      65535
*           hard    nofile      65535
*           soft    nproc       65535
*           hard    nproc       65535
root        soft    nofile      100000
root        hard    nofile      100000
@docker     soft    nofile      100000
@docker     hard    nofile      100000
  • * 所有使用者,@group 群組,user 單一使用者
  • nofile 開檔數,nproc 進程數

2. PAM 確保限制生效

# /etc/pam.d/login
session required pam_limits.so

# /etc/pam.d/system-auth (RHEL/CentOS) 或 /etc/pam.d/common-session (Debian/Ubuntu)
session required pam_limits.so

缺少此行,limits.conf 設定不會被讀取。

3. /etc/profile 或使用者 ~/.bash_profile(登入 Shell)

ulimit -n 65535
ulimit -u 65535

僅對登入 Shell 有效,非登入 Shell(如 su -s /bin/bash、systemd 服務)不生效。

systemd 服務專屬限制

# /etc/systemd/system/myservice.service
[Service]
LimitNOFILE=65535
LimitNPROC=65535
LimitMEMLOCK=infinity

執行 systemctl daemon-reload 後重啟服務生效,優先級高於 limits.conf。

驗證生效

# 以目標使用者身分
su - appuser -c "ulimit -a"
# 或查看進程實際限制
cat /proc/$(pgrep -f java)/limits

Solaris 對照(歷史參考)

  • rlim_fd_cur(軟)、rlim_fd_max(硬)對應 /etc/system
  • 32 位程式受限 256 描述符,需 gcc -m64 編譯 64 位突破

資源限制調優鐵律:先測量基線 → 依錯誤日誌調整 → 驗證生效 → 壓測確認。切勿盲目設 unlimited,需留給核心防禦資源耗盡的餘地。

Copyright © Windows教程網 All Rights Reserved