NGINX Server Failing to Handle Certain Number of New Connections on Ubuntu VM

Abstract: Resolve NGINX connection failures on Ubuntu by increasing file descriptor limits and kernel network parameters to prevent resource exhaustion.

Created: 2026-10-20 by

NGINX failing to accept new connections on an Ubuntu VM is typically caused by exhausted system file descriptors, kernel network limits, or application-level timeouts rather than a DDoS attack. The solution involves increasing ulimit values, adjusting net.core.somaxconn, and verifying upstream health checks to ensure the server can sustain the expected load without dropping packets.

Understanding Connection Limits in NGINX

When an NGINX server stops accepting new connections, it often returns a 502 Bad Gateway or 504 Gateway Timeout error, or simply hangs until the client times out. This behavior indicates that the web server process itself is still running but has reached a bottleneck preventing it from establishing new sockets. On an Ubuntu Virtual Machine (VM), these bottlenecks are frequently related to resource allocation limits imposed by the operating system or the hypervisor, rather than malicious traffic. It is crucial to distinguish between a genuine Distributed Denial of Service (DDoS) attack and legitimate traffic hitting infrastructure limits. While DDoS attacks can overwhelm servers, many administrators incorrectly diagnose simple connection drops as attacks when the root cause is actually misconfigured system limits. Idle resources or high latency do not necessarily indicate an active attack; they often signal that the kernel’s network stack is saturated or that file descriptor tables are full. Therefore, troubleshooting should begin with local configuration audits before implementing complex firewall rules or DDoS mitigation services. For more context on managing NGINX configurations on Ubuntu, you might find it useful to read about Why is my domain URL still rendering a 404 page after uninstalling nginx? which covers common service state issues. Additionally, understanding how your React and Express applications communicate through NGINX can help isolate whether the issue lies in the proxy layer or the backend, as discussed in Troubleshooting React/Express on Nginx/Ubuntu.

Increasing File Descriptor Limits

One of the most common reasons for connection failures is hitting the maximum number of open files allowed by the OS. Each incoming connection requires a file descriptor. If the limit is too low, NGINX will refuse new connections even if CPU and memory are available. First, check the current limit for the NGINX user by running:
cat /proc/$(pidof nginx)/limits | grep "Max open files"
If this value is low (e.g., 1024), you need to increase it. Edit the /etc/security/limits.conf file and add the following lines:
nginx soft nofile 65535
nginx hard nofile 65535
You must also update the systemd service definition to override these defaults. Create or edit /etc/systemd/system/nginx.service.d/override.conf and add:
[Service]
LimitNOFILE=65535
After saving, reload the systemd daemon and restart NGINX:
sudo systemctl daemon-reload
sudo systemctl restart nginx
Verify the change by checking the process limits again. This adjustment allows NGINX to handle thousands of simultaneous connections without exhausting the file table.

Adjusting Kernel Network Parameters

Beyond file descriptors, the Linux kernel has specific parameters controlling how many pending connections can be queued for acceptance. If this queue fills up, new TCP handshakes are dropped immediately. Check the current setting for somaxconn using:
sysctl net.core.somaxconn
The default is often 128, which is insufficient for high-traffic servers. Increase this value to 4096 or higher by adding the following line to /etc/sysctl.conf:
net.core.somaxconn = 4096
Apply the changes immediately with:
sudo sysctl -p
Additionally, ensure that the backlog queue in your NGINX configuration matches this kernel limit. In your server block or http block, set:
listen 80 backlog=4096;
This alignment ensures that the OS and NGINX agree on the maximum queue depth, preventing silent packet drops during traffic spikes.

Troubleshooting Upstream Timeouts

Sometimes the issue is not with NGINX itself but with the backend application it proxies to. If the upstream server (like Node.js, Python, or PHP-FPM) takes too long to respond, NGINX may close the connection or return a timeout error, making it appear as though it cannot handle new requests. Review your NGINX configuration for proxy_read_timeout and proxy_connect_timeout directives. Default values are often set to 60 seconds, which may be too short for complex backend operations. Increase these values if necessary:
proxy_read_timeout 300s;
proxy_connect_timeout 300s;
Monitor the backend logs to see if processes are crashing or hanging. If the backend is restarting frequently due to memory leaks, NGINX will fail to connect because the upstream socket is unavailable. Use tools like htop or free -m to monitor VM memory usage, ensuring the guest OS has sufficient RAM allocated. For tips on optimizing your Ubuntu VM environment, consider reviewing Run Ubuntu VM Guest without Installation to understand resource constraints better.

Verifying Firewall and Security Groups

Finally, ensure that the underlying firewall is not interfering with new connections. On Ubuntu, ufw (Uncomplicated Firewall) is commonly used. Check its status with:
sudo ufw status
Ensure that port 80 (HTTP) and 443 (HTTPS) are allowed. If you are using a cloud provider, verify that the security group or firewall rules associated with the VM instance permit inbound traffic on these ports. Misconfigured security groups can sometimes allow existing connections while blocking new ones, leading to intermittent failures.

Frequently Asked Questions

How do I know if my NGINX server is under a DDoS attack?

A true DDoS attack usually shows up as a massive spike in traffic from many different IP addresses, often with identical request patterns. If you see high CPU usage combined with normal traffic levels and connection refusals, it is likely a configuration limit issue rather than an attack.

What causes the "Too Many Open Files" error in NGINX?

This error occurs when the operating system reaches its limit for simultaneously open file descriptors. Since each network connection consumes a file descriptor, exceeding this limit prevents NGINX from accepting new clients. Increasing the nofile limit in limits.conf resolves this.

Why does my NGINX return 502 Bad Gateway errors randomly?

Random 502 errors often indicate that the upstream backend server is temporarily unavailable or overloaded. This can happen if the backend crashes, runs out of memory, or fails to respond within the configured timeout period. Checking backend logs is essential to confirm this.

Can I fix connection issues without restarting NGINX?

While some settings like sysctl parameters can be applied dynamically without a full restart, changing file descriptor limits or major configuration blocks usually requires reloading or restarting the service. Always test changes in a staging environment first to avoid downtime.

How does the backlog parameter affect NGINX performance?

The backlog parameter defines the maximum length of the queue for partially completed TCP connections. If the backlog is too small, new connections may be rejected during traffic spikes even if the server has capacity. Aligning this with net.core.somaxconn ensures optimal handling of concurrent requests.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More