Error Too many open files เกิดเมื่อ Process เปิด File Descriptors เกิน Limit (Default: 1024 per process/user) พบบ่อยใน Web Server (Nginx/Apache) และ Database (MySQL/PostgreSQL) ที่ High Load
ตรวจสอบ Limit ปัจจุบัน
cat /proc/sys/fs/file-max # System-wide Max
ulimit -n # Soft Limit (Current User) = 1024
ulimit -Sn # Soft Limit
ulimit -Hn # Hard Limit
ดู Limit ของ Process ที่รันอยู่ (PID): cat /proc/PID/limits | grep "Max open files"
เพิ่ม Limit ทั่วระบบ (Permanent)
แก้ไข /etc/security/limits.conf:
* hard nofile 97816
* soft nofile 97816
Ubuntu ต้องเพิ่มใน /etc/pam.d/common-session: session required pam_limits.so
Re-login/Restart Shell แล้วตรวจสอบ: ulimit -n → 97816
เพิ่ม Limit สำหรับ Service เฉพาะ (systemd)
ตัวอย่าง Apache (httpd):
systemctl edit httpd.service
# ใส่:
[Service]
LimitNOFILE=16000
LimitNOFILESoft=16000
systemctl daemon-reload
systemctl restart httpd
# Verify
systemctl status httpd # หา PID
cat /proc/PID/limits | grep "Max open files"
ตั้งค่าเฉพาะ Nginx และ Apache
Nginx (/etc/nginx/nginx.conf):
worker_rlimit_nofile 16000;
# สำหรับ 8 Cores, worker_connections 8192:
# worker_rlimit_nofile = 8192 * 2 * 8 = 131072
Restart: systemctl restart nginx
Apache (Systemd Drop-in):
mkdir -p /lib/systemd/system/httpd.service.d/
nano /lib/systemd/system/httpd.service.d/limit_nofile.conf
[Service]
LimitNOFILE=16000
systemctl daemon-reload
systemctl restart httpd
เปลี่ยน Limit สำหรับ Session ปัจจุบัน (Temporary)
ulimit -n 3000 # เปลี่ยน Soft Limit ใน Shell นี้เท่านั้น
เพิ่ม System-wide Kernel Limit
แก้ไข /etc/sysctl.conf:
fs.file-max = 100000
Apply: sysctl -p
สรุป
- User/Process Limit:
/etc/security/limits.conf+ PAM - Service Limit:
systemctl edit service+LimitNOFILE - App Config: Nginx
worker_rlimit_nofile, Apache Drop-in - Kernel Limit:
/etc/sysctl.conffs.file-max - ตรวจสอบด้วย
ulimit -nและ/proc/PID/limits