0
0
NginxHow-ToBeginner · 3 min read

How to Tune Worker Processes in Nginx for Optimal Performance

To tune worker_processes in Nginx, set it to the number of CPU cores available for best performance using worker_processes auto;. This allows Nginx to create one worker per CPU core, maximizing concurrency and resource utilization.
📐

Syntax

The worker_processes directive defines how many worker processes Nginx will spawn to handle client requests. Setting it properly helps Nginx use system resources efficiently.

  • worker_processes auto;: Automatically sets the number of workers to the number of CPU cores.
  • worker_processes 4;: Manually sets 4 worker processes.
nginx
worker_processes auto;
💻

Example

This example shows how to configure Nginx to automatically set worker processes based on CPU cores and tune related settings for better performance.

nginx
worker_processes auto;
events {
    worker_connections 1024;
}
http {
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
}
Output
Nginx starts with one worker process per CPU core, each handling up to 1024 connections concurrently.
⚠️

Common Pitfalls

Common mistakes when tuning worker_processes include:

  • Setting worker_processes higher than CPU cores, causing unnecessary context switching and overhead.
  • Using a fixed number without considering the server's CPU count.
  • Ignoring worker_connections, which limits how many connections each worker can handle.

Always pair worker_processes with appropriate worker_connections for optimal throughput.

nginx
# worker_processes 8;  # Wrong if server has 4 cores
worker_processes auto; # Correct for automatic tuning
📊

Quick Reference

DirectiveDescriptionRecommended Setting
worker_processesNumber of worker processesauto (matches CPU cores)
worker_connectionsMax connections per worker1024 or higher depending on load
sendfileEnable efficient file transferon
tcp_nopushOptimize packet sendingon
keepalive_timeoutTimeout for keep-alive connections65

Key Takeaways

Set worker_processes to auto to match CPU cores automatically.
Avoid setting more workers than CPU cores to prevent overhead.
Pair worker_processes with adequate worker_connections for concurrency.
Use related performance directives like sendfile and tcp_nopush for better throughput.
Test changes under load to find the best tuning for your specific server.