Your nginx workers start returning 502s at 2 AM. The error log shows accept4() failed (24: Too many open files). You restart the service and it works for three hours, then dies again. You need to find what's leaking file descriptors before the next spike, not just paper over the limit.
The 5-minute setup
First, confirm the process is actually at its FD limit. Replace <PID> with the main process PID (get it with pgrep -x nginx):
# Count currently open FDs for the process
ls /proc/<PID>/fd | wc -l
# Check the hard and soft limits for that specific process
cat /proc/<PID>/limits | grep "open files"
If the count is approaching the soft limit, you've confirmed the problem. Now find what is leaking:
# List all open FDs with their targets (sockets, pipes, files, etc.)
ls -l /proc/<PID>/fd | awk '{print $NF}' | sort | uniq -c | sort -rn | head -20
# If you suspect socket leaks specifically:
ls -l /proc/<PID>/fd | grep socket | wc -l
# Cross-reference with actual connections in TIME_WAIT or CLOSE_WAIT:
ss -tnp | grep "pid=<PID>" | awk '{print $1}' | sort | uniq -c
Once you've identified the leak source, raise the limit properly at the systemd level (not via ulimit in a shell, which won't survive restarts):
# Edit the unit file (e.g., /etc/systemd/system/nginx.service.d/override.conf)
mkdir -p /etc/systemd/system/nginx.service.d
cat > /etc/systemd/system/nginx.service.d/limits.conf <<'EOF'
[Service]
LimitNOFILE=65536
EOF
systemctl daemon-reload
systemctl restart nginx
Why it works
Linux tracks open file descriptors per process, and the default soft limit on most distros is 1024 or 4096. Every socket, pipe, eventfd, and open file consumes one. A connection leak (e.g., an upstream not closing keep-alive connections properly) silently consumes FDs until the process can no longer accept() new connections. The /proc/<PID>/fd directory gives you a live view of exactly what's consuming slots, and LimitNOFILE in the systemd unit raises the ceiling at the kernel level for that specific service without affecting the global fs.file-max or other processes.
Pro Tip
Set up a quick alert that catches the problem before it causes outages — add this to your monitoring or a cron job:
# Alert when any process exceeds 80% of its FD limit
for pid in $(pgrep -x nginx); do
used=$(ls /proc/$pid/fd 2>/dev/null | wc -l)
limit=$(awk '/Max open files/ {print $4}' /proc/$pid/limits)
pct=$(( used * 100 / limit ))
if [ "$pct" -ge 80 ]; then
echo "ALERT: PID $pid at ${pct}% FD usage ($used/$limit)" | logger -t fd-monitor
fi
done
Gotcha: If you see CLOSE_WAIT sockets piling up in ss, the leak is on your side — your application opened a connection and never called close(). If you see TIME_WAIT piling up, that's normal TCP behavior (2×MSL wait) and usually resolves itself; only worry if the total count exceeds your FD budget.