0
0
NginxHow-ToBeginner · 3 min read

How to Tune Worker Connections in Nginx for Better Performance

To tune worker_connections in Nginx, set the worker_connections directive inside the events block in your nginx.conf file. This value controls the maximum number of simultaneous connections each worker process can handle, so increase it based on your server capacity and expected traffic.
📐

Syntax

The worker_connections directive is placed inside the events block in the nginx.conf file. It defines the maximum number of simultaneous connections a single worker process can handle.

  • worker_connections: Number of connections per worker process.
  • events: Context where worker_connections is set.
nginx
events {
    worker_connections 1024;
}
💻

Example

This example shows how to set worker_connections to 2048 inside the events block. This allows each worker process to handle up to 2048 simultaneous connections, improving the server's ability to manage many clients at once.

nginx
events {
    worker_connections 2048;
}

http {
    server {
        listen 80;
        server_name example.com;

        location / {
            root /usr/share/nginx/html;
            index index.html;
        }
    }
}
Output
Nginx starts successfully and can handle up to 2048 connections per worker process.
⚠️

Common Pitfalls

Common mistakes when tuning worker_connections include:

  • Setting worker_connections too low, limiting concurrent connections and causing slow responses.
  • Ignoring the worker_processes setting, which multiplies the total connections capacity.
  • Not adjusting the system's file descriptor limits (ulimit), which can block Nginx from opening enough connections.

Always check and increase the OS limits if needed.

nginx
events {
    worker_connections 512;  # Too low for high traffic
}

# Correct approach
events {
    worker_connections 4096;
}
📊

Quick Reference

DirectiveDescriptionDefault ValueRecommended Tuning
worker_connectionsMax connections per worker process1024Increase based on traffic and server capacity
worker_processesNumber of worker processesautoSet to number of CPU cores
ulimit -nMax open files per process (OS limit)1024 or system defaultIncrease to support high connections

Key Takeaways

Set worker_connections inside the events block to control max connections per worker.
Combine worker_connections with worker_processes to calculate total concurrent connections.
Ensure OS file descriptor limits (ulimit) are high enough to support your settings.
Increase worker_connections based on expected traffic and server resources.
Restart Nginx after changes to apply new connection limits.