Website Vidya
UncategorizedStep-by-Step Guide

How to Fix Nginx “Too Many Open Files” Error (Complete Practical Guide)

If your Nginx server suddenly starts throwing the dreaded “too many open files” error, you’re not alone. This is one of those issues that usually appears only when your traffic grows , which makes it both frustrating and ironic—you’re doing...

RR
Rajesh RayLead Systems Educator
Published:
5 min read
PDF Cheat Sheet
How to Fix Nginx “Too Many Open Files” Error (Complete Practical Guide)
AI Executive SummaryCORE CIS AI

5 min read

If your Nginx server suddenly starts throwing the dreaded “too many open files” error, you’re not alone. This is one of those issues that usually appears only when your traffic grows , which makes it both frustrating and ironic—you’re doing...

Key Highlights
  • What Does “Too Many Open Files” Mean in Nginx?
  • Why This Error Is Dangerous If Ignored
  • Common Causes of the Nginx “Too Many Open Files” Error
Grounded in full engineering runbookCORE CIS Ai Engine

Interactive Builder for this Guide

Build your custom nginx syntax (How to Fix Nginx “Too Many Open Files” Error (Complete Practical Guide))

Generated Config Output
server {
    listen 80;
    listen [::]:80;
    server_name app.example.com;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name app.example.com;

    ssl_certificate /etc/letsencrypt/live/app.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/app.example.com/privkey.pem;

    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;

    gzip on;
    gzip_types text/plain text/css application/json application/javascript application/xml;

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}
Production Nginx reverse proxy -> 127.0.0.1:3000 for app.example.com.
Flag-by-Flag Breakdown
server_nameBinds this virtual host to app.example.com
return 301 https://...Redirects all plain HTTP requests permanently to TLS/HTTPS
proxy_pass http://127.0.0.1:3000Forwards HTTP + WebSocket requests to local application server
X-Content-Type-Options / X-Frame-OptionsProtects users against MIME sniffing and clickjacking

If your Nginx server suddenly starts throwing the dreaded “too many open files” error, you’re not alone. This is one of those issues that usually appears only when your traffic grows, which makes it both frustrating and ironic—you’re doing well, yet your server complains.

In this guide, I’ll walk you through how to fix Nginx “too many open files” error step by step, based on real-world server behavior, Linux internals, and production best practices. No vague theory, no copy-paste fluff—just practical fixes that actually work.

Whether you’re running Nginx on Ubuntu, Debian, CentOS, AlmaLinux, Rocky Linux, or Red Hat, the principles remain the same.


What Does “Too Many Open Files” Mean in Nginx?

At its core, this error means Nginx is trying to open more files or network connections than the operating system allows.

Advertisement

In Linux, everything is a file:

  • Network sockets
  • Log files
  • Static assets
  • Proxy connections
  • Temporary cache files

Each of these consumes a file descriptor (FD). When Nginx exceeds the allowed number of file descriptors, you’ll see errors like:

socket() failed (24: Too many open files)
accept4() failed (24: Too many open files)
open() "/var/log/nginx/access.log" failed (24: Too many open files)

At that point, Nginx can’t accept new connections—even though your CPU and RAM may look perfectly fine.


Why This Error Is Dangerous If Ignored

Ignoring this issue doesn’t just cause log spam. It leads to:

  • Dropped client connections
  • Random 502 / 504 errors
  • Partial site outages under load
  • Failed upstream connections (PHP-FPM, Node.js, APIs)
  • Crashes during traffic spikes

In high-traffic environments, this can turn into a silent performance killer.

Advertisement

Common Causes of the Nginx “Too Many Open Files” Error

Before fixing it, you should understand why it happens.

1. Low OS File Descriptor Limits

Linux enforces strict limits on how many files a process can open. These limits are often far lower than what Nginx needs.

2. Nginx Worker Processes Handling High Traffic

Each Nginx worker opens thousands of sockets under load. Multiply that by worker count, and you hit the ceiling quickly.

3. Misconfigured worker_connections

Even if system limits are high, Nginx itself may be artificially restricting connections.

4. Aggressive Logging

Access logs, error logs, and custom logs all consume file descriptors—especially with high request rates.

Advertisement

5. Keepalive Connections

Long-lived connections can quietly eat up file descriptors over time.


Step 1: Confirm the Problem (Don’t Guess)

Before changing anything, verify the limits.

Check current file descriptor limits

ulimit -n

If you see something like:

1024

That’s far too low for any production Nginx server.

Check Nginx worker limits

ps -o pid,cmd -C nginx

Then inspect open files per process:

ls /proc/<PID>/fd | wc -l

If workers are approaching the system limit, you’ve found the bottleneck.


Step 2: Increase System-Wide File Descriptor Limits

This is the most critical fix when learning how to fix Nginx “too many open files” error.

Edit /etc/security/limits.conf

sudo nano /etc/security/limits.conf

Add:

nginx   soft   nofile   65535
nginx   hard   nofile   65535

If Nginx runs as www-data, replace nginx accordingly.

Why this matters: This defines how many files the Nginx user can open, regardless of server power.


Step 3: Fix systemd Limits (Often Missed)

On modern Linux systems, systemd overrides traditional limits.

Edit the Nginx service file

sudo systemctl edit nginx

Add:

[Service]
LimitNOFILE=65535

Then reload:

sudo systemctl daemon-reexec
sudo systemctl restart nginx

This step alone fixes the issue for many production servers.


Step 4: Configure Nginx Worker Limits Correctly

Now let’s align Nginx with the OS.

Edit nginx.conf

sudo nano /etc/nginx/nginx.conf

Inside the events block:

worker_connections 8192;
use epoll;
multi_accept on;

And near the top:

worker_rlimit_nofile 65535;

Why this matters

  • worker_connections controls per-worker connections
  • worker_rlimit_nofile ensures workers can actually use higher limits

If you run 4 workers × 8192 connections, you’re already handling 32,768 concurrent connections.


Step 5: Adjust Kernel Limits (High-Traffic Servers)

For busy servers, Linux kernel defaults can still hold you back.

Edit:

sudo nano /etc/sysctl.conf

Add:

fs.file-max = 2097152
net.core.somaxconn = 65535
net.ipv4.ip_local_port_range = 1024 65000

Apply:

sudo sysctl -p

This ensures the OS itself isn’t the bottleneck.


Step 6: Optimize Logging to Reduce FD Usage

Excessive logging can silently exhaust file descriptors.

Disable access logs where not needed

access_log off;

Or use conditional logging:

access_log /var/log/nginx/access.log main if=$loggable;

Why this helps

Each log file is a file descriptor. On high-throughput APIs, logs can become the problem.


Step 7: Review Keepalive and Timeouts

Long keepalive connections are useful—but dangerous when misconfigured.

Recommended values:

keepalive_timeout 15;
keepalive_requests 1000;

For upstreams:

proxy_connect_timeout 10s;
proxy_read_timeout 30s;
proxy_send_timeout 30s;

This prevents zombie connections from consuming FDs indefinitely.


Step 8: Check Upstream Services (PHP-FPM, Node, APIs)

Sometimes Nginx is blamed unfairly.

PHP-FPM example

Check:

ulimit -n

And ensure:

rlimit_files = 65535

If upstreams hit their limits, Nginx connections pile up and trigger FD exhaustion.


Step 9: Monitor File Descriptor Usage in Real Time

Fixing the issue once isn’t enough—you need visibility.

Useful commands:

lsof -n | wc -l
cat /proc/sys/fs/file-nr

For long-term monitoring:

  • Prometheus + Node Exporter
  • Netdata
  • Datadog

Tracking FD usage helps you prevent future outages, not just react to them.


Common Mistakes to Avoid

  • Increasing worker_connections without raising OS limits
  • Forgetting systemd overrides
  • Setting extreme values without monitoring
  • Restarting Nginx but not reloading kernel parameters
  • Ignoring upstream service limits

These mistakes often cause the error to return weeks later.


Real-World Rule of Thumb (From Experience)

For most production servers:

  • File descriptor limit: 65,535 minimum
  • Worker connections: 8,000–16,000
  • Access logs: Disabled or minimized for APIs
  • Keepalive: Conservative, not infinite

Bigger numbers don’t mean better performance—balanced numbers do.


Final Thoughts

Learning how to fix Nginx “too many open files” error isn’t about blindly increasing limits—it’s about understanding how Nginx, Linux, and traffic patterns interact.

When configured correctly:

  • Nginx handles massive traffic gracefully
  • File descriptor exhaustion becomes a non-issue
  • Performance remains stable even during spikes

If you’re serious about running production-grade infrastructure, this is one optimization you should never skip.

RR
Written byVerified Author

Rajesh Ray

I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Uncategorized•

How to Redirect HTTP to HTTPS in Nginx

If you’re running a website today and it’s still accessible over plain HTTP, you’re already behind. Modern browsers flag non-HTTPS sites as “Not Secure,” search engines favor encrypted websites, and users are far more cautious about where t...

RR
Rajesh Rai
Read More
Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout